diff options
author | mike bayer <mike_mp@zzzcomputing.com> | 2020-04-14 19:48:20 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@bbpush.zzzcomputing.com> | 2020-04-14 19:48:20 +0000 |
commit | d9b230e78c70c17a6856f4ff3b8380b9ce510702 (patch) | |
tree | 3e1583daaa76cff27fbdf5de8b3b1f63c00a1225 /lib | |
parent | f39cf13680a0ee5b190d498d29ea31c76f546dfb (diff) | |
parent | cea03be855514d592b6671fa6dbc074a19a795fb (diff) | |
download | sqlalchemy-d9b230e78c70c17a6856f4ff3b8380b9ce510702.tar.gz |
Merge "Run search and replace of symbolic module names"
Diffstat (limited to 'lib')
77 files changed, 3643 insertions, 2702 deletions
diff --git a/lib/sqlalchemy/dialects/firebird/fdb.py b/lib/sqlalchemy/dialects/firebird/fdb.py index 46acd0559..7a7b87536 100644 --- a/lib/sqlalchemy/dialects/firebird/fdb.py +++ b/lib/sqlalchemy/dialects/firebird/fdb.py @@ -38,7 +38,7 @@ accept every argument that Kinterbasdb does. of Firebird, and setting this flag to False will also cause the SQLAlchemy ORM to ignore its usage. The behavior can also be controlled on a per-execution basis using the ``enable_rowcount`` option with - :meth:`.Connection.execution_options`:: + :meth:`_engine.Connection.execution_options`:: conn = engine.connect().execution_options(enable_rowcount=True) r = conn.execute(stmt) diff --git a/lib/sqlalchemy/dialects/mssql/base.py b/lib/sqlalchemy/dialects/mssql/base.py index 43f3aeb04..b5c49246f 100644 --- a/lib/sqlalchemy/dialects/mssql/base.py +++ b/lib/sqlalchemy/dialects/mssql/base.py @@ -18,8 +18,10 @@ SQL Server provides so-called "auto incrementing" behavior using the ``IDENTITY`` construct, which can be placed on any single integer column in a table. SQLAlchemy considers ``IDENTITY`` within its default "autoincrement" behavior for an integer primary key column, described at -:paramref:`.Column.autoincrement`. This means that by default, the first -integer primary key column in a :class:`.Table` will be considered to be the +:paramref:`_schema.Column.autoincrement`. This means that by default, +the first +integer primary key column in a :class:`_schema.Table` +will be considered to be the identity column and will generate DDL as such:: from sqlalchemy import Table, MetaData, Column, Integer @@ -41,7 +43,7 @@ The above example will generate DDL as: ) For the case where this default generation of ``IDENTITY`` is not desired, -specify ``False`` for the :paramref:`.Column.autoincrement` flag, +specify ``False`` for the :paramref:`_schema.Column.autoincrement` flag, on the first integer primary key column:: m = MetaData() @@ -51,8 +53,9 @@ on the first integer primary key column:: m.create_all(engine) To add the ``IDENTITY`` keyword to a non-primary key column, specify -``True`` for the :paramref:`.Column.autoincrement` flag on the desired -:class:`.Column` object, and ensure that :paramref:`.Column.autoincrement` +``True`` for the :paramref:`_schema.Column.autoincrement` flag on the desired +:class:`_schema.Column` object, and ensure that +:paramref:`_schema.Column.autoincrement` is set to ``False`` on any integer primary key column:: m = MetaData() @@ -62,7 +65,8 @@ is set to ``False`` on any integer primary key column:: m.create_all(engine) .. versionchanged:: 1.3 Added ``mssql_identity_start`` and - ``mssql_identity_increment`` parameters to :class:`.Column`. These replace + ``mssql_identity_increment`` parameters to :class:`_schema.Column`. + These replace the use of the :class:`.Sequence` object in order to specify these values. .. deprecated:: 1.3 @@ -85,7 +89,8 @@ is set to ``False`` on any integer primary key column:: marked with IDENTITY will be rejected by SQL Server. In order for the value to be accepted, a session-level option "SET IDENTITY_INSERT" must be enabled. The SQLAlchemy SQL Server dialect will perform this operation - automatically when using a core :class:`~.sql.expression.Insert` construct; if the + automatically when using a core :class:`_expression.Insert` + construct; if the execution specifies a value for the IDENTITY column, the "IDENTITY_INSERT" option will be enabled for the span of that statement's invocation.However, this scenario is not high performing and should not be relied upon for @@ -99,7 +104,7 @@ Controlling "Start" and "Increment" Specific control over the "start" and "increment" values for the ``IDENTITY`` generator are provided using the ``mssql_identity_start`` and ``mssql_identity_increment`` parameters -passed to the :class:`.Column` object:: +passed to the :class:`_schema.Column` object:: from sqlalchemy import Table, Integer, Column @@ -112,7 +117,7 @@ passed to the :class:`.Column` object:: Column('name', String(20)) ) -The CREATE TABLE for the above :class:`.Table` object would be: +The CREATE TABLE for the above :class:`_schema.Table` object would be: .. sourcecode:: sql @@ -123,7 +128,7 @@ The CREATE TABLE for the above :class:`.Table` object would be: .. versionchanged:: 1.3 The ``mssql_identity_start`` and ``mssql_identity_increment`` parameters are now used to affect the - ``IDENTITY`` generator for a :class:`.Column` under SQL Server. + ``IDENTITY`` generator for a :class:`_schema.Column` under SQL Server. Previously, the :class:`.Sequence` object was used. As SQL Server now supports real sequences as a separate construct, :class:`.Sequence` will be functional in the normal way in a future SQLAlchemy version. @@ -171,7 +176,8 @@ The process for fetching this value has several variants: A table that contains an ``IDENTITY`` column will prohibit an INSERT statement that refers to the identity column explicitly. The SQLAlchemy dialect will -detect when an INSERT construct, created using a core :func:`~.sql.expression.insert` +detect when an INSERT construct, created using a core +:func:`_expression.insert` construct (not a plain string SQL), refers to the identity column, and in this case will emit ``SET IDENTITY_INSERT ON`` prior to the insert statement proceeding, and ``SET IDENTITY_INSERT OFF`` subsequent to the @@ -213,7 +219,7 @@ MAX on VARCHAR / NVARCHAR ------------------------- SQL Server supports the special string "MAX" within the -:class:`.sqltypes.VARCHAR` and :class:`.sqltypes.NVARCHAR` datatypes, +:class:`_types.VARCHAR` and :class:`_types.NVARCHAR` datatypes, to indicate "maximum length possible". The dialect currently handles this as a length of "None" in the base type, rather than supplying a dialect-specific version of these types, so that a base type @@ -238,7 +244,7 @@ specified by the string argument "collation":: from sqlalchemy import VARCHAR Column('login', VARCHAR(32, collation='Latin1_General_CI_AS')) -When such a column is associated with a :class:`.Table`, the +When such a column is associated with a :class:`_schema.Table`, the CREATE TABLE statement for this column will yield:: login VARCHAR(32) COLLATE Latin1_General_CI_AS NULL @@ -291,7 +297,8 @@ both via a dialect-specific parameter accepted by :func:`.create_engine`, as well as the :paramref:`.Connection.execution_options.isolation_level` argument as passed to -:meth:`.Connection.execution_options`. This feature works by issuing the +:meth:`_engine.Connection.execution_options`. +This feature works by issuing the command ``SET TRANSACTION ISOLATION LEVEL <level>`` for each new connection. @@ -358,19 +365,22 @@ Per `SQL Server 2012/2014 Documentation <http://technet.microsoft.com/en-us/library/ms187993.aspx>`_, the ``NTEXT``, ``TEXT`` and ``IMAGE`` datatypes are to be removed from SQL Server in a future release. SQLAlchemy normally relates these types to the -:class:`.UnicodeText`, :class:`.Text` and :class:`.LargeBinary` datatypes. +:class:`.UnicodeText`, :class:`_expression.TextClause` and +:class:`.LargeBinary` datatypes. In order to accommodate this change, a new flag ``deprecate_large_types`` is added to the dialect, which will be automatically set based on detection of the server version in use, if not otherwise set by the user. The behavior of this flag is as follows: -* When this flag is ``True``, the :class:`.UnicodeText`, :class:`.Text` and +* When this flag is ``True``, the :class:`.UnicodeText`, + :class:`_expression.TextClause` and :class:`.LargeBinary` datatypes, when used to render DDL, will render the types ``NVARCHAR(max)``, ``VARCHAR(max)``, and ``VARBINARY(max)``, respectively. This is a new behavior as of the addition of this flag. -* When this flag is ``False``, the :class:`.UnicodeText`, :class:`.Text` and +* When this flag is ``False``, the :class:`.UnicodeText`, + :class:`_expression.TextClause` and :class:`.LargeBinary` datatypes, when used to render DDL, will render the types ``NTEXT``, ``TEXT``, and ``IMAGE``, respectively. This is the long-standing behavior of these types. @@ -391,9 +401,10 @@ behavior of this flag is as follows: * Complete control over whether the "old" or "new" types are rendered is available in all SQLAlchemy versions by using the UPPERCASE type objects - instead: :class:`.types.NVARCHAR`, :class:`.types.VARCHAR`, - :class:`.types.VARBINARY`, :class:`.types.TEXT`, :class:`.mssql.NTEXT`, - :class:`.mssql.IMAGE` will always remain fixed and always output exactly that + instead: :class:`_types.NVARCHAR`, :class:`_types.VARCHAR`, + :class:`_types.VARBINARY`, :class:`_types.TEXT`, :class:`_mssql.NTEXT`, + :class:`_mssql.IMAGE` + will always remain fixed and always output exactly that type. .. versionadded:: 1.0.0 @@ -406,7 +417,8 @@ Multipart Schema Names SQL Server schemas sometimes require multiple parts to their "schema" qualifier, that is, including the database name and owner name as separate tokens, such as ``mydatabase.dbo.some_table``. These multipart names can be set -at once using the :paramref:`.Table.schema` argument of :class:`.Table`:: +at once using the :paramref:`_schema.Table.schema` argument of +:class:`_schema.Table`:: Table( "some_table", metadata, @@ -609,7 +621,7 @@ generated primary key values via IDENTITY columns or other server side defaults. MS-SQL does not allow the usage of OUTPUT INSERTED on tables that have triggers. To disable the usage of OUTPUT INSERTED on a per-table basis, -specify ``implicit_returning=False`` for each :class:`.Table` +specify ``implicit_returning=False`` for each :class:`_schema.Table` which has triggers:: Table('mytable', metadata, @@ -645,8 +657,8 @@ verifies that the version identifier matched. When this condition occurs, a warning will be emitted but the operation will proceed. The use of OUTPUT INSERTED can be disabled by setting the -:paramref:`.Table.implicit_returning` flag to ``False`` on a particular -:class:`.Table`, which in declarative looks like:: +:paramref:`_schema.Table.implicit_returning` flag to ``False`` on a particular +:class:`_schema.Table`, which in declarative looks like:: class MyTable(Base): __tablename__ = 'mytable' @@ -1072,7 +1084,7 @@ class TIMESTAMP(sqltypes._Binary): .. seealso:: - :class:`.mssql.ROWVERSION` + :class:`_mssql.ROWVERSION` """ @@ -1117,7 +1129,7 @@ class ROWVERSION(TIMESTAMP): The ROWVERSION datatype does **not** reflect (e.g. introspect) from the database as itself; the returned datatype will be - :class:`.mssql.TIMESTAMP`. + :class:`_mssql.TIMESTAMP`. This is a read-only datatype that does not support INSERT of values. @@ -1125,7 +1137,7 @@ class ROWVERSION(TIMESTAMP): .. seealso:: - :class:`.mssql.TIMESTAMP` + :class:`_mssql.TIMESTAMP` """ @@ -1145,7 +1157,7 @@ class VARBINARY(sqltypes.VARBINARY, sqltypes.LargeBinary): This type is present to support "deprecate_large_types" mode where either ``VARBINARY(max)`` or IMAGE is rendered. Otherwise, this type - object is redundant vs. :class:`.types.VARBINARY`. + object is redundant vs. :class:`_types.VARBINARY`. .. versionadded:: 1.0.0 diff --git a/lib/sqlalchemy/dialects/mysql/base.py b/lib/sqlalchemy/dialects/mysql/base.py index a075b4d6b..e44dfa829 100644 --- a/lib/sqlalchemy/dialects/mysql/base.py +++ b/lib/sqlalchemy/dialects/mysql/base.py @@ -79,7 +79,8 @@ to ``MyISAM`` for this value, although newer versions may be defaulting to ``InnoDB``. The ``InnoDB`` engine is typically preferred for its support of transactions and foreign keys. -A :class:`.Table` that is created in a MySQL database with a storage engine +A :class:`_schema.Table` +that is created in a MySQL database with a storage engine of ``MyISAM`` will be essentially non-transactional, meaning any INSERT/UPDATE/DELETE statement referring to this table will be invoked as autocommit. It also will have no support for foreign key constraints; while @@ -122,7 +123,8 @@ All MySQL dialects support setting of transaction isolation level both via a dialect-specific parameter :paramref:`.create_engine.isolation_level` accepted by :func:`.create_engine`, as well as the :paramref:`.Connection.execution_options.isolation_level` argument as passed to -:meth:`.Connection.execution_options`. This feature works by issuing the +:meth:`_engine.Connection.execution_options`. +This feature works by issuing the command ``SET SESSION TRANSACTION ISOLATION LEVEL <level>`` for each new connection. For the special AUTOCOMMIT isolation level, DBAPI-specific techniques are used. @@ -174,7 +176,8 @@ foreign key:: ) You can disable this behavior by passing ``False`` to the -:paramref:`~.Column.autoincrement` argument of :class:`.Column`. This flag +:paramref:`_schema.Column.autoincrement` argument of :class:`_schema.Column`. +This flag can also be used to enable auto-increment on a secondary column in a multi-column key for some storage engines:: @@ -301,7 +304,8 @@ MySQL features two varieties of identifier "quoting style", one using backticks and the other using quotes, e.g. ```some_identifier``` vs. ``"some_identifier"``. All MySQL dialects detect which version is in use by checking the value of ``sql_mode`` when a connection is first -established with a particular :class:`.Engine`. This quoting style comes +established with a particular :class:`_engine.Engine`. +This quoting style comes into play when rendering table and column names as well as when reflecting existing database structures. The detection is entirely automatic and no special configuration is needed to use either quoting style. @@ -323,7 +327,8 @@ available. * INSERT..ON DUPLICATE KEY UPDATE: See :ref:`mysql_insert_on_duplicate_key_update` -* SELECT pragma, use :meth:`.Select.prefix_with` and :meth:`.Query.prefix_with`:: +* SELECT pragma, use :meth:`_expression.Select.prefix_with` and + :meth:`_query.Query.prefix_with`:: select(...).prefix_with(['HIGH_PRIORITY', 'SQL_SMALL_RESULT']) @@ -331,11 +336,13 @@ available. update(..., mysql_limit=10) -* optimizer hints, use :meth:`.Select.prefix_with` and :meth:`.Query.prefix_with`:: +* optimizer hints, use :meth:`_expression.Select.prefix_with` and + :meth:`_query.Query.prefix_with`:: select(...).prefix_with("/*+ NO_RANGE_OPTIMIZATION(t4 PRIMARY) */") -* index hints, use :meth:`.Select.with_hint` and :meth:`.Query.with_hint`:: +* index hints, use :meth:`_expression.Select.with_hint` and + :meth:`_query.Query.with_hint`:: select(...).with_hint(some_table, "USE INDEX xyz") @@ -379,7 +386,8 @@ from the proposed insertion. These values are normally specified using keyword arguments passed to the :meth:`~.mysql.Insert.on_duplicate_key_update` given column key values (usually the name of the column, unless it -specifies :paramref:`.Column.key`) as keys and literal or SQL expressions +specifies :paramref:`_schema.Column.key` +) as keys and literal or SQL expressions as values:: on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update( @@ -396,7 +404,8 @@ forms are accepted, including a single dictionary:: as well as a list of 2-tuples, which will automatically provide a parameter-ordered UPDATE statement in a manner similar to that described -at :ref:`updates_order_parameters`. Unlike the :class:`.Update` object, +at :ref:`updates_order_parameters`. Unlike the :class:`_expression.Update` +object, no special flag is needed to specify the intent since the argument form is this context is unambiguous:: @@ -412,9 +421,10 @@ this context is unambiguous:: .. warning:: - The :meth:`.Insert.on_duplicate_key_update` method does **not** take into + The :meth:`_expression.Insert.on_duplicate_key_update` + method does **not** take into account Python-side default UPDATE values or generation functions, e.g. - e.g. those specified using :paramref:`.Column.onupdate`. + e.g. those specified using :paramref:`_schema.Column.onupdate`. These values will not be exercised for an ON DUPLICATE KEY style of UPDATE, unless they are manually specified explicitly in the parameters. @@ -423,7 +433,7 @@ this context is unambiguous:: In order to refer to the proposed insertion row, the special alias :attr:`~.mysql.Insert.inserted` is available as an attribute on the :class:`.mysql.Insert` object; this object is a -:class:`.ColumnCollection` which contains all columns of the target +:class:`_expression.ColumnCollection` which contains all columns of the target table:: from sqlalchemy.dialects.mysql import insert @@ -586,7 +596,8 @@ Foreign Key Arguments to Avoid MySQL does not support the foreign key arguments "DEFERRABLE", "INITIALLY", or "MATCH". Using the ``deferrable`` or ``initially`` keyword argument with -:class:`.ForeignKeyConstraint` or :class:`.ForeignKey` will have the effect of +:class:`_schema.ForeignKeyConstraint` or :class:`_schema.ForeignKey` +will have the effect of these keywords being rendered in a DDL expression, which will then raise an error on MySQL. In order to use these keywords on a foreign key while having them ignored on a MySQL backend, use a custom compile rule:: @@ -601,7 +612,7 @@ them ignored on a MySQL backend, use a custom compile rule:: .. versionchanged:: 0.9.0 - the MySQL backend no longer silently ignores the ``deferrable`` or ``initially`` keyword arguments of - :class:`.ForeignKeyConstraint` and :class:`.ForeignKey`. + :class:`_schema.ForeignKeyConstraint` and :class:`_schema.ForeignKey`. The "MATCH" keyword is in fact more insidious, and is explicitly disallowed by SQLAlchemy in conjunction with the MySQL backend. This argument is @@ -613,7 +624,7 @@ ForeignKeyConstraint at DDL definition time. .. versionadded:: 0.9.0 - the MySQL backend will raise a :class:`.CompileError` when the ``match`` keyword is used with - :class:`.ForeignKeyConstraint` or :class:`.ForeignKey`. + :class:`_schema.ForeignKeyConstraint` or :class:`_schema.ForeignKey`. Reflection of Foreign Key Constraints ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -645,14 +656,16 @@ these constraints. However, MySQL does not have a unique constraint construct that is separate from a unique index; that is, the "UNIQUE" constraint on MySQL is equivalent to creating a "UNIQUE INDEX". -When reflecting these constructs, the :meth:`.Inspector.get_indexes` -and the :meth:`.Inspector.get_unique_constraints` methods will **both** +When reflecting these constructs, the +:meth:`_reflection.Inspector.get_indexes` +and the :meth:`_reflection.Inspector.get_unique_constraints` +methods will **both** return an entry for a UNIQUE index in MySQL. However, when performing full table reflection using ``Table(..., autoload=True)``, the :class:`.UniqueConstraint` construct is -**not** part of the fully reflected :class:`.Table` construct under any +**not** part of the fully reflected :class:`_schema.Table` construct under any circumstances; this construct is always represented by a :class:`.Index` -with the ``unique=True`` setting present in the :attr:`.Table.indexes` +with the ``unique=True`` setting present in the :attr:`_schema.Table.indexes` collection. @@ -1438,7 +1451,7 @@ class MySQLCompiler(compiler.SQLCompiler): .. note:: - this usage is deprecated. :meth:`.Select.prefix_with` + this usage is deprecated. :meth:`_expression.Select.prefix_with` should be used for special keywords at the start of a SELECT. diff --git a/lib/sqlalchemy/dialects/mysql/dml.py b/lib/sqlalchemy/dialects/mysql/dml.py index 531b31bc3..c19ed6c0b 100644 --- a/lib/sqlalchemy/dialects/mysql/dml.py +++ b/lib/sqlalchemy/dialects/mysql/dml.py @@ -31,12 +31,13 @@ class Insert(StandardInsert): This attribute provides all columns in this row to be referenceable such that they will render within a ``VALUES()`` function inside the ON DUPLICATE KEY UPDATE clause. The attribute is named ``.inserted`` - so as not to conflict with the existing :meth:`.Insert.values` method. + so as not to conflict with the existing + :meth:`_expression.Insert.values` method. .. seealso:: :ref:`mysql_insert_on_duplicate_key_update` - example of how - to use :attr:`.Insert.inserted` + to use :attr:`_expression.Insert.inserted` """ return self.inserted_alias.columns @@ -56,7 +57,7 @@ class Insert(StandardInsert): .. warning:: This dictionary does **not** take into account Python-specified default UPDATE values or generation functions, - e.g. those specified using :paramref:`.Column.onupdate`. + e.g. those specified using :paramref:`_schema.Column.onupdate`. These values will not be exercised for an ON DUPLICATE KEY UPDATE style of UPDATE, unless values are manually specified here. @@ -71,7 +72,8 @@ class Insert(StandardInsert): Passing a list of 2-tuples indicates that the parameter assignments in the UPDATE clause should be ordered as sent, in a manner similar - to that described for the :class:`.Update` construct overall + to that described for the :class:`_expression.Update` + construct overall in :ref:`updates_order_parameters`:: insert().on_duplicate_key_update( diff --git a/lib/sqlalchemy/dialects/mysql/json.py b/lib/sqlalchemy/dialects/mysql/json.py index 10354842f..733a4d696 100644 --- a/lib/sqlalchemy/dialects/mysql/json.py +++ b/lib/sqlalchemy/dialects/mysql/json.py @@ -17,7 +17,7 @@ class JSON(sqltypes.JSON): support JSON at the time of this writing. The :class:`.mysql.JSON` type supports persistence of JSON values - as well as the core index operations provided by :class:`.types.JSON` + as well as the core index operations provided by :class:`_types.JSON` datatype, by adapting the operations to render the ``JSON_EXTRACT`` function at the database level. diff --git a/lib/sqlalchemy/dialects/oracle/base.py b/lib/sqlalchemy/dialects/oracle/base.py index ae869b921..bbf65371c 100644 --- a/lib/sqlalchemy/dialects/oracle/base.py +++ b/lib/sqlalchemy/dialects/oracle/base.py @@ -61,7 +61,7 @@ of isolation, however the SQLAlchemy Oracle dialect currently only has explicit support for "READ COMMITTED". It is possible to emit a "SET TRANSACTION" statement on a connection in order to use SERIALIZABLE isolation, however the SQLAlchemy dialect will remain unaware of this setting, -such as if the :meth:`.Connection.get_isolation_level` method is used; +such as if the :meth:`_engine.Connection.get_isolation_level` method is used; this method is hardcoded to return "READ COMMITTED" right now. The AUTOCOMMIT isolation level is also supported by the cx_Oracle dialect. @@ -304,7 +304,7 @@ Synonym/DBLINK Reflection When using reflection with Table objects, the dialect can optionally search for tables indicated by synonyms, either in local or remote schemas or accessed over DBLINK, by passing the flag ``oracle_resolve_synonyms=True`` as -a keyword argument to the :class:`.Table` construct:: +a keyword argument to the :class:`_schema.Table` construct:: some_table = Table('some_table', autoload=True, autoload_with=some_engine, @@ -318,8 +318,8 @@ knows how to locate the table's information using DBLINK syntax(e.g. ``@dblink``). ``oracle_resolve_synonyms`` is accepted wherever reflection arguments are -accepted, including methods such as :meth:`.MetaData.reflect` and -:meth:`.Inspector.get_columns`. +accepted, including methods such as :meth:`_schema.MetaData.reflect` and +:meth:`_reflection.Inspector.get_columns`. If synonyms are not in use, this flag should be left disabled. @@ -332,18 +332,22 @@ The Oracle dialect can return information about foreign key, unique, and CHECK constraints, as well as indexes on tables. Raw information regarding these constraints can be acquired using -:meth:`.Inspector.get_foreign_keys`, :meth:`.Inspector.get_unique_constraints`, -:meth:`.Inspector.get_check_constraints`, and :meth:`.Inspector.get_indexes`. +:meth:`_reflection.Inspector.get_foreign_keys`, +:meth:`_reflection.Inspector.get_unique_constraints`, +:meth:`_reflection.Inspector.get_check_constraints`, and +:meth:`_reflection.Inspector.get_indexes`. .. versionchanged:: 1.2 The Oracle dialect can now reflect UNIQUE and CHECK constraints. -When using reflection at the :class:`.Table` level, the :class:`.Table` +When using reflection at the :class:`_schema.Table` level, the +:class:`_schema.Table` will also include these constraints. Note the following caveats: -* When using the :meth:`.Inspector.get_check_constraints` method, Oracle +* When using the :meth:`_reflection.Inspector.get_check_constraints` method, + Oracle builds a special "IS NOT NULL" constraint for columns that specify "NOT NULL". This constraint is **not** returned by default; to include the "IS NOT NULL" constraints, pass the flag ``include_all=True``:: @@ -355,11 +359,13 @@ Note the following caveats: all_check_constraints = inspector.get_check_constraints( "some_table", include_all=True) -* in most cases, when reflecting a :class:`.Table`, a UNIQUE constraint will +* in most cases, when reflecting a :class:`_schema.Table`, + a UNIQUE constraint will **not** be available as a :class:`.UniqueConstraint` object, as Oracle mirrors unique constraints with a UNIQUE index in most cases (the exception seems to be when two or more unique constraints represent the same columns); - the :class:`.Table` will instead represent these using :class:`.Index` + the :class:`_schema.Table` will instead represent these using + :class:`.Index` with the ``unique=True`` flag set. * Oracle creates an implicit index for the primary key of a table; this index @@ -371,11 +377,12 @@ Note the following caveats: Table names with SYSTEM/SYSAUX tablespaces ------------------------------------------- -The :meth:`.Inspector.get_table_names` and -:meth:`.Inspector.get_temp_table_names` +The :meth:`_reflection.Inspector.get_table_names` and +:meth:`_reflection.Inspector.get_temp_table_names` methods each return a list of table names for the current engine. These methods are also part of the reflection which occurs within an operation such as -:meth:`.MetaData.reflect`. By default, these operations exclude the ``SYSTEM`` +:meth:`_schema.MetaData.reflect`. By default, +these operations exclude the ``SYSTEM`` and ``SYSAUX`` tablespaces from the operation. In order to change this, the default list of tablespaces excluded can be changed at the engine level using the ``exclude_tablespaces`` parameter:: @@ -392,15 +399,15 @@ DateTime Compatibility Oracle has no datatype known as ``DATETIME``, it instead has only ``DATE``, which can actually store a date and time value. For this reason, the Oracle -dialect provides a type :class:`.oracle.DATE` which is a subclass of +dialect provides a type :class:`_oracle.DATE` which is a subclass of :class:`.DateTime`. This type has no special behavior, and is only present as a "marker" for this type; additionally, when a database column is reflected and the type is reported as ``DATE``, the time-supporting -:class:`.oracle.DATE` type is used. +:class:`_oracle.DATE` type is used. -.. versionchanged:: 0.9.4 Added :class:`.oracle.DATE` to subclass +.. versionchanged:: 0.9.4 Added :class:`_oracle.DATE` to subclass :class:`.DateTime`. This is a change as previous versions - would reflect a ``DATE`` column as :class:`.types.DATE`, which subclasses + would reflect a ``DATE`` column as :class:`_types.DATE`, which subclasses :class:`.Date`. The only significance here is for schemes that are examining the type of column for use in special Python translations or for migrating schemas to other database backends. @@ -411,7 +418,7 @@ Oracle Table Options ------------------------- The CREATE TABLE phrase supports the following options with Oracle -in conjunction with the :class:`.Table` construct: +in conjunction with the :class:`_schema.Table` construct: * ``ON COMMIT``:: @@ -584,7 +591,7 @@ class DATE(sqltypes.DateTime): """Provide the oracle DATE type. This type has no special Python behavior, except that it subclasses - :class:`.types.DateTime`; this is to suit the fact that the Oracle + :class:`_types.DateTime`; this is to suit the fact that the Oracle ``DATE`` type supports a time value. .. versionadded:: 0.9.4 diff --git a/lib/sqlalchemy/dialects/oracle/cx_oracle.py b/lib/sqlalchemy/dialects/oracle/cx_oracle.py index 0f41d7ed8..2cbf5b04a 100644 --- a/lib/sqlalchemy/dialects/oracle/cx_oracle.py +++ b/lib/sqlalchemy/dialects/oracle/cx_oracle.py @@ -97,8 +97,8 @@ as that the ``NLS_LANG`` environment variable is set appropriately, so that the VARCHAR2 and CLOB datatypes can accommodate the data. In the case that the Oracle database is not configured with a Unicode character -set, the two options are to use the :class:`.oracle.NCHAR` and -:class:`.oracle.NCLOB` datatypes explicitly, or to pass the flag +set, the two options are to use the :class:`_oracle.NCHAR` and +:class:`_oracle.NCLOB` datatypes explicitly, or to pass the flag ``use_nchar_for_unicode=True`` to :func:`.create_engine`, which will cause the SQLAlchemy dialect to use NCHAR/NCLOB for the :class:`.Unicode` / :class:`.UnicodeText` datatypes instead of VARCHAR/CLOB. @@ -260,12 +260,12 @@ Precision Numerics SQLAlchemy's numeric types can handle receiving and returning values as Python ``Decimal`` objects or float objects. When a :class:`.Numeric` object, or a -subclass such as :class:`.Float`, :class:`.oracle.DOUBLE_PRECISION` etc. is in +subclass such as :class:`.Float`, :class:`_oracle.DOUBLE_PRECISION` etc. is in use, the :paramref:`.Numeric.asdecimal` flag determines if values should be coerced to ``Decimal`` upon return, or returned as float objects. To make matters more complicated under Oracle, Oracle's ``NUMBER`` type can also represent integer values if the "scale" is zero, so the Oracle-specific -:class:`.oracle.NUMBER` type takes this into account as well. +:class:`_oracle.NUMBER` type takes this into account as well. The cx_Oracle dialect makes extensive use of connection- and cursor-level "outputtypehandler" callables in order to coerce numeric values as requested. diff --git a/lib/sqlalchemy/dialects/postgresql/array.py b/lib/sqlalchemy/dialects/postgresql/array.py index 9f0f676cd..a3537ba60 100644 --- a/lib/sqlalchemy/dialects/postgresql/array.py +++ b/lib/sqlalchemy/dialects/postgresql/array.py @@ -25,7 +25,7 @@ def Any(other, arrexpr, operator=operators.eq): .. seealso:: - :func:`.expression.any_` + :func:`_expression.any_` """ @@ -39,7 +39,7 @@ def All(other, arrexpr, operator=operators.eq): .. seealso:: - :func:`.expression.all_` + :func:`_expression.all_` """ @@ -68,14 +68,16 @@ class array(expression.Tuple): ARRAY[%(param_3)s, %(param_4)s, %(param_5)s]) AS anon_1 An instance of :class:`.array` will always have the datatype - :class:`.ARRAY`. The "inner" type of the array is inferred from + :class:`_types.ARRAY`. The "inner" type of the array is inferred from the values present, unless the ``type_`` keyword argument is passed:: array(['foo', 'bar'], type_=CHAR) Multidimensional arrays are produced by nesting :class:`.array` constructs. - The dimensionality of the final :class:`.ARRAY` type is calculated by - recursively adding the dimensions of the inner :class:`.ARRAY` type:: + The dimensionality of the final :class:`_types.ARRAY` + type is calculated by + recursively adding the dimensions of the inner :class:`_types.ARRAY` + type:: stmt = select([ array([ @@ -93,7 +95,7 @@ class array(expression.Tuple): .. seealso:: - :class:`.postgresql.ARRAY` + :class:`_postgresql.ARRAY` """ @@ -150,11 +152,11 @@ class ARRAY(sqltypes.ARRAY): """PostgreSQL ARRAY type. - .. versionchanged:: 1.1 The :class:`.postgresql.ARRAY` type is now - a subclass of the core :class:`.types.ARRAY` type. + .. versionchanged:: 1.1 The :class:`_postgresql.ARRAY` type is now + a subclass of the core :class:`_types.ARRAY` type. - The :class:`.postgresql.ARRAY` type is constructed in the same way - as the core :class:`.types.ARRAY` type; a member type is required, and a + The :class:`_postgresql.ARRAY` type is constructed in the same way + as the core :class:`_types.ARRAY` type; a member type is required, and a number of dimensions is recommended if the type is to be used for more than one dimension:: @@ -164,11 +166,12 @@ class ARRAY(sqltypes.ARRAY): Column("data", postgresql.ARRAY(Integer, dimensions=2)) ) - The :class:`.postgresql.ARRAY` type provides all operations defined on the - core :class:`.types.ARRAY` type, including support for "dimensions", + The :class:`_postgresql.ARRAY` type provides all operations defined on the + core :class:`_types.ARRAY` type, including support for "dimensions", indexed access, and simple matching such as :meth:`.types.ARRAY.Comparator.any` and - :meth:`.types.ARRAY.Comparator.all`. :class:`.postgresql.ARRAY` class also + :meth:`.types.ARRAY.Comparator.all`. :class:`_postgresql.ARRAY` + class also provides PostgreSQL-specific methods for containment operations, including :meth:`.postgresql.ARRAY.Comparator.contains` :meth:`.postgresql.ARRAY.Comparator.contained_by`, and @@ -176,24 +179,25 @@ class ARRAY(sqltypes.ARRAY): mytable.c.data.contains([1, 2]) - The :class:`.postgresql.ARRAY` type may not be supported on all + The :class:`_postgresql.ARRAY` type may not be supported on all PostgreSQL DBAPIs; it is currently known to work on psycopg2 only. - Additionally, the :class:`.postgresql.ARRAY` type does not work directly in + Additionally, the :class:`_postgresql.ARRAY` + type does not work directly in conjunction with the :class:`.ENUM` type. For a workaround, see the special type at :ref:`postgresql_array_of_enum`. .. seealso:: - :class:`.types.ARRAY` - base array type + :class:`_types.ARRAY` - base array type - :class:`.postgresql.array` - produces a literal array value. + :class:`_postgresql.array` - produces a literal array value. """ class Comparator(sqltypes.ARRAY.Comparator): - """Define comparison operations for :class:`.ARRAY`. + """Define comparison operations for :class:`_types.ARRAY`. Note that these operations are in addition to those provided by the base :class:`.types.ARRAY.Comparator` class, including diff --git a/lib/sqlalchemy/dialects/postgresql/base.py b/lib/sqlalchemy/dialects/postgresql/base.py index cb41a8f65..670de4ebf 100644 --- a/lib/sqlalchemy/dialects/postgresql/base.py +++ b/lib/sqlalchemy/dialects/postgresql/base.py @@ -86,7 +86,7 @@ All PostgreSQL dialects support setting of transaction isolation level both via a dialect-specific parameter :paramref:`.create_engine.isolation_level` accepted by :func:`.create_engine`, as well as the :paramref:`.Connection.execution_options.isolation_level` -argument as passed to :meth:`.Connection.execution_options`. +argument as passed to :meth:`_engine.Connection.execution_options`. When using a non-psycopg2 dialect, this feature works by issuing the command ``SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL <level>`` for each new connection. For the special AUTOCOMMIT isolation level, @@ -129,11 +129,13 @@ Remote-Schema Table Introspection and PostgreSQL search_path name schemas **other** than ``public`` explicitly within ``Table`` definitions. The PostgreSQL dialect can reflect tables from any schema. The -:paramref:`.Table.schema` argument, or alternatively the +:paramref:`_schema.Table.schema` argument, or alternatively the :paramref:`.MetaData.reflect.schema` argument determines which schema will -be searched for the table or tables. The reflected :class:`.Table` objects +be searched for the table or tables. The reflected :class:`_schema.Table` +objects will in all cases retain this ``.schema`` attribute as was specified. -However, with regards to tables which these :class:`.Table` objects refer to +However, with regards to tables which these :class:`_schema.Table` +objects refer to via foreign key constraint, a decision must be made as to how the ``.schema`` is represented in those remote tables, in the case where that remote schema name is also a member of the current @@ -205,7 +207,8 @@ reflection process as follows:: ... <sqlalchemy.engine.result.ResultProxy object at 0x101612ed0> -The above process would deliver to the :attr:`.MetaData.tables` collection +The above process would deliver to the :attr:`_schema.MetaData.tables` +collection ``referred`` table named **without** the schema:: >>> meta.tables['referred'].schema is None @@ -214,8 +217,8 @@ The above process would deliver to the :attr:`.MetaData.tables` collection To alter the behavior of reflection such that the referred schema is maintained regardless of the ``search_path`` setting, use the ``postgresql_ignore_search_path`` option, which can be specified as a -dialect-specific argument to both :class:`.Table` as well as -:meth:`.MetaData.reflect`:: +dialect-specific argument to both :class:`_schema.Table` as well as +:meth:`_schema.MetaData.reflect`:: >>> with engine.connect() as conn: ... conn.execute(text("SET search_path TO test_schema, public")) @@ -239,7 +242,7 @@ We will now have ``test_schema.referred`` stored as schema-qualified:: you just stick to the simplest use pattern: leave the ``search_path`` set to its default of ``public`` only, never refer to the name ``public`` as an explicit schema name otherwise, and refer to all other schema names - explicitly when building up a :class:`.Table` object. The options + explicitly when building up a :class:`_schema.Table` object. The options described here are only for those users who can't, or prefer not to, stay within these guidelines. @@ -251,8 +254,8 @@ which is in the ``public`` (i.e. default) schema will always have the ``.schema`` attribute set to ``None``. .. versionadded:: 0.9.2 Added the ``postgresql_ignore_search_path`` - dialect-level option accepted by :class:`.Table` and - :meth:`.MetaData.reflect`. + dialect-level option accepted by :class:`_schema.Table` and + :meth:`_schema.MetaData.reflect`. .. seealso:: @@ -304,7 +307,7 @@ or they may be *inferred* by stating the columns and conditions that comprise the indexes. SQLAlchemy provides ``ON CONFLICT`` support via the PostgreSQL-specific -:func:`.postgresql.insert()` function, which provides +:func:`_postgresql.insert()` function, which provides the generative methods :meth:`~.postgresql.Insert.on_conflict_do_update` and :meth:`~.postgresql.Insert.on_conflict_do_nothing`:: @@ -331,7 +334,7 @@ Both methods supply the "target" of the conflict using either the named constraint or by column inference: * The :paramref:`.Insert.on_conflict_do_update.index_elements` argument - specifies a sequence containing string column names, :class:`.Column` + specifies a sequence containing string column names, :class:`_schema.Column` objects, and/or SQL expression elements, which would identify a unique index:: @@ -381,8 +384,9 @@ named constraint or by column inference: constraint is unnamed, then inference will be used, where the expressions and optional WHERE clause of the constraint will be spelled out in the construct. This use is especially convenient - to refer to the named or unnamed primary key of a :class:`.Table` using the - :attr:`.Table.primary_key` attribute:: + to refer to the named or unnamed primary key of a :class:`_schema.Table` + using the + :attr:`_schema.Table.primary_key` attribute:: do_update_stmt = insert_stmt.on_conflict_do_update( constraint=my_table.primary_key, @@ -407,17 +411,19 @@ for UPDATE:: .. warning:: - The :meth:`.Insert.on_conflict_do_update` method does **not** take into + The :meth:`_expression.Insert.on_conflict_do_update` + method does **not** take into account Python-side default UPDATE values or generation functions, e.g. - those specified using :paramref:`.Column.onupdate`. + those specified using :paramref:`_schema.Column.onupdate`. These values will not be exercised for an ON CONFLICT style of UPDATE, unless they are manually specified in the :paramref:`.Insert.on_conflict_do_update.set_` dictionary. In order to refer to the proposed insertion row, the special alias :attr:`~.postgresql.Insert.excluded` is available as an attribute on -the :class:`.postgresql.Insert` object; this object is a -:class:`.ColumnCollection` which alias contains all columns of the target +the :class:`_postgresql.Insert` object; this object is a +:class:`_expression.ColumnCollection` +which alias contains all columns of the target table:: from sqlalchemy.dialects.postgresql import insert @@ -432,7 +438,7 @@ table:: ) conn.execute(do_update_stmt) -The :meth:`.Insert.on_conflict_do_update` method also accepts +The :meth:`_expression.Insert.on_conflict_do_update` method also accepts a WHERE clause using the :paramref:`.Insert.on_conflict_do_update.where` parameter, which will limit those rows which receive an UPDATE:: @@ -484,7 +490,8 @@ Full Text Search ---------------- SQLAlchemy makes available the PostgreSQL ``@@`` operator via the -:meth:`.ColumnElement.match` method on any textual column expression. +:meth:`_expression.ColumnElement.match` +method on any textual column expression. On a PostgreSQL dialect, an expression like the following:: select([sometable.c.text.match("search string")]) @@ -505,7 +512,7 @@ Emits the equivalent of:: SELECT to_tsvector('fat cats ate rats') @@ to_tsquery('cat & rat') -The :class:`.postgresql.TSVECTOR` type can provide for explicit CAST:: +The :class:`_postgresql.TSVECTOR` type can provide for explicit CAST:: from sqlalchemy.dialects.postgresql import TSVECTOR from sqlalchemy import select, cast @@ -613,8 +620,9 @@ The :class:`.Index` construct allows these to be specified via the }) Note that the keys in the ``postgresql_ops`` dictionary are the "key" name of -the :class:`.Column`, i.e. the name used to access it from the ``.c`` -collection of :class:`.Table`, which can be configured to be different than +the :class:`_schema.Column`, i.e. the name used to access it from the ``.c`` +collection of :class:`_schema.Table`, +which can be configured to be different than the actual name of the column as expressed in the database. If ``postgresql_ops`` is to be used against a complex SQL expression such @@ -666,7 +674,7 @@ The tablespace can be specified on :class:`.Index` using the .. versionadded:: 1.1 -Note that the same option is available on :class:`.Table` as well. +Note that the same option is available on :class:`_schema.Table` as well. .. _postgresql_index_concurrently: @@ -722,25 +730,30 @@ PostgreSQL Index Reflection The PostgreSQL database creates a UNIQUE INDEX implicitly whenever the UNIQUE CONSTRAINT construct is used. When inspecting a table using -:class:`.Inspector`, the :meth:`.Inspector.get_indexes` -and the :meth:`.Inspector.get_unique_constraints` will report on these +:class:`_reflection.Inspector`, the :meth:`_reflection.Inspector.get_indexes` +and the :meth:`_reflection.Inspector.get_unique_constraints` +will report on these two constructs distinctly; in the case of the index, the key ``duplicates_constraint`` will be present in the index entry if it is detected as mirroring a constraint. When performing reflection using ``Table(..., autoload=True)``, the UNIQUE INDEX is **not** returned -in :attr:`.Table.indexes` when it is detected as mirroring a -:class:`.UniqueConstraint` in the :attr:`.Table.constraints` collection. +in :attr:`_schema.Table.indexes` when it is detected as mirroring a +:class:`.UniqueConstraint` in the :attr:`_schema.Table.constraints` collection +. -.. versionchanged:: 1.0.0 - :class:`.Table` reflection now includes - :class:`.UniqueConstraint` objects present in the :attr:`.Table.constraints` +.. versionchanged:: 1.0.0 - :class:`_schema.Table` reflection now includes + :class:`.UniqueConstraint` objects present in the + :attr:`_schema.Table.constraints` collection; the PostgreSQL backend will no longer include a "mirrored" - :class:`.Index` construct in :attr:`.Table.indexes` if it is detected + :class:`.Index` construct in :attr:`_schema.Table.indexes` + if it is detected as corresponding to a unique constraint. Special Reflection Options -------------------------- -The :class:`.Inspector` used for the PostgreSQL backend is an instance +The :class:`_reflection.Inspector` +used for the PostgreSQL backend is an instance of :class:`.PGInspector`, which offers additional methods:: from sqlalchemy import create_engine, inspect @@ -759,7 +772,7 @@ PostgreSQL Table Options ------------------------ Several options for CREATE TABLE are supported directly by the PostgreSQL -dialect in conjunction with the :class:`.Table` construct: +dialect in conjunction with the :class:`_schema.Table` construct: * ``TABLESPACE``:: @@ -805,13 +818,13 @@ ARRAY Types The PostgreSQL dialect supports arrays, both as multidimensional column types as well as array literals: -* :class:`.postgresql.ARRAY` - ARRAY datatype +* :class:`_postgresql.ARRAY` - ARRAY datatype -* :class:`.postgresql.array` - array literal +* :class:`_postgresql.array` - array literal -* :func:`.postgresql.array_agg` - ARRAY_AGG SQL function +* :func:`_postgresql.array_agg` - ARRAY_AGG SQL function -* :class:`.postgresql.aggregate_order_by` - helper for PG's ORDER BY aggregate +* :class:`_postgresql.aggregate_order_by` - helper for PG's ORDER BY aggregate function syntax. JSON Types @@ -821,18 +834,18 @@ The PostgreSQL dialect supports both JSON and JSONB datatypes, including psycopg2's native support and support for all of PostgreSQL's special operators: -* :class:`.postgresql.JSON` +* :class:`_postgresql.JSON` -* :class:`.postgresql.JSONB` +* :class:`_postgresql.JSONB` HSTORE Type ----------- The PostgreSQL HSTORE type as well as hstore literals are supported: -* :class:`.postgresql.HSTORE` - HSTORE datatype +* :class:`_postgresql.HSTORE` - HSTORE datatype -* :class:`.postgresql.hstore` - hstore literal +* :class:`_postgresql.hstore` - hstore literal ENUM Types ---------- @@ -843,7 +856,7 @@ complexity on the SQLAlchemy side in terms of when this type should be CREATED and DROPPED. The type object is also an independently reflectable entity. The following sections should be consulted: -* :class:`.postgresql.ENUM` - DDL and typing support for ENUM. +* :class:`_postgresql.ENUM` - DDL and typing support for ENUM. * :meth:`.PGInspector.get_enums` - retrieve a listing of current ENUM types @@ -858,7 +871,7 @@ Using ENUM with ARRAY The combination of ENUM and ARRAY is not directly supported by backend DBAPIs at this time. In order to send and receive an ARRAY of ENUM, use the following workaround type, which decorates the -:class:`.postgresql.ARRAY` datatype. +:class:`_postgresql.ARRAY` datatype. .. sourcecode:: python @@ -1268,7 +1281,7 @@ PGUuid = UUID class TSVECTOR(sqltypes.TypeEngine): - """The :class:`.postgresql.TSVECTOR` type implements the PostgreSQL + """The :class:`_postgresql.TSVECTOR` type implements the PostgreSQL text search type TSVECTOR. It can be used to do full text queries on natural language @@ -1289,12 +1302,12 @@ class ENUM(sqltypes.NativeForEmulated, sqltypes.Enum): """PostgreSQL ENUM type. - This is a subclass of :class:`.types.Enum` which includes + This is a subclass of :class:`_types.Enum` which includes support for PG's ``CREATE TYPE`` and ``DROP TYPE``. - When the builtin type :class:`.types.Enum` is used and the + When the builtin type :class:`_types.Enum` is used and the :paramref:`.Enum.native_enum` flag is left at its default of - True, the PostgreSQL backend will use a :class:`.postgresql.ENUM` + True, the PostgreSQL backend will use a :class:`_postgresql.ENUM` type as the implementation, so the special create/drop rules will be used. @@ -1303,9 +1316,10 @@ class ENUM(sqltypes.NativeForEmulated, sqltypes.Enum): parent table, in that it may be "owned" by just a single table, or may be shared among many tables. - When using :class:`.types.Enum` or :class:`.postgresql.ENUM` + When using :class:`_types.Enum` or :class:`_postgresql.ENUM` in an "inline" fashion, the ``CREATE TYPE`` and ``DROP TYPE`` is emitted - corresponding to when the :meth:`.Table.create` and :meth:`.Table.drop` + corresponding to when the :meth:`_schema.Table.create` and + :meth:`_schema.Table.drop` methods are called:: table = Table('sometable', metadata, @@ -1316,9 +1330,9 @@ class ENUM(sqltypes.NativeForEmulated, sqltypes.Enum): table.drop(engine) # will emit DROP TABLE and DROP ENUM To use a common enumerated type between multiple tables, the best - practice is to declare the :class:`.types.Enum` or - :class:`.postgresql.ENUM` independently, and associate it with the - :class:`.MetaData` object itself:: + practice is to declare the :class:`_types.Enum` or + :class:`_postgresql.ENUM` independently, and associate it with the + :class:`_schema.MetaData` object itself:: my_enum = ENUM('a', 'b', 'c', name='myenum', metadata=metadata) @@ -1353,7 +1367,7 @@ class ENUM(sqltypes.NativeForEmulated, sqltypes.Enum): my_enum.create(engine) my_enum.drop(engine) - .. versionchanged:: 1.0.0 The PostgreSQL :class:`.postgresql.ENUM` type + .. versionchanged:: 1.0.0 The PostgreSQL :class:`_postgresql.ENUM` type now behaves more strictly with regards to CREATE/DROP. A metadata-level ENUM type will only be created and dropped at the metadata level, not the table level, with the exception of @@ -1366,10 +1380,10 @@ class ENUM(sqltypes.NativeForEmulated, sqltypes.Enum): native_enum = True def __init__(self, *enums, **kw): - """Construct an :class:`~.postgresql.ENUM`. + """Construct an :class:`_postgresql.ENUM`. Arguments are the same as that of - :class:`.types.Enum`, but also including + :class:`_types.Enum`, but also including the following parameters. :param create_type: Defaults to True. @@ -1397,7 +1411,7 @@ class ENUM(sqltypes.NativeForEmulated, sqltypes.Enum): @classmethod def adapt_emulated_to_native(cls, impl, **kw): - """Produce a PostgreSQL native :class:`.postgresql.ENUM` from plain + """Produce a PostgreSQL native :class:`_postgresql.ENUM` from plain :class:`.Enum`. """ @@ -1412,13 +1426,13 @@ class ENUM(sqltypes.NativeForEmulated, sqltypes.Enum): def create(self, bind=None, checkfirst=True): """Emit ``CREATE TYPE`` for this - :class:`~.postgresql.ENUM`. + :class:`_postgresql.ENUM`. If the underlying dialect does not support PostgreSQL CREATE TYPE, no action is taken. - :param bind: a connectable :class:`.Engine`, - :class:`.Connection`, or similar object to emit + :param bind: a connectable :class:`_engine.Engine`, + :class:`_engine.Connection`, or similar object to emit SQL. :param checkfirst: if ``True``, a query against the PG catalog will be first performed to see @@ -1436,13 +1450,13 @@ class ENUM(sqltypes.NativeForEmulated, sqltypes.Enum): def drop(self, bind=None, checkfirst=True): """Emit ``DROP TYPE`` for this - :class:`~.postgresql.ENUM`. + :class:`_postgresql.ENUM`. If the underlying dialect does not support PostgreSQL DROP TYPE, no action is taken. - :param bind: a connectable :class:`.Engine`, - :class:`.Connection`, or similar object to emit + :param bind: a connectable :class:`_engine.Engine`, + :class:`_engine.Connection`, or similar object to emit SQL. :param checkfirst: if ``True``, a query against the PG catalog will be first performed to see @@ -2276,7 +2290,8 @@ class PGInspector(reflection.Inspector): def get_foreign_table_names(self, schema=None): """Return a list of FOREIGN TABLE names. - Behavior is similar to that of :meth:`.Inspector.get_table_names`, + Behavior is similar to that of + :meth:`_reflection.Inspector.get_table_names`, except that the list is limited to those tables that report a ``relkind`` value of ``f``. diff --git a/lib/sqlalchemy/dialects/postgresql/dml.py b/lib/sqlalchemy/dialects/postgresql/dml.py index 626f81018..70d26a94b 100644 --- a/lib/sqlalchemy/dialects/postgresql/dml.py +++ b/lib/sqlalchemy/dialects/postgresql/dml.py @@ -23,7 +23,7 @@ class Insert(StandardInsert): Adds methods for PG-specific syntaxes such as ON CONFLICT. - The :class:`.postgresql.Insert` object is created using the + The :class:`_postgresql.Insert` object is created using the :func:`sqlalchemy.dialects.postgresql.insert` function. .. versionadded:: 1.1 @@ -41,7 +41,7 @@ class Insert(StandardInsert): .. seealso:: :ref:`postgresql_insert_on_conflict` - example of how - to use :attr:`.Insert.excluded` + to use :attr:`_expression.Insert.excluded` """ return alias(self.table, name="excluded").columns @@ -66,7 +66,7 @@ class Insert(StandardInsert): or the constraint object itself if it has a .name attribute. :param index_elements: - A sequence consisting of string column names, :class:`.Column` + A sequence consisting of string column names, :class:`_schema.Column` objects, or other column expression objects that will be used to infer a target index. @@ -78,12 +78,13 @@ class Insert(StandardInsert): Required argument. A dictionary or other mapping object with column names as keys and expressions or literals as values, specifying the ``SET`` actions to take. - If the target :class:`.Column` specifies a ".key" attribute distinct + If the target :class:`_schema.Column` specifies a ". + key" attribute distinct from the column name, that key should be used. .. warning:: This dictionary does **not** take into account Python-specified default UPDATE values or generation functions, - e.g. those specified using :paramref:`.Column.onupdate`. + e.g. those specified using :paramref:`_schema.Column.onupdate`. These values will not be exercised for an ON CONFLICT style of UPDATE, unless they are manually specified in the :paramref:`.Insert.on_conflict_do_update.set_` dictionary. @@ -122,7 +123,7 @@ class Insert(StandardInsert): or the constraint object itself if it has a .name attribute. :param index_elements: - A sequence consisting of string column names, :class:`.Column` + A sequence consisting of string column names, :class:`_schema.Column` objects, or other column expression objects that will be used to infer a target index. diff --git a/lib/sqlalchemy/dialects/postgresql/ext.py b/lib/sqlalchemy/dialects/postgresql/ext.py index f11919b4b..e64920719 100644 --- a/lib/sqlalchemy/dialects/postgresql/ext.py +++ b/lib/sqlalchemy/dialects/postgresql/ext.py @@ -46,7 +46,7 @@ class aggregate_order_by(expression.ColumnElement): .. seealso:: - :class:`.array_agg` + :class:`_functions.array_agg` """ @@ -113,7 +113,8 @@ class ExcludeConstraint(ColumnCollectionConstraint): where=(Column('group') != 'some group') ) - The constraint is normally embedded into the :class:`.Table` construct + The constraint is normally embedded into the :class:`_schema.Table` + construct directly, or added later using :meth:`.append_constraint`:: some_table = Table( @@ -136,11 +137,14 @@ class ExcludeConstraint(ColumnCollectionConstraint): A sequence of two tuples of the form ``(column, operator)`` where "column" is a SQL expression element or a raw SQL string, most - typically a :class:`.Column` object, and "operator" is a string + typically a :class:`_schema.Column` object, + and "operator" is a string containing the operator to use. In order to specify a column name - when a :class:`.Column` object is not available, while ensuring + when a :class:`_schema.Column` object is not available, + while ensuring that any necessary quoting rules take effect, an ad-hoc - :class:`.Column` or :func:`.sql.expression.column` object should be + :class:`_schema.Column` or :func:`_expression.column` + object should be used. :param name: @@ -230,9 +234,9 @@ class ExcludeConstraint(ColumnCollectionConstraint): def array_agg(*arg, **kw): - """PostgreSQL-specific form of :class:`.array_agg`, ensures - return type is :class:`.postgresql.ARRAY` and not - the plain :class:`.types.ARRAY`, unless an explicit ``type_`` + """PostgreSQL-specific form of :class:`_functions.array_agg`, ensures + return type is :class:`_postgresql.ARRAY` and not + the plain :class:`_types.ARRAY`, unless an explicit ``type_`` is passed. .. versionadded:: 1.1 diff --git a/lib/sqlalchemy/dialects/postgresql/hstore.py b/lib/sqlalchemy/dialects/postgresql/hstore.py index 7f90ffa0e..679805183 100644 --- a/lib/sqlalchemy/dialects/postgresql/hstore.py +++ b/lib/sqlalchemy/dialects/postgresql/hstore.py @@ -141,7 +141,7 @@ class HSTORE(sqltypes.Indexable, sqltypes.Concatenable, sqltypes.TypeEngine): """Construct a new :class:`.HSTORE`. :param text_type: the type that should be used for indexed values. - Defaults to :class:`.types.Text`. + Defaults to :class:`_types.Text`. .. versionadded:: 1.1.0 diff --git a/lib/sqlalchemy/dialects/postgresql/json.py b/lib/sqlalchemy/dialects/postgresql/json.py index 9661634c2..811159953 100644 --- a/lib/sqlalchemy/dialects/postgresql/json.py +++ b/lib/sqlalchemy/dialects/postgresql/json.py @@ -102,14 +102,14 @@ colspecs[sqltypes.JSON.JSONPathType] = JSONPathType class JSON(sqltypes.JSON): """Represent the PostgreSQL JSON type. - This type is a specialization of the Core-level :class:`.types.JSON` - type. Be sure to read the documentation for :class:`.types.JSON` for + This type is a specialization of the Core-level :class:`_types.JSON` + type. Be sure to read the documentation for :class:`_types.JSON` for important tips regarding treatment of NULL values and ORM use. - .. versionchanged:: 1.1 :class:`.postgresql.JSON` is now a PostgreSQL- - specific specialization of the new :class:`.types.JSON` type. + .. versionchanged:: 1.1 :class:`_postgresql.JSON` is now a PostgreSQL- + specific specialization of the new :class:`_types.JSON` type. - The operators provided by the PostgreSQL version of :class:`.JSON` + The operators provided by the PostgreSQL version of :class:`_types.JSON` include: * Index operations (the ``->`` operator):: @@ -142,13 +142,15 @@ class JSON(sqltypes.JSON): data_table.c.data[('key_1', 'key_2', 5, ..., 'key_n')].astext == 'some value' - .. versionchanged:: 1.1 The :meth:`.ColumnElement.cast` operator on + .. versionchanged:: 1.1 The :meth:`_expression.ColumnElement.cast` + operator on JSON objects now requires that the :attr:`.JSON.Comparator.astext` modifier be called explicitly, if the cast works only from a textual string. Index operations return an expression object whose type defaults to - :class:`.JSON` by default, so that further JSON-oriented instructions + :class:`_types.JSON` by default, + so that further JSON-oriented instructions may be called upon the result type. Custom serializers and deserializers are specified at the dialect level, @@ -166,16 +168,16 @@ class JSON(sqltypes.JSON): .. seealso:: - :class:`.types.JSON` - Core level JSON type + :class:`_types.JSON` - Core level JSON type - :class:`.JSONB` + :class:`_postgresql.JSONB` """ # noqa astext_type = sqltypes.Text() def __init__(self, none_as_null=False, astext_type=None): - """Construct a :class:`.JSON` type. + """Construct a :class:`_types.JSON` type. :param none_as_null: if True, persist the value ``None`` as a SQL NULL value, not the JSON encoding of ``null``. Note that @@ -190,11 +192,11 @@ class JSON(sqltypes.JSON): .. seealso:: - :attr:`.JSON.NULL` + :attr:`_types.JSON.NULL` :param astext_type: the type to use for the :attr:`.JSON.Comparator.astext` - accessor on indexed attributes. Defaults to :class:`.types.Text`. + accessor on indexed attributes. Defaults to :class:`_types.Text`. .. versionadded:: 1.1 @@ -204,7 +206,7 @@ class JSON(sqltypes.JSON): self.astext_type = astext_type class Comparator(sqltypes.JSON.Comparator): - """Define comparison operations for :class:`.JSON`.""" + """Define comparison operations for :class:`_types.JSON`.""" @property def astext(self): @@ -217,7 +219,7 @@ class JSON(sqltypes.JSON): .. seealso:: - :meth:`.ColumnElement.cast` + :meth:`_expression.ColumnElement.cast` """ if isinstance(self.expr.right.type, sqltypes.JSON.JSONPathType): @@ -241,7 +243,8 @@ ischema_names["json"] = JSON class JSONB(JSON): """Represent the PostgreSQL JSONB type. - The :class:`.JSONB` type stores arbitrary JSONB format data, e.g.:: + The :class:`_postgresql.JSONB` type stores arbitrary JSONB format data, e. + g.:: data_table = Table('data_table', metadata, Column('id', Integer, primary_key=True), @@ -254,19 +257,22 @@ class JSONB(JSON): data = {"key1": "value1", "key2": "value2"} ) - The :class:`.JSONB` type includes all operations provided by - :class:`.JSON`, including the same behaviors for indexing operations. + The :class:`_postgresql.JSONB` type includes all operations provided by + :class:`_types.JSON`, including the same behaviors for indexing operations + . It also adds additional operators specific to JSONB, including :meth:`.JSONB.Comparator.has_key`, :meth:`.JSONB.Comparator.has_all`, :meth:`.JSONB.Comparator.has_any`, :meth:`.JSONB.Comparator.contains`, and :meth:`.JSONB.Comparator.contained_by`. - Like the :class:`.JSON` type, the :class:`.JSONB` type does not detect + Like the :class:`_types.JSON` type, the :class:`_postgresql.JSONB` + type does not detect in-place changes when used with the ORM, unless the :mod:`sqlalchemy.ext.mutable` extension is used. Custom serializers and deserializers - are shared with the :class:`.JSON` class, using the ``json_serializer`` + are shared with the :class:`_types.JSON` class, + using the ``json_serializer`` and ``json_deserializer`` keyword arguments. These must be specified at the dialect level using :func:`.create_engine`. When using psycopg2, the serializers are associated with the jsonb type using @@ -278,14 +284,14 @@ class JSONB(JSON): .. seealso:: - :class:`.JSON` + :class:`_types.JSON` """ __visit_name__ = "JSONB" class Comparator(JSON.Comparator): - """Define comparison operations for :class:`.JSON`.""" + """Define comparison operations for :class:`_types.JSON`.""" def has_key(self, other): """Boolean expression. Test for presence of a key. Note that the diff --git a/lib/sqlalchemy/dialects/postgresql/psycopg2.py b/lib/sqlalchemy/dialects/postgresql/psycopg2.py index 89a63fd47..6d2672bbe 100644 --- a/lib/sqlalchemy/dialects/postgresql/psycopg2.py +++ b/lib/sqlalchemy/dialects/postgresql/psycopg2.py @@ -119,18 +119,21 @@ Per-Statement/Connection Execution Options ------------------------------------------- The following DBAPI-specific options are respected when used with -:meth:`.Connection.execution_options`, :meth:`.Executable.execution_options`, -:meth:`.Query.execution_options`, in addition to those not specific to DBAPIs: +:meth:`_engine.Connection.execution_options`, +:meth:`.Executable.execution_options`, +:meth:`_query.Query.execution_options`, +in addition to those not specific to DBAPIs: * ``isolation_level`` - Set the transaction isolation level for the lifespan - of a :class:`.Connection` (can only be set on a connection, not a statement + of a :class:`_engine.Connection` (can only be set on a connection, + not a statement or query). See :ref:`psycopg2_isolation_level`. * ``stream_results`` - Enable or disable usage of psycopg2 server side cursors - this feature makes use of "named" cursors in combination with special result handling methods so that result rows are not fully buffered. If ``None`` or not set, the ``server_side_cursors`` option of the - :class:`.Engine` is used. + :class:`_engine.Engine` is used. * ``max_row_buffer`` - when using ``stream_results``, an integer value that specifies the maximum number of rows to buffer at a time. This is @@ -153,7 +156,8 @@ Modern versions of psycopg2 include a feature known as have been shown in benchmarking to improve psycopg2's executemany() performance, primarily with INSERT statements, by multiple orders of magnitude. SQLAlchemy allows this extension to be used for all ``executemany()`` style -calls invoked by an :class:`.Engine` when used with :ref:`multiple parameter +calls invoked by an :class:`_engine.Engine` +when used with :ref:`multiple parameter sets <execute_multiple>`, which includes the use of this feature both by the Core as well as by the ORM for inserts of objects with non-autogenerated primary key values, by adding the ``executemany_mode`` flag to @@ -180,13 +184,15 @@ Possible options for ``executemany_mode`` include: semicolon. This is the same behavior as was provided by the ``use_batch_mode=True`` flag. -* ``'values'``- For Core :func:`~.sql.expression.insert` constructs only (including those +* ``'values'``- For Core :func:`_expression.insert` + constructs only (including those emitted by the ORM automatically), the ``psycopg2.extras.execute_values`` extension is used so that multiple parameter sets are grouped into a single INSERT statement and joined together with multiple VALUES expressions. This method requires that the string text of the VALUES clause inside the INSERT statement is manipulated, so is only supported with a compiled - :func:`~.sql.expression.insert` construct where the format is predictable. For all other + :func:`_expression.insert` construct where the format is predictable. + For all other constructs, including plain textual INSERT statements not rendered by the SQLAlchemy expression language compiler, the ``psycopg2.extras.execute_batch`` method is used. It is therefore important @@ -213,7 +219,8 @@ more appropriate:: .. seealso:: :ref:`execute_multiple` - General information on using the - :class:`.Connection` object to execute statements in such a way as to make + :class:`_engine.Connection` + object to execute statements in such a way as to make use of the DBAPI ``.executemany()`` method. .. versionchanged:: 1.3.7 - Added support for @@ -299,7 +306,8 @@ actually contain percent or parenthesis symbols; as SQLAlchemy in many cases generates bound parameter names based on the name of a column, the presence of these characters in a column name can lead to problems. -There are two solutions to the issue of a :class:`.schema.Column` that contains +There are two solutions to the issue of a :class:`_schema.Column` +that contains one of these characters in its name. One is to specify the :paramref:`.schema.Column.key` for columns that have such names:: @@ -312,10 +320,12 @@ Above, an INSERT statement such as ``measurement.insert()`` will use ``measurement.c.size_meters > 10`` will derive the bound parameter name from the ``size_meters`` key as well. -.. versionchanged:: 1.0.0 - SQL expressions will use :attr:`.Column.key` +.. versionchanged:: 1.0.0 - SQL expressions will use + :attr:`_schema.Column.key` as the source of naming when anonymous bound parameters are created in SQL expressions; previously, this behavior only applied to - :meth:`.Table.insert` and :meth:`.Table.update` parameter names. + :meth:`_schema.Table.insert` and :meth:`_schema.Table.update` + parameter names. The other solution is to use a positional format; psycopg2 allows use of the "format" paramstyle, which can be passed to @@ -352,7 +362,8 @@ As discussed in :ref:`postgresql_isolation_level`, all PostgreSQL dialects support setting of transaction isolation level both via the ``isolation_level`` parameter passed to :func:`.create_engine`, as well as the ``isolation_level`` argument used by -:meth:`.Connection.execution_options`. When using the psycopg2 dialect, these +:meth:`_engine.Connection.execution_options`. When using the psycopg2 dialect +, these options make use of psycopg2's ``set_isolation_level()`` connection method, rather than emitting a PostgreSQL directive; this is because psycopg2's API-level setting is always emitted at the start of each transaction in any diff --git a/lib/sqlalchemy/dialects/sqlite/base.py b/lib/sqlalchemy/dialects/sqlite/base.py index d3105f268..1e265a9eb 100644 --- a/lib/sqlalchemy/dialects/sqlite/base.py +++ b/lib/sqlalchemy/dialects/sqlite/base.py @@ -19,7 +19,7 @@ not provide out of the box functionality for translating values between Python `datetime` objects and a SQLite-supported format. SQLAlchemy's own :class:`~sqlalchemy.types.DateTime` and related types provide date formatting and parsing functionality when SQLite is used. The implementation classes are -:class:`~.sqlite.DATETIME`, :class:`~.sqlite.DATE` and :class:`~.sqlite.TIME`. +:class:`_sqlite.DATETIME`, :class:`_sqlite.DATE` and :class:`_sqlite.TIME`. These types represent dates and times as ISO formatted strings, which also nicely support ordering. There's no reliance on typical "libc" internals for these functions so historical dates are fully supported. @@ -216,7 +216,7 @@ SAVEPOINT Support SQLite supports SAVEPOINTs, which only function once a transaction is begun. SQLAlchemy's SAVEPOINT support is available using the -:meth:`.Connection.begin_nested` method at the Core level, and +:meth:`_engine.Connection.begin_nested` method at the Core level, and :meth:`.Session.begin_nested` at the ORM level. However, SAVEPOINTs won't work at all with pysqlite unless workarounds are taken. @@ -303,11 +303,12 @@ itself depending on the location of the target constraint. To render this clause within DDL, the extension parameter ``sqlite_on_conflict`` can be specified with a string conflict resolution algorithm within the :class:`.PrimaryKeyConstraint`, :class:`.UniqueConstraint`, -:class:`.CheckConstraint` objects. Within the :class:`.Column` object, there +:class:`.CheckConstraint` objects. Within the :class:`_schema.Column` object, +there are individual parameters ``sqlite_on_conflict_not_null``, ``sqlite_on_conflict_primary_key``, ``sqlite_on_conflict_unique`` which each correspond to the three types of relevant constraint types that can be -indicated from a :class:`.Column` object. +indicated from a :class:`_schema.Column` object. .. seealso:: @@ -339,9 +340,10 @@ The above renders CREATE TABLE DDL as:: ) -When using the :paramref:`.Column.unique` flag to add a UNIQUE constraint +When using the :paramref:`_schema.Column.unique` +flag to add a UNIQUE constraint to a single column, the ``sqlite_on_conflict_unique`` parameter can -be added to the :class:`.Column` as well, which will be added to the +be added to the :class:`_schema.Column` as well, which will be added to the UNIQUE constraint in the DDL:: some_table = Table( @@ -417,30 +419,30 @@ http://www.sqlite.org/datatype3.html section 2.1. The provided typemap will make direct associations from an exact string name match for the following types: -:class:`~.types.BIGINT`, :class:`~.types.BLOB`, -:class:`~.types.BOOLEAN`, :class:`~.types.BOOLEAN`, -:class:`~.types.CHAR`, :class:`~.types.DATE`, -:class:`~.types.DATETIME`, :class:`~.types.FLOAT`, -:class:`~.types.DECIMAL`, :class:`~.types.FLOAT`, -:class:`~.types.INTEGER`, :class:`~.types.INTEGER`, -:class:`~.types.NUMERIC`, :class:`~.types.REAL`, -:class:`~.types.SMALLINT`, :class:`~.types.TEXT`, -:class:`~.types.TIME`, :class:`~.types.TIMESTAMP`, -:class:`~.types.VARCHAR`, :class:`~.types.NVARCHAR`, -:class:`~.types.NCHAR` +:class:`_types.BIGINT`, :class:`_types.BLOB`, +:class:`_types.BOOLEAN`, :class:`_types.BOOLEAN`, +:class:`_types.CHAR`, :class:`_types.DATE`, +:class:`_types.DATETIME`, :class:`_types.FLOAT`, +:class:`_types.DECIMAL`, :class:`_types.FLOAT`, +:class:`_types.INTEGER`, :class:`_types.INTEGER`, +:class:`_types.NUMERIC`, :class:`_types.REAL`, +:class:`_types.SMALLINT`, :class:`_types.TEXT`, +:class:`_types.TIME`, :class:`_types.TIMESTAMP`, +:class:`_types.VARCHAR`, :class:`_types.NVARCHAR`, +:class:`_types.NCHAR` When a type name does not match one of the above types, the "type affinity" lookup is used instead: -* :class:`~.types.INTEGER` is returned if the type name includes the +* :class:`_types.INTEGER` is returned if the type name includes the string ``INT`` -* :class:`~.types.TEXT` is returned if the type name includes the +* :class:`_types.TEXT` is returned if the type name includes the string ``CHAR``, ``CLOB`` or ``TEXT`` -* :class:`~.types.NullType` is returned if the type name includes the +* :class:`_types.NullType` is returned if the type name includes the string ``BLOB`` -* :class:`~.types.REAL` is returned if the type name includes the string +* :class:`_types.REAL` is returned if the type name includes the string ``REAL``, ``FLOA`` or ``DOUB``. -* Otherwise, the :class:`~.types.NUMERIC` type is used. +* Otherwise, the :class:`_types.NUMERIC` type is used. .. versionadded:: 0.9.3 Support for SQLite type affinity rules when reflecting columns. @@ -560,7 +562,7 @@ the very specific case where an application is forced to use column names that contain dots, and the functionality of :meth:`.ResultProxy.keys` and :meth:`.Row.keys()` is required to return these dotted names unmodified, the ``sqlite_raw_colnames`` execution option may be provided, either on a -per-:class:`.Connection` basis:: +per-:class:`_engine.Connection` basis:: result = conn.execution_options(sqlite_raw_colnames=True).exec_driver_sql(''' select x.a, x.b from x where a=1 @@ -569,11 +571,11 @@ per-:class:`.Connection` basis:: ''') assert result.keys() == ["x.a", "x.b"] -or on a per-:class:`.Engine` basis:: +or on a per-:class:`_engine.Engine` basis:: engine = create_engine("sqlite://", execution_options={"sqlite_raw_colnames": True}) -When using the per-:class:`.Engine` execution option, note that +When using the per-:class:`_engine.Engine` execution option, note that **Core and ORM queries that use UNION may not function properly**. """ # noqa diff --git a/lib/sqlalchemy/dialects/sqlite/json.py b/lib/sqlalchemy/dialects/sqlite/json.py index db185dd4d..775f557f8 100644 --- a/lib/sqlalchemy/dialects/sqlite/json.py +++ b/lib/sqlalchemy/dialects/sqlite/json.py @@ -9,8 +9,8 @@ class JSON(sqltypes.JSON): `loadable extension <https://www.sqlite.org/loadext.html>`_ and as such may not be available, or may require run-time loading. - The :class:`.sqlite.JSON` type supports persistence of JSON values - as well as the core index operations provided by :class:`.types.JSON` + The :class:`_sqlite.JSON` type supports persistence of JSON values + as well as the core index operations provided by :class:`_types.JSON` datatype, by adapting the operations to render the ``JSON_EXTRACT`` function wrapped in the ``JSON_QUOTE`` function at the database level. Extracted values are quoted in order to ensure that the results are diff --git a/lib/sqlalchemy/dialects/sqlite/pysqlite.py b/lib/sqlalchemy/dialects/sqlite/pysqlite.py index 72bbd0177..307114c03 100644 --- a/lib/sqlalchemy/dialects/sqlite/pysqlite.py +++ b/lib/sqlalchemy/dialects/sqlite/pysqlite.py @@ -326,7 +326,8 @@ ourselves. This is achieved using two event listeners:: .. warning:: When using the above recipe, it is advised to not use the :paramref:`.Connection.execution_options.isolation_level` setting on - :class:`.Connection` and :func:`.create_engine` with the SQLite driver, + :class:`_engine.Connection` and :func:`.create_engine` + with the SQLite driver, as this function necessarily will also alter the ".isolation_level" setting. diff --git a/lib/sqlalchemy/engine/base.py b/lib/sqlalchemy/engine/base.py index 1a5562a9b..014d433a7 100644 --- a/lib/sqlalchemy/engine/base.py +++ b/lib/sqlalchemy/engine/base.py @@ -20,7 +20,7 @@ from ..sql import compiler from ..sql import util as sql_util -"""Defines :class:`.Connection` and :class:`.Engine`. +"""Defines :class:`_engine.Connection` and :class:`_engine.Engine`. """ @@ -29,7 +29,8 @@ class Connection(Connectable): """Provides high-level functionality for a wrapped DB-API connection. Provides execution support for string-based SQL statements as well as - :class:`.ClauseElement`, :class:`.Compiled` and :class:`.DefaultGenerator` + :class:`_expression.ClauseElement`, :class:`.Compiled` and + :class:`.DefaultGenerator` objects. Provides a :meth:`begin` method to return :class:`.Transaction` objects. @@ -185,10 +186,12 @@ class Connection(Connectable): r""" Set non-SQL options for the connection which take effect during execution. - The method returns a copy of this :class:`.Connection` which references + The method returns a copy of this :class:`_engine.Connection` + which references the same underlying DBAPI connection, but also defines the given execution options which will take effect for a call to - :meth:`execute`. As the new :class:`.Connection` references the same + :meth:`execute`. As the new :class:`_engine.Connection` + references the same underlying resource, it's usually a good idea to ensure that the copies will be discarded immediately, which is implicit if used as in:: @@ -196,14 +199,16 @@ class Connection(Connectable): execute(stmt) Note that any key/value can be passed to - :meth:`.Connection.execution_options`, and it will be stored in the - ``_execution_options`` dictionary of the :class:`.Connection`. It + :meth:`_engine.Connection.execution_options`, + and it will be stored in the + ``_execution_options`` dictionary of the :class:`_engine.Connection`. + It is suitable for usage by end-user schemes to communicate with event listeners, for example. The keywords that are currently recognized by SQLAlchemy itself include all those listed under :meth:`.Executable.execution_options`, - as well as others that are specific to :class:`.Connection`. + as well as others that are specific to :class:`_engine.Connection`. :param autocommit: Available on: Connection, statement. When True, a COMMIT will be invoked after execution @@ -221,7 +226,8 @@ class Connection(Connectable): :param compiled_cache: Available on: Connection. A dictionary where :class:`.Compiled` objects - will be cached when the :class:`.Connection` compiles a clause + will be cached when the :class:`_engine.Connection` + compiles a clause expression into a :class:`.Compiled` object. It is the user's responsibility to manage the size of this dictionary, which will have keys @@ -236,10 +242,11 @@ class Connection(Connectable): used by the ORM internally supersedes a cache dictionary specified here. - :param isolation_level: Available on: :class:`.Connection`. + :param isolation_level: Available on: :class:`_engine.Connection`. Set the transaction isolation level for the lifespan of this - :class:`.Connection` object. Valid values include those string + :class:`_engine.Connection` object. + Valid values include those string values accepted by the :paramref:`.create_engine.isolation_level` parameter passed to :func:`.create_engine`. These levels are semi-database specific; see individual dialect documentation for @@ -248,25 +255,27 @@ class Connection(Connectable): The isolation level option applies the isolation level by emitting statements on the DBAPI connection, and **necessarily affects the original Connection object overall**, not just the copy that is - returned by the call to :meth:`.Connection.execution_options` + returned by the call to :meth:`_engine.Connection.execution_options` method. The isolation level will remain at the given setting until the DBAPI connection itself is returned to the connection pool, i.e. - the :meth:`.Connection.close` method on the original - :class:`.Connection` is called, where an event handler will emit + the :meth:`_engine.Connection.close` method on the original + :class:`_engine.Connection` is called, + where an event handler will emit additional statements on the DBAPI connection in order to revert the isolation level change. .. warning:: The ``isolation_level`` execution option should **not** be used when a transaction is already established, that - is, the :meth:`.Connection.begin` method or similar has been + is, the :meth:`_engine.Connection.begin` + method or similar has been called. A database cannot change the isolation level on a transaction in progress, and different DBAPIs and/or SQLAlchemy dialects may implicitly roll back or commit the transaction, or not affect the connection at all. .. note:: The ``isolation_level`` execution option is implicitly - reset if the :class:`.Connection` is invalidated, e.g. via - the :meth:`.Connection.invalidate` method, or if a + reset if the :class:`_engine.Connection` is invalidated, e.g. via + the :meth:`_engine.Connection.invalidate` method, or if a disconnection error occurs. The new connection produced after the invalidation will not have the isolation level re-applied to it automatically. @@ -274,9 +283,10 @@ class Connection(Connectable): .. seealso:: :paramref:`.create_engine.isolation_level` - - set per :class:`.Engine` isolation level + - set per :class:`_engine.Engine` isolation level - :meth:`.Connection.get_isolation_level` - view current level + :meth:`_engine.Connection.get_isolation_level` + - view current level :ref:`SQLite Transaction Isolation <sqlite_isolation_level>` @@ -308,8 +318,9 @@ class Connection(Connectable): :param schema_translate_map: Available on: Connection, Engine. A dictionary mapping schema names to schema names, that will be - applied to the :paramref:`.Table.schema` element of each - :class:`.Table` encountered when SQL or DDL expression elements + applied to the :paramref:`_schema.Table.schema` element of each + :class:`_schema.Table` + encountered when SQL or DDL expression elements are compiled into strings; the resulting schema name will be converted based on presence in the map of the original name. @@ -321,11 +332,11 @@ class Connection(Connectable): .. seealso:: - :meth:`.Engine.execution_options` + :meth:`_engine.Engine.execution_options` :meth:`.Executable.execution_options` - :meth:`.Connection.get_execution_options` + :meth:`_engine.Connection.get_execution_options` """ # noqa @@ -343,7 +354,7 @@ class Connection(Connectable): .. seealso:: - :meth:`.Connection.execution_options` + :meth:`_engine.Connection.execution_options` """ return self._execution_options @@ -386,19 +397,19 @@ class Connection(Connectable): def get_isolation_level(self): """Return the current isolation level assigned to this - :class:`.Connection`. + :class:`_engine.Connection`. This will typically be the default isolation level as determined by the dialect, unless if the :paramref:`.Connection.execution_options.isolation_level` feature has been used to alter the isolation level on a - per-:class:`.Connection` basis. + per-:class:`_engine.Connection` basis. This attribute will typically perform a live SQL operation in order to procure the current isolation level, so the value returned is the actual level on the underlying DBAPI connection regardless of how this state was set. Compare to the - :attr:`.Connection.default_isolation_level` accessor + :attr:`_engine.Connection.default_isolation_level` accessor which returns the dialect-level setting without performing a SQL query. @@ -406,13 +417,14 @@ class Connection(Connectable): .. seealso:: - :attr:`.Connection.default_isolation_level` - view default level + :attr:`_engine.Connection.default_isolation_level` + - view default level :paramref:`.create_engine.isolation_level` - - set per :class:`.Engine` isolation level + - set per :class:`_engine.Engine` isolation level :paramref:`.Connection.execution_options.isolation_level` - - set per :class:`.Connection` isolation level + - set per :class:`_engine.Connection` isolation level """ try: @@ -422,15 +434,18 @@ class Connection(Connectable): @property def default_isolation_level(self): - """The default isolation level assigned to this :class:`.Connection`. + """The default isolation level assigned to this + :class:`_engine.Connection`. - This is the isolation level setting that the :class:`.Connection` - has when first procured via the :meth:`.Engine.connect` method. + This is the isolation level setting that the + :class:`_engine.Connection` + has when first procured via the :meth:`_engine.Engine.connect` method. This level stays in place until the :paramref:`.Connection.execution_options.isolation_level` is used - to change the setting on a per-:class:`.Connection` basis. + to change the setting on a per-:class:`_engine.Connection` basis. - Unlike :meth:`.Connection.get_isolation_level`, this attribute is set + Unlike :meth:`_engine.Connection.get_isolation_level`, + this attribute is set ahead of time from the first connection procured by the dialect, so SQL query is not invoked when this accessor is called. @@ -438,13 +453,14 @@ class Connection(Connectable): .. seealso:: - :meth:`.Connection.get_isolation_level` - view current level + :meth:`_engine.Connection.get_isolation_level` + - view current level :paramref:`.create_engine.isolation_level` - - set per :class:`.Engine` isolation level + - set per :class:`_engine.Engine` isolation level :paramref:`.Connection.execution_options.isolation_level` - - set per :class:`.Connection` isolation level + - set per :class:`_engine.Connection` isolation level """ return self.dialect.default_isolation_level @@ -482,12 +498,12 @@ class Connection(Connectable): @property def info(self): """Info dictionary associated with the underlying DBAPI connection - referred to by this :class:`.Connection`, allowing user-defined + referred to by this :class:`_engine.Connection`, allowing user-defined data to be associated with the connection. The data here will follow along with the DBAPI connection including after it is returned to the connection pool and used again - in subsequent instances of :class:`.Connection`. + in subsequent instances of :class:`_engine.Connection`. """ @@ -495,14 +511,14 @@ class Connection(Connectable): @util.deprecated_20(":meth:`.Connection.connect`") def connect(self, close_with_result=False): - """Returns a branched version of this :class:`.Connection`. + """Returns a branched version of this :class:`_engine.Connection`. - The :meth:`.Connection.close` method on the returned - :class:`.Connection` can be called and this - :class:`.Connection` will remain open. + The :meth:`_engine.Connection.close` method on the returned + :class:`_engine.Connection` can be called and this + :class:`_engine.Connection` will remain open. This method provides usage symmetry with - :meth:`.Engine.connect`, including for usage + :meth:`_engine.Engine.connect`, including for usage with context managers. """ @@ -511,36 +527,38 @@ class Connection(Connectable): def invalidate(self, exception=None): """Invalidate the underlying DBAPI connection associated with - this :class:`.Connection`. + this :class:`_engine.Connection`. The underlying DBAPI connection is literally closed (if possible), and is discarded. Its source connection pool will typically lazily create a new connection to replace it. Upon the next use (where "use" typically means using the - :meth:`.Connection.execute` method or similar), - this :class:`.Connection` will attempt to + :meth:`_engine.Connection.execute` method or similar), + this :class:`_engine.Connection` will attempt to procure a new DBAPI connection using the services of the - :class:`.Pool` as a source of connectivity (e.g. a "reconnection"). + :class:`_pool.Pool` as a source of connectivity (e.g. + a "reconnection"). If a transaction was in progress (e.g. the - :meth:`.Connection.begin` method has been called) when - :meth:`.Connection.invalidate` method is called, at the DBAPI + :meth:`_engine.Connection.begin` method has been called) when + :meth:`_engine.Connection.invalidate` method is called, at the DBAPI level all state associated with this transaction is lost, as - the DBAPI connection is closed. The :class:`.Connection` + the DBAPI connection is closed. The :class:`_engine.Connection` will not allow a reconnection to proceed until the :class:`.Transaction` object is ended, by calling the :meth:`.Transaction.rollback` method; until that point, any attempt at - continuing to use the :class:`.Connection` will raise an + continuing to use the :class:`_engine.Connection` will raise an :class:`~sqlalchemy.exc.InvalidRequestError`. This is to prevent applications from accidentally continuing an ongoing transactional operations despite the fact that the transaction has been lost due to an invalidation. - The :meth:`.Connection.invalidate` method, just like auto-invalidation, + The :meth:`_engine.Connection.invalidate` method, + just like auto-invalidation, will at the connection pool level invoke the - :meth:`.PoolEvents.invalidate` event. + :meth:`_events.PoolEvents.invalidate` event. .. seealso:: @@ -573,7 +591,8 @@ class Connection(Connectable): # connection is fully closed (since we used "with:", can # also call .close()) - This :class:`.Connection` instance will remain usable. When closed + This :class:`_engine.Connection` instance will remain usable. + When closed (or exited from a context manager context as above), the DB-API connection will be literally closed and not returned to its originating pool. @@ -594,7 +613,7 @@ class Connection(Connectable): which completes when either the :meth:`.Transaction.rollback` or :meth:`.Transaction.commit` method is called. - Nested calls to :meth:`.begin` on the same :class:`.Connection` + Nested calls to :meth:`.begin` on the same :class:`_engine.Connection` will return new :class:`.Transaction` objects that represent an emulated transaction within the scope of the enclosing transaction, that is:: @@ -612,13 +631,13 @@ class Connection(Connectable): .. seealso:: - :meth:`.Connection.begin_nested` - use a SAVEPOINT + :meth:`_engine.Connection.begin_nested` - use a SAVEPOINT - :meth:`.Connection.begin_twophase` - + :meth:`_engine.Connection.begin_twophase` - use a two phase /XID transaction - :meth:`.Engine.begin` - context manager available from - :class:`.Engine` + :meth:`_engine.Engine.begin` - context manager available from + :class:`_engine.Engine` """ if self.__branch_from: @@ -643,9 +662,9 @@ class Connection(Connectable): .. seealso:: - :meth:`.Connection.begin` + :meth:`_engine.Connection.begin` - :meth:`.Connection.begin_twophase` + :meth:`_engine.Connection.begin_twophase` """ if self.__branch_from: @@ -671,9 +690,9 @@ class Connection(Connectable): .. seealso:: - :meth:`.Connection.begin` + :meth:`_engine.Connection.begin` - :meth:`.Connection.begin_twophase` + :meth:`_engine.Connection.begin_twophase` """ @@ -870,21 +889,21 @@ class Connection(Connectable): self._root._rollback_impl() def close(self): - """Close this :class:`.Connection`. + """Close this :class:`_engine.Connection`. This results in a release of the underlying database resources, that is, the DBAPI connection referenced internally. The DBAPI connection is typically restored - back to the connection-holding :class:`.Pool` referenced - by the :class:`.Engine` that produced this - :class:`.Connection`. Any transactional state present on + back to the connection-holding :class:`_pool.Pool` referenced + by the :class:`_engine.Engine` that produced this + :class:`_engine.Connection`. Any transactional state present on the DBAPI connection is also unconditionally released via the DBAPI connection's ``rollback()`` method, regardless of any :class:`.Transaction` object that may be - outstanding with regards to this :class:`.Connection`. + outstanding with regards to this :class:`_engine.Connection`. - After :meth:`~.Connection.close` is called, the - :class:`.Connection` is permanently in a closed state, + After :meth:`_engine.Connection.close` is called, the + :class:`_engine.Connection` is permanently in a closed state, and will allow no further operations. """ @@ -937,9 +956,9 @@ class Connection(Connectable): one of: * a plain string (deprecated) - * any :class:`.ClauseElement` construct that is also + * any :class:`_expression.ClauseElement` construct that is also a subclass of :class:`.Executable`, such as a - :func:`~.expression.select` construct + :func:`_expression.select` construct * a :class:`.FunctionElement`, such as that generated by :data:`.func`, will be automatically wrapped in a SELECT statement, which is then executed. @@ -947,11 +966,13 @@ class Connection(Connectable): * a :class:`.DefaultGenerator` object * a :class:`.Compiled` object - .. deprecated:: 2.0 passing a string to :meth:`.Connection.execute` is + .. deprecated:: 2.0 passing a string to + :meth:`_engine.Connection.execute` is deprecated and will be removed in version 2.0. Use the - :func:`~.expression.text` construct with - :meth:`.Connection.execute`, or the - :meth:`.Connection.exec_driver_sql` method to invoke a driver-level + :func:`_expression.text` construct with + :meth:`_engine.Connection.execute`, or the + :meth:`_engine.Connection.exec_driver_sql` + method to invoke a driver-level SQL string. :param \*multiparams/\**params: represent bound parameter @@ -992,7 +1013,7 @@ class Connection(Connectable): for details on paramstyle. To execute a textual SQL statement which uses bound parameters in a - DBAPI-agnostic way, use the :func:`~.expression.text` construct. + DBAPI-agnostic way, use the :func:`_expression.text` construct. .. deprecated:: 2.0 use of tuple or scalar positional parameters is deprecated. All params should be dicts or sequences of dicts. @@ -1653,14 +1674,15 @@ class Connection(Connectable): @util.deprecated( "1.4", - "The :meth:`.Connection.transaction` method is deprecated and will be " - "removed in a future release. Use the :meth:`.Engine.begin` " + "The :meth:`_engine.Connection.transaction` " + "method is deprecated and will be " + "removed in a future release. Use the :meth:`_engine.Engine.begin` " "context manager instead.", ) def transaction(self, callable_, *args, **kwargs): r"""Execute the given function within a transaction boundary. - The function is passed this :class:`.Connection` + The function is passed this :class:`_engine.Connection` as the first argument, followed by the given \*args and \**kwargs, e.g.:: @@ -1679,23 +1701,23 @@ class Connection(Connectable): The :meth:`.transaction` method is superseded by the usage of the Python ``with:`` statement, which can - be used with :meth:`.Connection.begin`:: + be used with :meth:`_engine.Connection.begin`:: with conn.begin(): conn.execute(text("some statement"), {'x':5, 'y':10}) - As well as with :meth:`.Engine.begin`:: + As well as with :meth:`_engine.Engine.begin`:: with engine.begin() as conn: conn.execute(text("some statement"), {'x':5, 'y':10}) .. seealso:: - :meth:`.Engine.begin` - engine-level transactional + :meth:`_engine.Engine.begin` - engine-level transactional context - :meth:`.Engine.transaction` - engine-level version of - :meth:`.Connection.transaction` + :meth:`_engine.Engine.transaction` - engine-level version of + :meth:`_engine.Connection.transaction` """ @@ -1711,19 +1733,20 @@ class Connection(Connectable): @util.deprecated( "1.4", - "The :meth:`.Connection.run_callable` method is deprecated and will " + "The :meth:`_engine.Connection.run_callable` " + "method is deprecated and will " "be removed in a future release. Use a context manager instead.", ) def run_callable(self, callable_, *args, **kwargs): r"""Given a callable object or function, execute it, passing - a :class:`.Connection` as the first argument. + a :class:`_engine.Connection` as the first argument. The given \*args and \**kwargs are passed subsequent - to the :class:`.Connection` argument. + to the :class:`_engine.Connection` argument. - This function, along with :meth:`.Engine.run_callable`, - allows a function to be run with a :class:`.Connection` - or :class:`.Engine` object without the need to know + This function, along with :meth:`_engine.Engine.run_callable`, + allows a function to be run with a :class:`_engine.Connection` + or :class:`_engine.Engine` object without the need to know which one is being dealt with. """ @@ -1761,8 +1784,8 @@ class Transaction(object): """Represent a database transaction in progress. The :class:`.Transaction` object is procured by - calling the :meth:`~.Connection.begin` method of - :class:`.Connection`:: + calling the :meth:`_engine.Connection.begin` method of + :class:`_engine.Connection`:: from sqlalchemy import create_engine engine = create_engine("postgresql://scott:tiger@localhost/test") @@ -1775,7 +1798,7 @@ class Transaction(object): methods in order to control transaction boundaries. It also implements a context manager interface so that the Python ``with`` statement can be used with the - :meth:`.Connection.begin` method:: + :meth:`_engine.Connection.begin` method:: with connection.begin(): connection.execute(text("insert into x (a, b) values (1, 2)")) @@ -1784,11 +1807,11 @@ class Transaction(object): .. seealso:: - :meth:`.Connection.begin` + :meth:`_engine.Connection.begin` - :meth:`.Connection.begin_twophase` + :meth:`_engine.Connection.begin_twophase` - :meth:`.Connection.begin_nested` + :meth:`_engine.Connection.begin_nested` .. index:: single: thread safety; Transaction @@ -1886,7 +1909,7 @@ class NestedTransaction(Transaction): """Represent a 'nested', or SAVEPOINT transaction. A new :class:`.NestedTransaction` object may be procured - using the :meth:`.Connection.begin_nested` method. + using the :meth:`_engine.Connection.begin_nested` method. The interface is the same as that of :class:`.Transaction`. @@ -1917,7 +1940,7 @@ class TwoPhaseTransaction(Transaction): """Represent a two-phase transaction. A new :class:`.TwoPhaseTransaction` object may be procured - using the :meth:`.Connection.begin_twophase` method. + using the :meth:`_engine.Connection.begin_twophase` method. The interface is the same as that of :class:`.Transaction` with the addition of the :meth:`prepare` method. @@ -1954,7 +1977,7 @@ class Engine(Connectable, log.Identified): :class:`~sqlalchemy.engine.interfaces.Dialect` together to provide a source of database connectivity and behavior. - An :class:`.Engine` object is instantiated publicly using the + An :class:`_engine.Engine` object is instantiated publicly using the :func:`~sqlalchemy.create_engine` function. .. seealso:: @@ -1998,7 +2021,7 @@ class Engine(Connectable, log.Identified): def update_execution_options(self, **opt): r"""Update the default execution_options dictionary - of this :class:`.Engine`. + of this :class:`_engine.Engine`. The given keys/values in \**opt are added to the default execution options that will be used for @@ -2008,9 +2031,9 @@ class Engine(Connectable, log.Identified): .. seealso:: - :meth:`.Connection.execution_options` + :meth:`_engine.Connection.execution_options` - :meth:`.Engine.execution_options` + :meth:`_engine.Engine.execution_options` """ self._execution_options = self._execution_options.union(opt) @@ -2018,25 +2041,28 @@ class Engine(Connectable, log.Identified): self.dialect.set_engine_execution_options(self, opt) def execution_options(self, **opt): - """Return a new :class:`.Engine` that will provide - :class:`.Connection` objects with the given execution options. + """Return a new :class:`_engine.Engine` that will provide + :class:`_engine.Connection` objects with the given execution options. - The returned :class:`.Engine` remains related to the original - :class:`.Engine` in that it shares the same connection pool and + The returned :class:`_engine.Engine` remains related to the original + :class:`_engine.Engine` in that it shares the same connection pool and other state: - * The :class:`.Pool` used by the new :class:`.Engine` is the - same instance. The :meth:`.Engine.dispose` method will replace + * The :class:`_pool.Pool` used by the new :class:`_engine.Engine` + is the + same instance. The :meth:`_engine.Engine.dispose` + method will replace the connection pool instance for the parent engine as well as this one. - * Event listeners are "cascaded" - meaning, the new :class:`.Engine` + * Event listeners are "cascaded" - meaning, the new + :class:`_engine.Engine` inherits the events of the parent, and new events can be associated - with the new :class:`.Engine` individually. + with the new :class:`_engine.Engine` individually. * The logging configuration and logging_name is copied from the parent - :class:`.Engine`. + :class:`_engine.Engine`. - The intent of the :meth:`.Engine.execution_options` method is - to implement "sharding" schemes where multiple :class:`.Engine` + The intent of the :meth:`_engine.Engine.execution_options` method is + to implement "sharding" schemes where multiple :class:`_engine.Engine` objects refer to the same connection pool, but are differentiated by options that would be consumed by a custom event:: @@ -2045,15 +2071,18 @@ class Engine(Connectable, log.Identified): shard2 = primary_engine.execution_options(shard_id="shard2") Above, the ``shard1`` engine serves as a factory for - :class:`.Connection` objects that will contain the execution option - ``shard_id=shard1``, and ``shard2`` will produce :class:`.Connection` + :class:`_engine.Connection` + objects that will contain the execution option + ``shard_id=shard1``, and ``shard2`` will produce + :class:`_engine.Connection` objects that contain the execution option ``shard_id=shard2``. An event handler can consume the above execution option to perform a schema switch or other operation, given a connection. Below we emit a MySQL ``use`` statement to switch databases, at the same time keeping track of which database we've established using the - :attr:`.Connection.info` dictionary, which gives us a persistent + :attr:`_engine.Connection.info` dictionary, + which gives us a persistent storage space that follows the DBAPI connection:: from sqlalchemy import event @@ -2073,13 +2102,15 @@ class Engine(Connectable, log.Identified): .. seealso:: - :meth:`.Connection.execution_options` - update execution options - on a :class:`.Connection` object. + :meth:`_engine.Connection.execution_options` + - update execution options + on a :class:`_engine.Connection` object. - :meth:`.Engine.update_execution_options` - update the execution - options for a given :class:`.Engine` in place. + :meth:`_engine.Engine.update_execution_options` + - update the execution + options for a given :class:`_engine.Engine` in place. - :meth:`.Engine.get_execution_options` + :meth:`_engine.Engine.get_execution_options` """ @@ -2092,7 +2123,7 @@ class Engine(Connectable, log.Identified): .. seealso:: - :meth:`.Engine.execution_options` + :meth:`_engine.Engine.execution_options` """ return self._execution_options @@ -2116,20 +2147,23 @@ class Engine(Connectable, log.Identified): return "Engine(%r)" % self.url def dispose(self): - """Dispose of the connection pool used by this :class:`.Engine`. + """Dispose of the connection pool used by this :class:`_engine.Engine` + . This has the effect of fully closing all **currently checked in** database connections. Connections that are still checked out will **not** be closed, however they will no longer be associated - with this :class:`.Engine`, so when they are closed individually, - eventually the :class:`.Pool` which they are associated with will + with this :class:`_engine.Engine`, + so when they are closed individually, + eventually the :class:`_pool.Pool` which they are associated with will be garbage collected and they will be closed out fully, if not already closed on checkin. A new connection pool is created immediately after the old one has been disposed. This new pool, like all SQLAlchemy connection pools, does not make any actual connections to the database until one is - first requested, so as long as the :class:`.Engine` isn't used again, + first requested, so as long as the :class:`_engine.Engine` + isn't used again, no new connections will be made. .. seealso:: @@ -2171,7 +2205,7 @@ class Engine(Connectable, log.Identified): self.conn.close() def begin(self, close_with_result=False): - """Return a context manager delivering a :class:`.Connection` + """Return a context manager delivering a :class:`_engine.Connection` with a :class:`.Transaction` established. E.g.:: @@ -2187,20 +2221,22 @@ class Engine(Connectable, log.Identified): is rolled back. The ``close_with_result`` flag is normally ``False``, and indicates - that the :class:`.Connection` will be closed when the operation + that the :class:`_engine.Connection` will be closed when the operation is complete. When set to ``True``, it indicates the - :class:`.Connection` is in "single use" mode, where the + :class:`_engine.Connection` is in "single use" mode, where the :class:`.ResultProxy` returned by the first call to - :meth:`.Connection.execute` will close the :class:`.Connection` when + :meth:`_engine.Connection.execute` will close the + :class:`_engine.Connection` when that :class:`.ResultProxy` has exhausted all result rows. .. seealso:: - :meth:`.Engine.connect` - procure a :class:`.Connection` from - an :class:`.Engine`. + :meth:`_engine.Engine.connect` - procure a + :class:`_engine.Connection` from + an :class:`_engine.Engine`. - :meth:`.Connection.begin` - start a :class:`.Transaction` - for a particular :class:`.Connection`. + :meth:`_engine.Connection.begin` - start a :class:`.Transaction` + for a particular :class:`_engine.Connection`. """ conn = self.connect(close_with_result=close_with_result) @@ -2213,15 +2249,17 @@ class Engine(Connectable, log.Identified): @util.deprecated( "1.4", - "The :meth:`.Engine.transaction` method is deprecated and will be " - "removed in a future release. Use the :meth:`.Engine.begin` context " + "The :meth:`_engine.Engine.transaction` " + "method is deprecated and will be " + "removed in a future release. Use the :meth:`_engine.Engine.begin` " + "context " "manager instead.", ) def transaction(self, callable_, *args, **kwargs): r"""Execute the given function within a transaction boundary. - The function is passed a :class:`.Connection` newly procured - from :meth:`.Engine.connect` as the first argument, + The function is passed a :class:`_engine.Connection` newly procured + from :meth:`_engine.Engine.connect` as the first argument, followed by the given \*args and \**kwargs. e.g.:: @@ -2241,18 +2279,19 @@ class Engine(Connectable, log.Identified): The :meth:`.transaction` method is superseded by the usage of the Python ``with:`` statement, which can - be used with :meth:`.Engine.begin`:: + be used with :meth:`_engine.Engine.begin`:: with engine.begin() as conn: conn.execute(text("some statement"), {'x':5, 'y':10}) .. seealso:: - :meth:`.Engine.begin` - engine-level transactional + :meth:`_engine.Engine.begin` - engine-level transactional context - :meth:`.Connection.transaction` - connection-level version of - :meth:`.Engine.transaction` + :meth:`_engine.Connection.transaction` + - connection-level version of + :meth:`_engine.Engine.transaction` """ kwargs["_sa_skip_warning"] = True @@ -2261,20 +2300,21 @@ class Engine(Connectable, log.Identified): @util.deprecated( "1.4", - "The :meth:`.Engine.run_callable` method is deprecated and will be " - "removed in a future release. Use the :meth:`.Engine.connect` " + "The :meth:`_engine.Engine.run_callable` " + "method is deprecated and will be " + "removed in a future release. Use the :meth:`_engine.Engine.connect` " "context manager instead.", ) def run_callable(self, callable_, *args, **kwargs): r"""Given a callable object or function, execute it, passing - a :class:`.Connection` as the first argument. + a :class:`_engine.Connection` as the first argument. The given \*args and \**kwargs are passed subsequent - to the :class:`.Connection` argument. + to the :class:`_engine.Connection` argument. - This function, along with :meth:`.Connection.run_callable`, - allows a function to be run with a :class:`.Connection` - or :class:`.Engine` object without the need to know + This function, along with :meth:`_engine.Connection.run_callable`, + allows a function to be run with a :class:`_engine.Connection` + or :class:`_engine.Engine` object without the need to know which one is being dealt with. """ @@ -2287,9 +2327,10 @@ class Engine(Connectable, log.Identified): conn._run_ddl_visitor(visitorcallable, element, **kwargs) @util.deprecated_20( - ":meth:`.Engine.execute`", + ":meth:`_engine.Engine.execute`", alternative="All statement execution in SQLAlchemy 2.0 is performed " - "by the :meth:`.Connection.execute` method of :class:`.Connection`, " + "by the :meth:`_engine.Connection.execute` method of " + ":class:`_engine.Connection`, " "or in the ORM by the :meth:`.Session.execute` method of " ":class:`.Session`.", ) @@ -2297,13 +2338,14 @@ class Engine(Connectable, log.Identified): """Executes the given construct and returns a :class:`.ResultProxy`. The arguments are the same as those used by - :meth:`.Connection.execute`. + :meth:`_engine.Connection.execute`. - Here, a :class:`.Connection` is acquired using the - :meth:`~.Engine.connect` method, and the statement executed + Here, a :class:`_engine.Connection` is acquired using the + :meth:`_engine.Engine.connect` method, and the statement executed with that connection. The returned :class:`.ResultProxy` is flagged such that when the :class:`.ResultProxy` is exhausted and its - underlying cursor is closed, the :class:`.Connection` created here + underlying cursor is closed, the :class:`_engine.Connection` + created here will also be closed, which allows its associated DBAPI connection resource to be returned to the connection pool. @@ -2312,9 +2354,10 @@ class Engine(Connectable, log.Identified): return connection.execute(statement, *multiparams, **params) @util.deprecated_20( - ":meth:`.Engine.scalar`", + ":meth:`_engine.Engine.scalar`", alternative="All statement execution in SQLAlchemy 2.0 is performed " - "by the :meth:`.Connection.execute` method of :class:`.Connection`, " + "by the :meth:`_engine.Connection.execute` method of " + ":class:`_engine.Connection`, " "or in the ORM by the :meth:`.Session.execute` method of " ":class:`.Session`; the :meth:`.Result.scalar` method can then be " "used to return a scalar result.", @@ -2335,16 +2378,17 @@ class Engine(Connectable, log.Identified): return connection._execute_compiled(compiled, multiparams, params) def connect(self, close_with_result=False): - """Return a new :class:`.Connection` object. + """Return a new :class:`_engine.Connection` object. - The :class:`.Connection` object is a facade that uses a DBAPI + The :class:`_engine.Connection` object is a facade that uses a DBAPI connection internally in order to communicate with the database. This - connection is procured from the connection-holding :class:`.Pool` - referenced by this :class:`.Engine`. When the - :meth:`~.Connection.close` method of the :class:`.Connection` object + connection is procured from the connection-holding :class:`_pool.Pool` + referenced by this :class:`_engine.Engine`. When the + :meth:`_engine.Connection.close` method of the + :class:`_engine.Connection` object is called, the underlying DBAPI connection is then returned to the connection pool, where it may be used again in a subsequent call to - :meth:`~.Engine.connect`. + :meth:`_engine.Engine.connect`. """ @@ -2352,9 +2396,10 @@ class Engine(Connectable, log.Identified): @util.deprecated( "1.4", - "The :meth:`.Engine.table_names` method is deprecated and will be " + "The :meth:`_engine.Engine.table_names` " + "method is deprecated and will be " "removed in a future release. Please refer to " - ":meth:`.Inspector.get_table_names`.", + ":meth:`_reflection.Inspector.get_table_names`.", ) def table_names(self, schema=None, connection=None): """Return a list of all table names available in the database. @@ -2369,9 +2414,10 @@ class Engine(Connectable, log.Identified): @util.deprecated( "1.4", - "The :meth:`.Engine.has_table` method is deprecated and will be " + "The :meth:`_engine.Engine.has_table` " + "method is deprecated and will be " "removed in a future release. Please refer to " - ":meth:`.Inspector.has_table`.", + ":meth:`_reflection.Inspector.has_table`.", ) def has_table(self, table_name, schema=None): """Return True if the given backend has a table of the given name. @@ -2379,7 +2425,7 @@ class Engine(Connectable, log.Identified): .. seealso:: :ref:`metadata_reflection_inspector` - detailed schema inspection - using the :class:`.Inspector` interface. + using the :class:`_reflection.Inspector` interface. :class:`.quoted_name` - used to pass quoting information along with a schema identifier. @@ -2414,10 +2460,11 @@ class Engine(Connectable, log.Identified): for real. This method provides direct DBAPI connection access for - special situations when the API provided by :class:`.Connection` - is not needed. When a :class:`.Connection` object is already + special situations when the API provided by + :class:`_engine.Connection` + is not needed. When a :class:`_engine.Connection` object is already present, the DBAPI connection is available using - the :attr:`.Connection.connection` accessor. + the :attr:`_engine.Connection.connection` accessor. .. seealso:: diff --git a/lib/sqlalchemy/engine/create.py b/lib/sqlalchemy/engine/create.py index 2831f5e7d..3c1345c63 100644 --- a/lib/sqlalchemy/engine/create.py +++ b/lib/sqlalchemy/engine/create.py @@ -43,7 +43,7 @@ from ..sql import compiler ), ) def create_engine(url, **kwargs): - """Create a new :class:`.Engine` instance. + """Create a new :class:`_engine.Engine` instance. The standard calling form is to send the URL as the first positional argument, usually a string @@ -53,8 +53,8 @@ def create_engine(url, **kwargs): engine = create_engine("postgresql://scott:tiger@localhost/test") Additional keyword arguments may then follow it which - establish various options on the resulting :class:`.Engine` - and its underlying :class:`.Dialect` and :class:`.Pool` + establish various options on the resulting :class:`_engine.Engine` + and its underlying :class:`.Dialect` and :class:`_pool.Pool` constructs:: engine = create_engine("mysql://scott:tiger@hostname/dbname", @@ -69,15 +69,17 @@ def create_engine(url, **kwargs): ``**kwargs`` takes a wide variety of options which are routed towards their appropriate components. Arguments may be specific to - the :class:`.Engine`, the underlying :class:`.Dialect`, as well as the - :class:`.Pool`. Specific dialects also accept keyword arguments that + the :class:`_engine.Engine`, the underlying :class:`.Dialect`, + as well as the + :class:`_pool.Pool`. Specific dialects also accept keyword arguments that are unique to that dialect. Here, we describe the parameters that are common to most :func:`.create_engine()` usage. - Once established, the newly resulting :class:`.Engine` will - request a connection from the underlying :class:`.Pool` once - :meth:`.Engine.connect` is called, or a method which depends on it - such as :meth:`.Engine.execute` is invoked. The :class:`.Pool` in turn + Once established, the newly resulting :class:`_engine.Engine` will + request a connection from the underlying :class:`_pool.Pool` once + :meth:`_engine.Engine.connect` is called, or a method which depends on it + such as :meth:`_engine.Engine.execute` is invoked. The + :class:`_pool.Pool` in turn will establish the first actual DBAPI connection when this request is received. The :func:`.create_engine` call itself does **not** establish any actual DBAPI connections directly. @@ -233,16 +235,17 @@ def create_engine(url, **kwargs): individual dialects should be consulted directly. Note that the isolation level can also be set on a - per-:class:`.Connection` basis as well, using the + per-:class:`_engine.Connection` basis as well, using the :paramref:`.Connection.execution_options.isolation_level` feature. .. seealso:: - :attr:`.Connection.default_isolation_level` - view default level + :attr:`_engine.Connection.default_isolation_level` + - view default level :paramref:`.Connection.execution_options.isolation_level` - - set per :class:`.Connection` isolation level + - set per :class:`_engine.Connection` isolation level :ref:`SQLite Transaction Isolation <sqlite_isolation_level>` @@ -252,7 +255,8 @@ def create_engine(url, **kwargs): :ref:`session_transaction_isolation` - for the ORM - :param json_deserializer: for dialects that support the :class:`.JSON` + :param json_deserializer: for dialects that support the + :class:`_types.JSON` datatype, this is a Python callable that will convert a JSON string to a Python object. By default, the Python ``json.loads`` function is used. @@ -260,7 +264,7 @@ def create_engine(url, **kwargs): .. versionchanged:: 1.3.7 The SQLite dialect renamed this from ``_json_deserializer``. - :param json_serializer: for dialects that support the :class:`.JSON` + :param json_serializer: for dialects that support the :class:`_types.JSON` datatype, this is a Python callable that will render a given object as JSON. By default, the Python ``json.dumps`` function is used. @@ -317,7 +321,7 @@ def create_engine(url, **kwargs): specific DBAPI which will be imported before first connect. This parameter causes the import to be bypassed, and the given module to be used instead. Can be used for testing of DBAPIs as well as to - inject "mock" DBAPI implementations into the :class:`.Engine`. + inject "mock" DBAPI implementations into the :class:`_engine.Engine`. :param paramstyle=None: The `paramstyle <http://legacy.python.org/dev/peps/pep-0249/#paramstyle>`_ to use when rendering bound parameters. This style defaults to the @@ -382,13 +386,13 @@ def create_engine(url, **kwargs): :ref:`pool_setting_recycle` :param pool_reset_on_return='rollback': set the - :paramref:`.Pool.reset_on_return` parameter of the underlying - :class:`.Pool` object, which can be set to the values + :paramref:`_pool.Pool.reset_on_return` parameter of the underlying + :class:`_pool.Pool` object, which can be set to the values ``"rollback"``, ``"commit"``, or ``None``. .. seealso:: - :paramref:`.Pool.reset_on_return` + :paramref:`_pool.Pool.reset_on_return` :param pool_timeout=30: number of seconds to wait before giving up on getting a connection from the pool. This is only used diff --git a/lib/sqlalchemy/engine/default.py b/lib/sqlalchemy/engine/default.py index 43ebce83a..5b8cb635c 100644 --- a/lib/sqlalchemy/engine/default.py +++ b/lib/sqlalchemy/engine/default.py @@ -446,7 +446,7 @@ class DefaultDialect(interfaces.Dialect): This method looks for a dictionary called ``colspecs`` as a class or instance-level variable, - and passes on to :func:`.types.adapt_type`. + and passes on to :func:`_types.adapt_type`. """ return sqltypes.adapt_type(typeobj, self.colspecs) @@ -1446,12 +1446,13 @@ class DefaultExecutionContext(interfaces.ExecutionContext): generation function, e.g. as described at :ref:`context_default_functions`. It consists of a dictionary which includes entries for each column/value pair that is to be part of the INSERT or UPDATE statement. The keys of the - dictionary will be the key value of each :class:`.Column`, which is usually + dictionary will be the key value of each :class:`_schema.Column`, + which is usually synonymous with the name. Note that the :attr:`.DefaultExecutionContext.current_parameters` attribute does not accommodate for the "multi-values" feature of the - :meth:`.Insert.values` method. The + :meth:`_expression.Insert.values` method. The :meth:`.DefaultExecutionContext.get_current_parameters` method should be preferred. @@ -1471,11 +1472,13 @@ class DefaultExecutionContext(interfaces.ExecutionContext): :ref:`context_default_functions`. When invoked, a dictionary is returned which includes entries for each column/value pair that is part of the INSERT or UPDATE statement. The keys of the dictionary will be - the key value of each :class:`.Column`, which is usually synonymous + the key value of each :class:`_schema.Column`, + which is usually synonymous with the name. :param isolate_multiinsert_groups=True: indicates that multi-valued - INSERT constructs created using :meth:`.Insert.values` should be + INSERT constructs created using :meth:`_expression.Insert.values` + should be handled by returning only the subset of parameters that are local to the current column default invocation. When ``False``, the raw parameters of the statement are returned including the diff --git a/lib/sqlalchemy/engine/events.py b/lib/sqlalchemy/engine/events.py index 32292c826..46459cf73 100644 --- a/lib/sqlalchemy/engine/events.py +++ b/lib/sqlalchemy/engine/events.py @@ -15,13 +15,13 @@ from .. import exc class ConnectionEvents(event.Events): """Available events for :class:`.Connectable`, which includes - :class:`.Connection` and :class:`.Engine`. + :class:`_engine.Connection` and :class:`_engine.Engine`. The methods here define the name of an event as well as the names of members that are passed to listener functions. An event listener can be associated with any :class:`.Connectable` - class or instance, such as an :class:`.Engine`, e.g.:: + class or instance, such as an :class:`_engine.Engine`, e.g.:: from sqlalchemy import event, create_engine @@ -32,7 +32,7 @@ class ConnectionEvents(event.Events): engine = create_engine('postgresql://scott:tiger@localhost/test') event.listen(engine, "before_cursor_execute", before_cursor_execute) - or with a specific :class:`.Connection`:: + or with a specific :class:`_engine.Connection`:: with engine.begin() as conn: @event.listens_for(conn, 'before_cursor_execute') @@ -62,19 +62,23 @@ class ConnectionEvents(event.Events): return statement, parameters .. note:: :class:`.ConnectionEvents` can be established on any - combination of :class:`.Engine`, :class:`.Connection`, as well + combination of :class:`_engine.Engine`, :class:`_engine.Connection`, + as well as instances of each of those classes. Events across all four scopes will fire off for a given instance of - :class:`.Connection`. However, for performance reasons, the - :class:`.Connection` object determines at instantiation time - whether or not its parent :class:`.Engine` has event listeners - established. Event listeners added to the :class:`.Engine` - class or to an instance of :class:`.Engine` *after* the instantiation - of a dependent :class:`.Connection` instance will usually - *not* be available on that :class:`.Connection` instance. The newly - added listeners will instead take effect for :class:`.Connection` + :class:`_engine.Connection`. However, for performance reasons, the + :class:`_engine.Connection` object determines at instantiation time + whether or not its parent :class:`_engine.Engine` has event listeners + established. Event listeners added to the :class:`_engine.Engine` + class or to an instance of :class:`_engine.Engine` + *after* the instantiation + of a dependent :class:`_engine.Connection` instance will usually + *not* be available on that :class:`_engine.Connection` instance. + The newly + added listeners will instead take effect for + :class:`_engine.Connection` instances created subsequent to those event listeners being - established on the parent :class:`.Engine` class or instance. + established on the parent :class:`_engine.Engine` class or instance. :param retval=False: Applies to the :meth:`.before_execute` and :meth:`.before_cursor_execute` events only. When True, the @@ -156,9 +160,10 @@ class ConnectionEvents(event.Events): # do something with clauseelement, multiparams, params return clauseelement, multiparams, params - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object :param clauseelement: SQL expression construct, :class:`.Compiled` - instance, or string statement passed to :meth:`.Connection.execute`. + instance, or string statement passed to + :meth:`_engine.Connection.execute`. :param multiparams: Multiple parameter sets, a list of dictionaries. :param params: Single parameter set, a single dictionary. @@ -172,9 +177,10 @@ class ConnectionEvents(event.Events): """Intercept high level execute() events after execute. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object :param clauseelement: SQL expression construct, :class:`.Compiled` - instance, or string statement passed to :meth:`.Connection.execute`. + instance, or string statement passed to + :meth:`_engine.Connection.execute`. :param multiparams: Multiple parameter sets, a list of dictionaries. :param params: Single parameter set, a single dictionary. :param result: :class:`.ResultProxy` generated by the execution. @@ -204,7 +210,7 @@ class ConnectionEvents(event.Events): See the example at :class:`.ConnectionEvents`. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object :param cursor: DBAPI cursor object :param statement: string SQL statement, as to be passed to the DBAPI :param parameters: Dictionary, tuple, or list of parameters being @@ -228,7 +234,7 @@ class ConnectionEvents(event.Events): ): """Intercept low-level cursor execute() events after execution. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object :param cursor: DBAPI cursor object. Will have results pending if the statement was a SELECT, but these should not be consumed as they will be needed by the :class:`.ResultProxy`. @@ -244,7 +250,8 @@ class ConnectionEvents(event.Events): """ def handle_error(self, exception_context): - r"""Intercept all exceptions processed by the :class:`.Connection`. + r"""Intercept all exceptions processed by the + :class:`_engine.Connection`. This includes all exceptions emitted by the DBAPI as well as within SQLAlchemy's statement invocation process, including @@ -362,9 +369,9 @@ class ConnectionEvents(event.Events): ``False``. .. versionchanged:: 1.0.0 The :meth:`.handle_error` event is now - invoked when an :class:`.Engine` fails during the initial - call to :meth:`.Engine.connect`, as well as when a - :class:`.Connection` object encounters an error during a + invoked when an :class:`_engine.Engine` fails during the initial + call to :meth:`_engine.Engine.connect`, as well as when a + :class:`_engine.Connection` object encounters an error during a reconnect operation. .. versionchanged:: 1.0.0 The :meth:`.handle_error` event is @@ -380,32 +387,39 @@ class ConnectionEvents(event.Events): """ def engine_connect(self, conn, branch): - """Intercept the creation of a new :class:`.Connection`. + """Intercept the creation of a new :class:`_engine.Connection`. This event is called typically as the direct result of calling - the :meth:`.Engine.connect` method. + the :meth:`_engine.Engine.connect` method. - It differs from the :meth:`.PoolEvents.connect` method, which + It differs from the :meth:`_events.PoolEvents.connect` method, which refers to the actual connection to a database at the DBAPI level; a DBAPI connection may be pooled and reused for many operations. In contrast, this event refers only to the production of a higher level - :class:`.Connection` wrapper around such a DBAPI connection. + :class:`_engine.Connection` wrapper around such a DBAPI connection. - It also differs from the :meth:`.PoolEvents.checkout` event - in that it is specific to the :class:`.Connection` object, not the - DBAPI connection that :meth:`.PoolEvents.checkout` deals with, although + It also differs from the :meth:`_events.PoolEvents.checkout` event + in that it is specific to the :class:`_engine.Connection` object, + not the + DBAPI connection that :meth:`_events.PoolEvents.checkout` deals with, + although this DBAPI connection is available here via the - :attr:`.Connection.connection` attribute. But note there can in fact - be multiple :meth:`.PoolEvents.checkout` events within the lifespan - of a single :class:`.Connection` object, if that :class:`.Connection` + :attr:`_engine.Connection.connection` attribute. + But note there can in fact + be multiple :meth:`_events.PoolEvents.checkout` + events within the lifespan + of a single :class:`_engine.Connection` object, if that + :class:`_engine.Connection` is invalidated and re-established. There can also be multiple - :class:`.Connection` objects generated for the same already-checked-out - DBAPI connection, in the case that a "branch" of a :class:`.Connection` + :class:`_engine.Connection` + objects generated for the same already-checked-out + DBAPI connection, in the case that a "branch" of a + :class:`_engine.Connection` is produced. - :param conn: :class:`.Connection` object. + :param conn: :class:`_engine.Connection` object. :param branch: if True, this is a "branch" of an existing - :class:`.Connection`. A branch is generated within the course + :class:`_engine.Connection`. A branch is generated within the course of a statement execution to invoke supplemental statements, most typically to pre-execute a SELECT of a default value for the purposes of an INSERT statement. @@ -419,81 +433,91 @@ class ConnectionEvents(event.Events): to transparently ensure pooled connections are connected to the database. - :meth:`.PoolEvents.checkout` the lower-level pool checkout event + :meth:`_events.PoolEvents.checkout` + the lower-level pool checkout event for an individual DBAPI connection :meth:`.ConnectionEvents.set_connection_execution_options` - a copy - of a :class:`.Connection` is also made when the - :meth:`.Connection.execution_options` method is called. + of a :class:`_engine.Connection` is also made when the + :meth:`_engine.Connection.execution_options` method is called. """ def set_connection_execution_options(self, conn, opts): - """Intercept when the :meth:`.Connection.execution_options` + """Intercept when the :meth:`_engine.Connection.execution_options` method is called. - This method is called after the new :class:`.Connection` has been + This method is called after the new :class:`_engine.Connection` + has been produced, with the newly updated execution options collection, but before the :class:`.Dialect` has acted upon any of those new options. - Note that this method is not called when a new :class:`.Connection` + Note that this method is not called when a new + :class:`_engine.Connection` is produced which is inheriting execution options from its parent - :class:`.Engine`; to intercept this condition, use the + :class:`_engine.Engine`; to intercept this condition, use the :meth:`.ConnectionEvents.engine_connect` event. - :param conn: The newly copied :class:`.Connection` object + :param conn: The newly copied :class:`_engine.Connection` object :param opts: dictionary of options that were passed to the - :meth:`.Connection.execution_options` method. + :meth:`_engine.Connection.execution_options` method. .. versionadded:: 0.9.0 .. seealso:: :meth:`.ConnectionEvents.set_engine_execution_options` - event - which is called when :meth:`.Engine.execution_options` is called. + which is called when :meth:`_engine.Engine.execution_options` + is called. """ def set_engine_execution_options(self, engine, opts): - """Intercept when the :meth:`.Engine.execution_options` + """Intercept when the :meth:`_engine.Engine.execution_options` method is called. - The :meth:`.Engine.execution_options` method produces a shallow - copy of the :class:`.Engine` which stores the new options. That new - :class:`.Engine` is passed here. A particular application of this + The :meth:`_engine.Engine.execution_options` method produces a shallow + copy of the :class:`_engine.Engine` which stores the new options. + That new + :class:`_engine.Engine` is passed here. + A particular application of this method is to add a :meth:`.ConnectionEvents.engine_connect` event - handler to the given :class:`.Engine` which will perform some per- - :class:`.Connection` task specific to these execution options. + handler to the given :class:`_engine.Engine` + which will perform some per- + :class:`_engine.Connection` task specific to these execution options. - :param conn: The newly copied :class:`.Engine` object + :param conn: The newly copied :class:`_engine.Engine` object :param opts: dictionary of options that were passed to the - :meth:`.Connection.execution_options` method. + :meth:`_engine.Connection.execution_options` method. .. versionadded:: 0.9.0 .. seealso:: :meth:`.ConnectionEvents.set_connection_execution_options` - event - which is called when :meth:`.Connection.execution_options` is + which is called when :meth:`_engine.Connection.execution_options` + is called. """ def engine_disposed(self, engine): - """Intercept when the :meth:`.Engine.dispose` method is called. + """Intercept when the :meth:`_engine.Engine.dispose` method is called. - The :meth:`.Engine.dispose` method instructs the engine to - "dispose" of it's connection pool (e.g. :class:`.Pool`), and + The :meth:`_engine.Engine.dispose` method instructs the engine to + "dispose" of it's connection pool (e.g. :class:`_pool.Pool`), and replaces it with a new one. Disposing of the old pool has the effect that existing checked-in connections are closed. The new pool does not establish any new connections until it is first used. This event can be used to indicate that resources related to the - :class:`.Engine` should also be cleaned up, keeping in mind that the - :class:`.Engine` can still be used for new requests in which case + :class:`_engine.Engine` should also be cleaned up, + keeping in mind that the + :class:`_engine.Engine` + can still be used for new requests in which case it re-acquires connection resources. .. versionadded:: 1.0.5 @@ -503,7 +527,7 @@ class ConnectionEvents(event.Events): def begin(self, conn): """Intercept begin() events. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object """ @@ -511,17 +535,17 @@ class ConnectionEvents(event.Events): """Intercept rollback() events, as initiated by a :class:`.Transaction`. - Note that the :class:`.Pool` also "auto-rolls back" + Note that the :class:`_pool.Pool` also "auto-rolls back" a DBAPI connection upon checkin, if the ``reset_on_return`` flag is set to its default value of ``'rollback'``. To intercept this - rollback, use the :meth:`.PoolEvents.reset` hook. + rollback, use the :meth:`_events.PoolEvents.reset` hook. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object .. seealso:: - :meth:`.PoolEvents.reset` + :meth:`_events.PoolEvents.reset` """ @@ -529,18 +553,18 @@ class ConnectionEvents(event.Events): """Intercept commit() events, as initiated by a :class:`.Transaction`. - Note that the :class:`.Pool` may also "auto-commit" + Note that the :class:`_pool.Pool` may also "auto-commit" a DBAPI connection upon checkin, if the ``reset_on_return`` flag is set to the value ``'commit'``. To intercept this - commit, use the :meth:`.PoolEvents.reset` hook. + commit, use the :meth:`_events.PoolEvents.reset` hook. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object """ def savepoint(self, conn, name): """Intercept savepoint() events. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object :param name: specified name used for the savepoint. """ @@ -548,7 +572,7 @@ class ConnectionEvents(event.Events): def rollback_savepoint(self, conn, name, context): """Intercept rollback_savepoint() events. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object :param name: specified name used for the savepoint. :param context: :class:`.ExecutionContext` in use. May be ``None``. @@ -557,7 +581,7 @@ class ConnectionEvents(event.Events): def release_savepoint(self, conn, name, context): """Intercept release_savepoint() events. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object :param name: specified name used for the savepoint. :param context: :class:`.ExecutionContext` in use. May be ``None``. @@ -566,7 +590,7 @@ class ConnectionEvents(event.Events): def begin_twophase(self, conn, xid): """Intercept begin_twophase() events. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object :param xid: two-phase XID identifier """ @@ -574,14 +598,14 @@ class ConnectionEvents(event.Events): def prepare_twophase(self, conn, xid): """Intercept prepare_twophase() events. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object :param xid: two-phase XID identifier """ def rollback_twophase(self, conn, xid, is_prepared): """Intercept rollback_twophase() events. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object :param xid: two-phase XID identifier :param is_prepared: boolean, indicates if :meth:`.TwoPhaseTransaction.prepare` was called. @@ -591,7 +615,7 @@ class ConnectionEvents(event.Events): def commit_twophase(self, conn, xid, is_prepared): """Intercept commit_twophase() events. - :param conn: :class:`.Connection` object + :param conn: :class:`_engine.Connection` object :param xid: two-phase XID identifier :param is_prepared: boolean, indicates if :meth:`.TwoPhaseTransaction.prepare` was called. diff --git a/lib/sqlalchemy/engine/interfaces.py b/lib/sqlalchemy/engine/interfaces.py index 6cf4d7dbd..224d4f693 100644 --- a/lib/sqlalchemy/engine/interfaces.py +++ b/lib/sqlalchemy/engine/interfaces.py @@ -185,7 +185,7 @@ class Dialect(object): """Transform a generic type to a dialect-specific type. Dialect classes will usually use the - :func:`.types.adapt_type` function in the types module to + :func:`_types.adapt_type` function in the types module to accomplish this. The returned result is cached *per dialect class* so can @@ -215,7 +215,7 @@ class Dialect(object): def get_columns(self, connection, table_name, schema=None, **kw): """Return information about columns in `table_name`. - Given a :class:`.Connection`, a string + Given a :class:`_engine.Connection`, a string `table_name`, and an optional string `schema`, return column information as a list of dictionaries with these keys: @@ -249,7 +249,7 @@ class Dialect(object): """Return information about the primary key constraint on table_name`. - Given a :class:`.Connection`, a string + Given a :class:`_engine.Connection`, a string `table_name`, and an optional string `schema`, return primary key information as a dictionary with these keys: @@ -265,7 +265,7 @@ class Dialect(object): def get_foreign_keys(self, connection, table_name, schema=None, **kw): """Return information about foreign_keys in `table_name`. - Given a :class:`.Connection`, a string + Given a :class:`_engine.Connection`, a string `table_name`, and an optional string `schema`, return foreign key information as a list of dicts with these keys: @@ -321,7 +321,7 @@ class Dialect(object): def get_view_definition(self, connection, view_name, schema=None, **kw): """Return view definition. - Given a :class:`.Connection`, a string + Given a :class:`_engine.Connection`, a string `view_name`, and an optional string `schema`, return the view definition. """ @@ -331,7 +331,7 @@ class Dialect(object): def get_indexes(self, connection, table_name, schema=None, **kw): """Return information about indexes in `table_name`. - Given a :class:`.Connection`, a string + Given a :class:`_engine.Connection`, a string `table_name` and an optional string `schema`, return index information as a list of dictionaries with these keys: @@ -434,7 +434,7 @@ class Dialect(object): def has_table(self, connection, table_name, schema=None, **kw): """Check the existence of a particular table in the database. - Given a :class:`.Connection` object and a string + Given a :class:`_engine.Connection` object and a string `table_name`, return True if the given table (possibly within the specified `schema`) exists in the database, False otherwise. @@ -445,7 +445,7 @@ class Dialect(object): def has_index(self, connection, table_name, index_name, schema=None): """Check the existence of a particular index name in the database. - Given a :class:`.Connection` object, a string + Given a :class:`_engine.Connection` object, a string `table_name` and stiring index name, return True if an index of the given name on the given table exists, false otherwise. @@ -463,7 +463,7 @@ class Dialect(object): def has_sequence(self, connection, sequence_name, schema=None, **kw): """Check the existence of a particular sequence in the database. - Given a :class:`.Connection` object and a string + Given a :class:`_engine.Connection` object and a string `sequence_name`, return True if the given sequence exists in the database, False otherwise. """ @@ -506,7 +506,8 @@ class Dialect(object): :meth:`.Dialect.do_autocommit` hook is provided for DBAPIs that need some extra commands emitted after a commit in order to enter the next transaction, when the - SQLAlchemy :class:`.Connection` is used in its default "autocommit" + SQLAlchemy :class:`_engine.Connection` + is used in its default "autocommit" mode. :param dbapi_connection: a DBAPI connection, typically @@ -542,7 +543,8 @@ class Dialect(object): """Provide an implementation of ``connection.close()``, given a DBAPI connection. - This hook is called by the :class:`.Pool` when a connection has been + This hook is called by the :class:`_pool.Pool` + when a connection has been detached from the pool, or is being returned beyond the normal capacity of the pool. @@ -563,7 +565,7 @@ class Dialect(object): def do_savepoint(self, connection, name): """Create a savepoint with the given name. - :param connection: a :class:`.Connection`. + :param connection: a :class:`_engine.Connection`. :param name: savepoint name. """ @@ -573,7 +575,7 @@ class Dialect(object): def do_rollback_to_savepoint(self, connection, name): """Rollback a connection to the named savepoint. - :param connection: a :class:`.Connection`. + :param connection: a :class:`_engine.Connection`. :param name: savepoint name. """ @@ -583,7 +585,7 @@ class Dialect(object): def do_release_savepoint(self, connection, name): """Release the named savepoint on a connection. - :param connection: a :class:`.Connection`. + :param connection: a :class:`_engine.Connection`. :param name: savepoint name. """ @@ -592,7 +594,7 @@ class Dialect(object): def do_begin_twophase(self, connection, xid): """Begin a two phase transaction on the given connection. - :param connection: a :class:`.Connection`. + :param connection: a :class:`_engine.Connection`. :param xid: xid """ @@ -602,7 +604,7 @@ class Dialect(object): def do_prepare_twophase(self, connection, xid): """Prepare a two phase transaction on the given connection. - :param connection: a :class:`.Connection`. + :param connection: a :class:`_engine.Connection`. :param xid: xid """ @@ -614,7 +616,7 @@ class Dialect(object): ): """Rollback a two phase transaction on the given connection. - :param connection: a :class:`.Connection`. + :param connection: a :class:`_engine.Connection`. :param xid: xid :param is_prepared: whether or not :meth:`.TwoPhaseTransaction.prepare` was called. @@ -630,7 +632,7 @@ class Dialect(object): """Commit a two phase transaction on the given connection. - :param connection: a :class:`.Connection`. + :param connection: a :class:`_engine.Connection`. :param xid: xid :param is_prepared: whether or not :meth:`.TwoPhaseTransaction.prepare` was called. @@ -644,7 +646,7 @@ class Dialect(object): """Recover list of uncommitted prepared two phase transaction identifiers on the given connection. - :param connection: a :class:`.Connection`. + :param connection: a :class:`_engine.Connection`. """ @@ -734,11 +736,13 @@ class Dialect(object): isolation modes, Unicode modes, etc. The "do_on_connect" callable is invoked by using the - :meth:`.PoolEvents.first_connect` and :meth:`.PoolEvents.connect` event + :meth:`_events.PoolEvents.first_connect` and + :meth:`_events.PoolEvents.connect` event hooks, then unwrapping the DBAPI connection and passing it into the callable. The reason it is invoked for both events is so that any dialect-level initialization that occurs upon first connection, which - also makes use of the :meth:`.PoolEvents.first_connect` method, will + also makes use of the :meth:`_events.PoolEvents.first_connect` method, + will proceed after this hook has been called. This currently means the hook is in fact called twice for the very first connection in which a dialect creates; and once per connection afterwards. @@ -760,22 +764,24 @@ class Dialect(object): """Given a DBAPI connection, revert its isolation to the default. Note that this is a dialect-level method which is used as part - of the implementation of the :class:`.Connection` and - :class:`.Engine` + of the implementation of the :class:`_engine.Connection` and + :class:`_engine.Engine` isolation level facilities; these APIs should be preferred for most typical use cases. .. seealso:: - :meth:`.Connection.get_isolation_level` - view current level + :meth:`_engine.Connection.get_isolation_level` + - view current level - :attr:`.Connection.default_isolation_level` - view default level + :attr:`_engine.Connection.default_isolation_level` + - view default level :paramref:`.Connection.execution_options.isolation_level` - - set per :class:`.Connection` isolation level + set per :class:`_engine.Connection` isolation level :paramref:`.create_engine.isolation_level` - - set per :class:`.Engine` isolation level + set per :class:`_engine.Engine` isolation level """ @@ -785,22 +791,24 @@ class Dialect(object): """Given a DBAPI connection, set its isolation level. Note that this is a dialect-level method which is used as part - of the implementation of the :class:`.Connection` and - :class:`.Engine` + of the implementation of the :class:`_engine.Connection` and + :class:`_engine.Engine` isolation level facilities; these APIs should be preferred for most typical use cases. .. seealso:: - :meth:`.Connection.get_isolation_level` - view current level + :meth:`_engine.Connection.get_isolation_level` + - view current level - :attr:`.Connection.default_isolation_level` - view default level + :attr:`_engine.Connection.default_isolation_level` + - view default level :paramref:`.Connection.execution_options.isolation_level` - - set per :class:`.Connection` isolation level + set per :class:`_engine.Connection` isolation level :paramref:`.create_engine.isolation_level` - - set per :class:`.Engine` isolation level + set per :class:`_engine.Engine` isolation level """ @@ -809,27 +817,30 @@ class Dialect(object): def get_isolation_level(self, dbapi_conn): """Given a DBAPI connection, return its isolation level. - When working with a :class:`.Connection` object, the corresponding + When working with a :class:`_engine.Connection` object, + the corresponding DBAPI connection may be procured using the - :attr:`.Connection.connection` accessor. + :attr:`_engine.Connection.connection` accessor. Note that this is a dialect-level method which is used as part - of the implementation of the :class:`.Connection` and - :class:`.Engine` isolation level facilities; + of the implementation of the :class:`_engine.Connection` and + :class:`_engine.Engine` isolation level facilities; these APIs should be preferred for most typical use cases. .. seealso:: - :meth:`.Connection.get_isolation_level` - view current level + :meth:`_engine.Connection.get_isolation_level` + - view current level - :attr:`.Connection.default_isolation_level` - view default level + :attr:`_engine.Connection.default_isolation_level` + - view default level :paramref:`.Connection.execution_options.isolation_level` - - set per :class:`.Connection` isolation level + set per :class:`_engine.Connection` isolation level :paramref:`.create_engine.isolation_level` - - set per :class:`.Engine` isolation level + set per :class:`_engine.Engine` isolation level """ @@ -883,7 +894,8 @@ class Dialect(object): @classmethod def engine_created(cls, engine): - """A convenience hook called before returning the final :class:`.Engine`. + """A convenience hook called before returning the final + :class:`_engine.Engine`. If the dialect returned a different class from the :meth:`.get_dialect_cls` @@ -903,7 +915,7 @@ class Dialect(object): class CreateEnginePlugin(object): """A set of hooks intended to augment the construction of an - :class:`.Engine` object based on entrypoint names in a URL. + :class:`_engine.Engine` object based on entrypoint names in a URL. The purpose of :class:`.CreateEnginePlugin` is to allow third-party systems to apply engine, pool and dialect level event listeners without @@ -979,7 +991,7 @@ class CreateEnginePlugin(object): arguments afterwards. When the engine creation process completes and produces the - :class:`.Engine` object, it is again passed to the plugin via the + :class:`_engine.Engine` object, it is again passed to the plugin via the :meth:`.CreateEnginePlugin.engine_created` hook. In this hook, additional changes can be made to the engine, most typically involving setup of events (e.g. those defined in :ref:`core_event_toplevel`). @@ -992,7 +1004,7 @@ class CreateEnginePlugin(object): """Construct a new :class:`.CreateEnginePlugin`. The plugin object is instantiated individually for each call - to :func:`.create_engine`. A single :class:`.Engine` will be + to :func:`.create_engine`. A single :class:`_engine.Engine` will be passed to the :meth:`.CreateEnginePlugin.engine_created` method corresponding to this URL. @@ -1015,7 +1027,8 @@ class CreateEnginePlugin(object): """parse and modify pool kwargs""" def engine_created(self, engine): - """Receive the :class:`.Engine` object when it is fully constructed. + """Receive the :class:`_engine.Engine` + object when it is fully constructed. The plugin may make additional changes to the engine, such as registering engine or connection pool events. @@ -1246,9 +1259,9 @@ class ExecutionContext(object): @util.deprecated_20_cls( ":class:`.Connectable`", alternative=( - "The :class:`.Engine` will be the only Core " + "The :class:`_engine.Engine` will be the only Core " "object that features a .connect() method, and the " - ":class:`.Connection` will be the only object that features " + ":class:`_engine.Connection` will be the only object that features " "an .execute() method." ), constructor=None, @@ -1257,7 +1270,7 @@ class Connectable(object): """Interface for an object which supports execution of SQL constructs. The two implementations of :class:`.Connectable` are - :class:`.Connection` and :class:`.Engine`. + :class:`_engine.Connection` and :class:`_engine.Engine`. Connectable must also implement the 'dialect' member which references a :class:`.Dialect` instance. @@ -1265,19 +1278,20 @@ class Connectable(object): """ def connect(self, **kwargs): - """Return a :class:`.Connection` object. + """Return a :class:`_engine.Connection` object. Depending on context, this may be ``self`` if this object - is already an instance of :class:`.Connection`, or a newly - procured :class:`.Connection` if this object is an instance - of :class:`.Engine`. + is already an instance of :class:`_engine.Connection`, or a newly + procured :class:`_engine.Connection` if this object is an instance + of :class:`_engine.Engine`. """ engine = None - """The :class:`.Engine` instance referred to by this :class:`.Connectable`. + """The :class:`_engine.Engine` instance referred to by this + :class:`.Connectable`. - May be ``self`` if this is already an :class:`.Engine`. + May be ``self`` if this is already an :class:`_engine.Engine`. """ @@ -1311,7 +1325,7 @@ class ExceptionContext(object): """ connection = None - """The :class:`.Connection` in use during the exception. + """The :class:`_engine.Connection` in use during the exception. This member is present, except in the case of a failure when first connecting. @@ -1324,7 +1338,7 @@ class ExceptionContext(object): """ engine = None - """The :class:`.Engine` in use during the exception. + """The :class:`_engine.Engine` in use during the exception. This member should always be present, even in the case of a failure when first connecting. diff --git a/lib/sqlalchemy/engine/mock.py b/lib/sqlalchemy/engine/mock.py index bda9e91b5..19a3b8e6c 100644 --- a/lib/sqlalchemy/engine/mock.py +++ b/lib/sqlalchemy/engine/mock.py @@ -62,7 +62,8 @@ def create_mock_engine(url, executor, **kw): """Create a "mock" engine used for echoing DDL. This is a utility function used for debugging or storing the output of DDL - sequences as generated by :meth:`.MetaData.create_all` and related methods. + sequences as generated by :meth:`_schema.MetaData.create_all` + and related methods. The function accepts a URL which is used only to determine the kind of dialect to be used, as well as an "executor" callable function which diff --git a/lib/sqlalchemy/engine/reflection.py b/lib/sqlalchemy/engine/reflection.py index 1a34e9c72..344d5511d 100644 --- a/lib/sqlalchemy/engine/reflection.py +++ b/lib/sqlalchemy/engine/reflection.py @@ -66,38 +66,43 @@ class Inspector(object): consistent interface as well as caching support for previously fetched metadata. - A :class:`.Inspector` object is usually created via the - :func:`.inspect` function, which may be passed an :class:`.Engine` - or a :class:`.Connection`:: + A :class:`_reflection.Inspector` object is usually created via the + :func:`_sa.inspect` function, which may be passed an + :class:`_engine.Engine` + or a :class:`_engine.Connection`:: from sqlalchemy import inspect, create_engine engine = create_engine('...') insp = inspect(engine) Where above, the :class:`~sqlalchemy.engine.interfaces.Dialect` associated - with the engine may opt to return an :class:`.Inspector` subclass that + with the engine may opt to return an :class:`_reflection.Inspector` + subclass that provides additional methods specific to the dialect's target database. """ @util.deprecated( "1.4", - "The __init__() method on :class:`.Inspector` is deprecated and " + "The __init__() method on :class:`_reflection.Inspector` " + "is deprecated and " "will be removed in a future release. Please use the " ":func:`.sqlalchemy.inspect` " - "function on an :class:`.Engine` or :class:`.Connection` in order to " - "acquire an :class:`.Inspector`.", + "function on an :class:`_engine.Engine` or " + ":class:`_engine.Connection` " + "in order to " + "acquire an :class:`_reflection.Inspector`.", ) def __init__(self, bind): - """Initialize a new :class:`.Inspector`. + """Initialize a new :class:`_reflection.Inspector`. :param bind: a :class:`~sqlalchemy.engine.Connectable`, which is typically an instance of :class:`~sqlalchemy.engine.Engine` or :class:`~sqlalchemy.engine.Connection`. - For a dialect-specific instance of :class:`.Inspector`, see - :meth:`.Inspector.from_engine` + For a dialect-specific instance of :class:`_reflection.Inspector`, see + :meth:`_reflection.Inspector.from_engine` """ return self._init_legacy(bind) @@ -135,11 +140,14 @@ class Inspector(object): @classmethod @util.deprecated( "1.4", - "The from_engine() method on :class:`.Inspector` is deprecated and " + "The from_engine() method on :class:`_reflection.Inspector` " + "is deprecated and " "will be removed in a future release. Please use the " ":func:`.sqlalchemy.inspect` " - "function on an :class:`.Engine` or :class:`.Connection` in order to " - "acquire an :class:`.Inspector`.", + "function on an :class:`_engine.Engine` or " + ":class:`_engine.Connection` " + "in order to " + "acquire an :class:`_reflection.Inspector`.", ) def from_engine(cls, bind): """Construct a new dialect-specific Inspector object from the given @@ -151,12 +159,13 @@ class Inspector(object): :class:`~sqlalchemy.engine.Connection`. This method differs from direct a direct constructor call of - :class:`.Inspector` in that the + :class:`_reflection.Inspector` in that the :class:`~sqlalchemy.engine.interfaces.Dialect` is given a chance to - provide a dialect-specific :class:`.Inspector` instance, which may + provide a dialect-specific :class:`_reflection.Inspector` instance, + which may provide additional methods. - See the example at :class:`.Inspector`. + See the example at :class:`_reflection.Inspector`. """ return cls._construct(cls._init_legacy, bind) @@ -182,7 +191,8 @@ class Inspector(object): transaction. This essentially allows connect()/close() to be called if we detected - that we're against an :class:`.Engine` and not a :class:`.Connection`. + that we're against an :class:`_engine.Engine` and not a + :class:`_engine.Connection`. """ if self._op_context_requires_connect: @@ -197,7 +207,8 @@ class Inspector(object): @contextlib.contextmanager def _inspection_context(self): - """Return an :class:`.Inspector` from this one that will run all + """Return an :class:`_reflection.Inspector` + from this one that will run all operations on a single connection. """ @@ -233,7 +244,8 @@ class Inspector(object): """Return all table names in referred to within a particular schema. The names are expected to be real tables only, not views. - Views are instead returned using the :meth:`.Inspector.get_view_names` + Views are instead returned using the + :meth:`_reflection.Inspector.get_view_names` method. @@ -250,9 +262,9 @@ class Inspector(object): .. seealso:: - :meth:`.Inspector.get_sorted_table_and_fkc_names` + :meth:`_reflection.Inspector.get_sorted_table_and_fkc_names` - :attr:`.MetaData.sorted_tables` + :attr:`_schema.MetaData.sorted_tables` """ @@ -289,10 +301,10 @@ class Inspector(object): .. seealso:: - :meth:`.Inspector.get_table_names` + :meth:`_reflection.Inspector.get_table_names` :func:`.sort_tables_and_constraints` - similar method which works - with an already-given :class:`.MetaData`. + with an already-given :class:`_schema.MetaData`. """ @@ -646,9 +658,10 @@ class Inspector(object): ) @util.deprecated_20( - ":meth:`.Inspector.reflecttable`", - "The :meth:`.Inspector.reflecttable` method was renamed to " - ":meth:`.Inspector.reflect_table`. This deprecated alias " + ":meth:`_reflection.Inspector.reflecttable`", + "The :meth:`_reflection.Inspector.reflecttable` " + "method was renamed to " + ":meth:`_reflection.Inspector.reflect_table`. This deprecated alias " "will be removed in a future release.", ) def reflecttable(self, *args, **kwargs): diff --git a/lib/sqlalchemy/engine/result.py b/lib/sqlalchemy/engine/result.py index be44f67e7..6944e0c67 100644 --- a/lib/sqlalchemy/engine/result.py +++ b/lib/sqlalchemy/engine/result.py @@ -327,7 +327,8 @@ class CursorResultMetaData(ResultMetaData): The remaining fairly common case is that of the textual SQL that includes at least partial column information; this is when - we use a :class:`.TextualSelect` construct. This construct may have + we use a :class:`_expression.TextualSelect` construct. + This construct may have unordered or ordered column information. In the ordered case, we merge the cursor.description and the compiled construct's information positionally, and warn if there are additional description names @@ -350,7 +351,8 @@ class CursorResultMetaData(ResultMetaData): SQLAlchemy for all cases up through te 0.9 series. Positional matching for compiled SQL expressions was introduced in 1.0 as a major performance feature, and positional matching for textual - :class:`.TextualSelect` objects in 1.1. As name matching is no longer + :class:`_expression.TextualSelect` objects in 1.1. + As name matching is no longer a common case, it was acceptable to factor it into smaller generator- oriented methods that are easier to understand, but incur slightly more performance overhead. @@ -1245,14 +1247,14 @@ class BaseResult(object): corresponding to the list of primary key columns in the target table. - This only applies to single row :func:`~.sql.expression.insert` + This only applies to single row :func:`_expression.insert` constructs which did not explicitly specify - :meth:`.Insert.returning`. + :meth:`_expression.Insert.returning`. Note that primary key columns which specify a server_default clause, or otherwise do not qualify as "autoincrement" - columns (see the notes at :class:`.Column`), and were + columns (see the notes at :class:`_schema.Column`), and were generated using the database-side default, will appear in this list as ``None`` unless the backend supports "returning" and the insert statement executed @@ -1504,7 +1506,7 @@ class BaseResult(object): def is_insert(self): """True if this :class:`.ResultProxy` is the result of a executing an expression language compiled - :func:`.expression.insert` construct. + :func:`_expression.insert` construct. When True, this implies that the :attr:`inserted_primary_key` attribute is accessible, @@ -1562,7 +1564,8 @@ class ResultProxy(BaseResult): In the case of a result that is the product of :ref:`connectionless execution <dbengine_implicit>`, - the underlying :class:`.Connection` object is also closed, which + the underlying :class:`_engine.Connection` object is also closed, + which :term:`releases` DBAPI connection resources. .. deprecated:: 2.0 "connectionless" execution is deprecated and will diff --git a/lib/sqlalchemy/exc.py b/lib/sqlalchemy/exc.py index a6da844dc..aef8598a9 100644 --- a/lib/sqlalchemy/exc.py +++ b/lib/sqlalchemy/exc.py @@ -127,8 +127,9 @@ class CircularDependencyError(SQLAlchemyError): or pre-deassociate one of the foreign key constrained values. The ``post_update`` flag described at :ref:`post_update` can resolve this cycle. - * In a :attr:`.MetaData.sorted_tables` operation, two :class:`.ForeignKey` - or :class:`.ForeignKeyConstraint` objects mutually refer to each + * In a :attr:`_schema.MetaData.sorted_tables` operation, two + :class:`_schema.ForeignKey` + or :class:`_schema.ForeignKeyConstraint` objects mutually refer to each other. Apply the ``use_alter=True`` flag to one or both, see :ref:`use_alter`. @@ -178,7 +179,8 @@ class DisconnectionError(SQLAlchemyError): """A disconnect is detected on a raw DB-API connection. This error is raised and consumed internally by a connection pool. It can - be raised by the :meth:`.PoolEvents.checkout` event so that the host pool + be raised by the :meth:`_events.PoolEvents.checkout` + event so that the host pool forces a retry; the exception will be caught three times in a row before the pool gives up and raises :class:`~sqlalchemy.exc.InvalidRequestError` regarding the connection attempt. @@ -191,12 +193,12 @@ class DisconnectionError(SQLAlchemyError): class InvalidatePoolError(DisconnectionError): """Raised when the connection pool should invalidate all stale connections. - A subclass of :class:`.DisconnectionError` that indicates that the + A subclass of :class:`_exc.DisconnectionError` that indicates that the disconnect situation encountered on the connection probably means the entire pool should be invalidated, as the database has been restarted. This exception will be handled otherwise the same way as - :class:`.DisconnectionError`, allowing three attempts to reconnect + :class:`_exc.DisconnectionError`, allowing three attempts to reconnect before giving up. .. versionadded:: 1.2 @@ -607,7 +609,7 @@ class RemovedIn20Warning(SADeprecationWarning): class SAPendingDeprecationWarning(PendingDeprecationWarning): - """A similar warning as :class:`.SADeprecationWarning`, this warning + """A similar warning as :class:`_exc.SADeprecationWarning`, this warning is not used in modern versions of SQLAlchemy. """ diff --git a/lib/sqlalchemy/ext/associationproxy.py b/lib/sqlalchemy/ext/associationproxy.py index 599bf966d..fc10cb88d 100644 --- a/lib/sqlalchemy/ext/associationproxy.py +++ b/lib/sqlalchemy/ext/associationproxy.py @@ -114,7 +114,7 @@ class AssociationProxy(interfaces.InspectionAttrInfo): and/or subclassed directly. :param target_collection: Name of the collection we'll proxy to, - usually created with :func:`.relationship`. + usually created with :func:`_orm.relationship`. :param attr: Attribute on the collected instances we'll proxy for. For example, given a target collection of [obj1, obj2], a @@ -216,7 +216,7 @@ class AssociationProxy(interfaces.InspectionAttrInfo): keywords = association_proxy('kws', 'keyword') If we access this :class:`.AssociationProxy` from - :attr:`.Mapper.all_orm_descriptors`, and we want to view the + :attr:`_orm.Mapper.all_orm_descriptors`, and we want to view the target class for this proxy as mapped by ``User``:: inspect(User).all_orm_descriptors["keywords"].for_class(User).target_class @@ -467,7 +467,7 @@ class AssociationProxyInstance(object): """Return a tuple of ``(local_attr, remote_attr)``. This attribute is convenient when specifying a join - using :meth:`.Query.join` across two relationships:: + using :meth:`_query.Query.join` across two relationships:: sess.query(Parent).join(*Parent.proxied.attr) diff --git a/lib/sqlalchemy/ext/automap.py b/lib/sqlalchemy/ext/automap.py index e409cf38c..4ae3a415e 100644 --- a/lib/sqlalchemy/ext/automap.py +++ b/lib/sqlalchemy/ext/automap.py @@ -60,12 +60,16 @@ asking it to reflect the schema and produce mappings:: Above, calling :meth:`.AutomapBase.prepare` while passing along the :paramref:`.AutomapBase.prepare.reflect` parameter indicates that the -:meth:`.MetaData.reflect` method will be called on this declarative base -classes' :class:`.MetaData` collection; then, each **viable** -:class:`.Table` within the :class:`.MetaData` will get a new mapped class -generated automatically. The :class:`.ForeignKeyConstraint` objects which +:meth:`_schema.MetaData.reflect` +method will be called on this declarative base +classes' :class:`_schema.MetaData` collection; then, each **viable** +:class:`_schema.Table` within the :class:`_schema.MetaData` +will get a new mapped class +generated automatically. The :class:`_schema.ForeignKeyConstraint` +objects which link the various tables together will be used to produce new, bidirectional -:func:`.relationship` objects between classes. The classes and relationships +:func:`_orm.relationship` objects between classes. +The classes and relationships follow along a default naming scheme that we can customize. At this point, our basic mapping consisting of related ``User`` and ``Address`` classes is ready to use in the traditional way. @@ -79,10 +83,12 @@ ready to use in the traditional way. Generating Mappings from an Existing MetaData ============================================= -We can pass a pre-declared :class:`.MetaData` object to :func:`.automap_base`. +We can pass a pre-declared :class:`_schema.MetaData` object to +:func:`.automap_base`. This object can be constructed in any way, including programmatically, from a serialized file, or from itself being reflected using -:meth:`.MetaData.reflect`. Below we illustrate a combination of reflection and +:meth:`_schema.MetaData.reflect`. +Below we illustrate a combination of reflection and explicit table declaration:: from sqlalchemy import create_engine, MetaData, Table, Column, ForeignKey @@ -160,7 +166,7 @@ established based on the table name we use. If our schema contains tables print (a1.user) Above, one of the more intricate details is that we illustrated overriding -one of the :func:`.relationship` objects that automap would have created. +one of the :func:`_orm.relationship` objects that automap would have created. To do this, we needed to make sure the names match up with what automap would normally generate, in that the relationship name would be ``User.address_collection`` and the name of the class referred to, from @@ -226,39 +232,43 @@ Relationship Detection ====================== The vast majority of what automap accomplishes is the generation of -:func:`.relationship` structures based on foreign keys. The mechanism +:func:`_orm.relationship` structures based on foreign keys. The mechanism by which this works for many-to-one and one-to-many relationships is as follows: -1. A given :class:`.Table`, known to be mapped to a particular class, - is examined for :class:`.ForeignKeyConstraint` objects. +1. A given :class:`_schema.Table`, known to be mapped to a particular class, + is examined for :class:`_schema.ForeignKeyConstraint` objects. -2. From each :class:`.ForeignKeyConstraint`, the remote :class:`.Table` +2. From each :class:`_schema.ForeignKeyConstraint`, the remote + :class:`_schema.Table` object present is matched up to the class to which it is to be mapped, if any, else it is skipped. -3. As the :class:`.ForeignKeyConstraint` we are examining corresponds to a +3. As the :class:`_schema.ForeignKeyConstraint` + we are examining corresponds to a reference from the immediate mapped class, the relationship will be set up as a many-to-one referring to the referred class; a corresponding one-to-many backref will be created on the referred class referring to this class. -4. If any of the columns that are part of the :class:`.ForeignKeyConstraint` +4. If any of the columns that are part of the + :class:`_schema.ForeignKeyConstraint` are not nullable (e.g. ``nullable=False``), a - :paramref:`~.relationship.cascade` keyword argument + :paramref:`_orm.relationship.cascade` keyword argument of ``all, delete-orphan`` will be added to the keyword arguments to be passed to the relationship or backref. If the - :class:`.ForeignKeyConstraint` reports that - :paramref:`.ForeignKeyConstraint.ondelete` + :class:`_schema.ForeignKeyConstraint` reports that + :paramref:`_schema.ForeignKeyConstraint.ondelete` is set to ``CASCADE`` for a not null or ``SET NULL`` for a nullable - set of columns, the option :paramref:`~.relationship.passive_deletes` + set of columns, the option :paramref:`_orm.relationship.passive_deletes` flag is set to ``True`` in the set of relationship keyword arguments. Note that not all backends support reflection of ON DELETE. .. versionadded:: 1.0.0 - automap will detect non-nullable foreign key constraints when producing a one-to-many relationship and establish a default cascade of ``all, delete-orphan`` if so; additionally, - if the constraint specifies :paramref:`.ForeignKeyConstraint.ondelete` + if the constraint specifies + :paramref:`_schema.ForeignKeyConstraint.ondelete` of ``CASCADE`` for non-nullable or ``SET NULL`` for nullable columns, the ``passive_deletes=True`` option is also added. @@ -274,18 +284,20 @@ follows: 6. The classes are inspected for an existing mapped property matching these names. If one is detected on one side, but none on the other side, :class:`.AutomapBase` attempts to create a relationship on the missing side, - then uses the :paramref:`.relationship.back_populates` parameter in order to + then uses the :paramref:`_orm.relationship.back_populates` + parameter in order to point the new relationship to the other side. 7. In the usual case where no relationship is on either side, - :meth:`.AutomapBase.prepare` produces a :func:`.relationship` on the + :meth:`.AutomapBase.prepare` produces a :func:`_orm.relationship` on the "many-to-one" side and matches it to the other using the - :paramref:`.relationship.backref` parameter. + :paramref:`_orm.relationship.backref` parameter. -8. Production of the :func:`.relationship` and optionally the :func:`.backref` +8. Production of the :func:`_orm.relationship` and optionally the + :func:`.backref` is handed off to the :paramref:`.AutomapBase.prepare.generate_relationship` function, which can be supplied by the end-user in order to augment - the arguments passed to :func:`.relationship` or :func:`.backref` or to + the arguments passed to :func:`_orm.relationship` or :func:`.backref` or to make use of custom implementations of these functions. Custom Relationship Arguments @@ -298,8 +310,8 @@ the object, after augmenting the given keyword dictionary with our own arguments. Below is an illustration of how to send -:paramref:`.relationship.cascade` and -:paramref:`.relationship.passive_deletes` +:paramref:`_orm.relationship.cascade` and +:paramref:`_orm.relationship.passive_deletes` options along to all one-to-many relationships:: from sqlalchemy.ext.automap import generate_relationship @@ -331,20 +343,24 @@ Many-to-Many relationships those which contain a ``secondary`` argument. The process for producing these is as follows: -1. A given :class:`.Table` is examined for :class:`.ForeignKeyConstraint` +1. A given :class:`_schema.Table` is examined for + :class:`_schema.ForeignKeyConstraint` objects, before any mapped class has been assigned to it. -2. If the table contains two and exactly two :class:`.ForeignKeyConstraint` +2. If the table contains two and exactly two + :class:`_schema.ForeignKeyConstraint` objects, and all columns within this table are members of these two - :class:`.ForeignKeyConstraint` objects, the table is assumed to be a + :class:`_schema.ForeignKeyConstraint` objects, the table is assumed to be a "secondary" table, and will **not be mapped directly**. 3. The two (or one, for self-referential) external tables to which the - :class:`.Table` refers to are matched to the classes to which they will be + :class:`_schema.Table` + refers to are matched to the classes to which they will be mapped, if any. 4. If mapped classes for both sides are located, a many-to-many bi-directional - :func:`.relationship` / :func:`.backref` pair is created between the two + :func:`_orm.relationship` / :func:`.backref` + pair is created between the two classes. 5. The override logic for many-to-many works the same as that of one-to-many/ @@ -469,7 +485,8 @@ Using Automap with Explicit Declarations ======================================== As noted previously, automap has no dependency on reflection, and can make -use of any collection of :class:`.Table` objects within a :class:`.MetaData` +use of any collection of :class:`_schema.Table` objects within a +:class:`_schema.MetaData` collection. From this, it follows that automap can also be used generate missing relationships given an otherwise complete model that fully defines table metadata:: @@ -503,7 +520,7 @@ defines table metadata:: assert a1.user is u1 Above, given mostly complete ``User`` and ``Address`` mappings, the -:class:`.ForeignKey` which we defined on ``Address.user_id`` allowed a +:class:`_schema.ForeignKey` which we defined on ``Address.user_id`` allowed a bidirectional relationship pair ``Address.user`` and ``User.address_collection`` to be generated on the mapped classes. @@ -539,9 +556,9 @@ def classname_for_table(base, tablename, table): :param base: the :class:`.AutomapBase` class doing the prepare. - :param tablename: string name of the :class:`.Table`. + :param tablename: string name of the :class:`_schema.Table`. - :param table: the :class:`.Table` object itself. + :param table: the :class:`_schema.Table` object itself. :return: a string class name. @@ -549,7 +566,8 @@ def classname_for_table(base, tablename, table): In Python 2, the string used for the class name **must** be a non-Unicode object, e.g. a ``str()`` object. The ``.name`` attribute - of :class:`.Table` is typically a Python unicode subclass, so the + of :class:`_schema.Table` is typically a Python unicode subclass, + so the ``str()`` function should be applied to this name, after accounting for any non-ASCII characters. @@ -575,7 +593,7 @@ def name_for_scalar_relationship(base, local_cls, referred_cls, constraint): :param referred_cls: the class to be mapped on the referring side. - :param constraint: the :class:`.ForeignKeyConstraint` that is being + :param constraint: the :class:`_schema.ForeignKeyConstraint` that is being inspected to produce this relationship. """ @@ -603,7 +621,7 @@ def name_for_collection_relationship( :param referred_cls: the class to be mapped on the referring side. - :param constraint: the :class:`.ForeignKeyConstraint` that is being + :param constraint: the :class:`_schema.ForeignKeyConstraint` that is being inspected to produce this relationship. """ @@ -613,7 +631,8 @@ def name_for_collection_relationship( def generate_relationship( base, direction, return_fn, attrname, local_cls, referred_cls, **kw ): - r"""Generate a :func:`.relationship` or :func:`.backref` on behalf of two + r"""Generate a :func:`_orm.relationship` or :func:`.backref` + on behalf of two mapped classes. An alternate implementation of this function can be specified using the @@ -634,9 +653,10 @@ def generate_relationship( be one of :data:`.ONETOMANY`, :data:`.MANYTOONE`, :data:`.MANYTOMANY`. :param return_fn: the function that is used by default to create the - relationship. This will be either :func:`.relationship` or + relationship. This will be either :func:`_orm.relationship` or :func:`.backref`. The :func:`.backref` function's result will be used to - produce a new :func:`.relationship` in a second step, so it is critical + produce a new :func:`_orm.relationship` in a second step, + so it is critical that user-defined implementations correctly differentiate between the two functions, if a custom relationship function is being used. @@ -654,7 +674,8 @@ def generate_relationship( :param \**kw: all additional keyword arguments are passed along to the function. - :return: a :func:`.relationship` or :func:`.backref` construct, as dictated + :return: a :func:`_orm.relationship` or :func:`.backref` construct, + as dictated by the :paramref:`.generate_relationship.return_fn` parameter. """ @@ -710,19 +731,24 @@ class AutomapBase(object): name_for_collection_relationship=name_for_collection_relationship, generate_relationship=generate_relationship, ): - """Extract mapped classes and relationships from the :class:`.MetaData` and + """Extract mapped classes and relationships from the + :class:`_schema.MetaData` and perform mappings. - :param engine: an :class:`.Engine` or :class:`.Connection` with which + :param engine: an :class:`_engine.Engine` or + :class:`_engine.Connection` with which to perform schema reflection, if specified. If the :paramref:`.AutomapBase.prepare.reflect` argument is False, this object is not used. - :param reflect: if True, the :meth:`.MetaData.reflect` method is called - on the :class:`.MetaData` associated with this :class:`.AutomapBase`. - The :class:`.Engine` passed via + :param reflect: if True, the :meth:`_schema.MetaData.reflect` + method is called + on the :class:`_schema.MetaData` associated with this + :class:`.AutomapBase`. + The :class:`_engine.Engine` passed via :paramref:`.AutomapBase.prepare.engine` will be used to perform the - reflection if present; else, the :class:`.MetaData` should already be + reflection if present; else, the :class:`_schema.MetaData` + should already be bound to some engine else the operation will fail. :param classname_for_table: callable function which will be used to @@ -738,16 +764,18 @@ class AutomapBase(object): relationships. Defaults to :func:`.name_for_collection_relationship`. :param generate_relationship: callable function which will be used to - actually generate :func:`.relationship` and :func:`.backref` + actually generate :func:`_orm.relationship` and :func:`.backref` constructs. Defaults to :func:`.generate_relationship`. :param collection_class: the Python collection class that will be used - when a new :func:`.relationship` object is created that represents a + when a new :func:`_orm.relationship` + object is created that represents a collection. Defaults to ``list``. :param schema: When present in conjunction with the :paramref:`.AutomapBase.prepare.reflect` flag, is passed to - :meth:`.MetaData.reflect` to indicate the primary schema where tables + :meth:`_schema.MetaData.reflect` + to indicate the primary schema where tables should be reflected from. When omitted, the default schema in use by the database connection is used. diff --git a/lib/sqlalchemy/ext/baked.py b/lib/sqlalchemy/ext/baked.py index ff741db32..839aae730 100644 --- a/lib/sqlalchemy/ext/baked.py +++ b/lib/sqlalchemy/ext/baked.py @@ -147,7 +147,7 @@ class BakedQuery(object): :class:`.BakedQuery` object subsequent to the spoil step will be non-cached; the state of the :class:`.BakedQuery` up until this point will be pulled from the cache. If True, then the - entire :class:`.Query` object is built from scratch each + entire :class:`_query.Query` object is built from scratch each time, with all creational functions being called on each invocation. @@ -165,8 +165,8 @@ class BakedQuery(object): :class:`.Session`. This basically means we also will include the session's query_class, - as the actual :class:`.Query` object is part of what's cached - and needs to match the type of :class:`.Query` that a later + as the actual :class:`_query.Query` object is part of what's cached + and needs to match the type of :class:`_query.Query` that a later session will want to use. """ @@ -255,11 +255,11 @@ class BakedQuery(object): return context def to_query(self, query_or_session): - """Return the :class:`.Query` object for use as a subquery. + """Return the :class:`_query.Query` object for use as a subquery. This method should be used within the lambda callable being used to generate a step of an enclosing :class:`.BakedQuery`. The - parameter should normally be the :class:`.Query` object that + parameter should normally be the :class:`_query.Query` object that is passed to the lambda:: sub_bq = self.bakery(lambda s: s.query(User.name)) @@ -282,7 +282,7 @@ class BakedQuery(object): Address.id, sub_bq.to_query(q).scalar_subquery()) ) - :param query_or_session: a :class:`.Query` object or a class + :param query_or_session: a :class:`_query.Query` object or a class :class:`.Session` object, that is assumed to be within the context of an enclosing :class:`.BakedQuery` callable. @@ -394,13 +394,14 @@ class Result(object): """Add a criteria function that will be applied post-cache. This adds a function that will be run against the - :class:`.Query` object after it is retrieved from the + :class:`_query.Query` object after it is retrieved from the cache. Functions here can be used to alter the query in ways that **do not affect the SQL output**, such as execution options and shard identifiers (when using a shard-enabled query object) .. warning:: :meth:`.Result.with_post_criteria` functions are applied - to the :class:`.Query` object **after** the query's SQL statement + to the :class:`_query.Query` + object **after** the query's SQL statement object has been retrieved from the cache. Any operations here which intend to modify the SQL should ensure that :meth:`.BakedQuery.spoil` was called first. @@ -449,7 +450,7 @@ class Result(object): def count(self): """return the 'count'. - Equivalent to :meth:`.Query.count`. + Equivalent to :meth:`_query.Query.count`. Note this uses a subquery to ensure an accurate count regardless of the structure of the original statement. @@ -467,7 +468,7 @@ class Result(object): if no rows present. If multiple rows are returned, raises MultipleResultsFound. - Equivalent to :meth:`.Query.scalar`. + Equivalent to :meth:`_query.Query.scalar`. .. versionadded:: 1.1.6 @@ -483,7 +484,7 @@ class Result(object): def first(self): """Return the first row. - Equivalent to :meth:`.Query.first`. + Equivalent to :meth:`_query.Query.first`. """ bq = self.bq.with_criteria(lambda q: q.slice(0, 1)) @@ -500,7 +501,7 @@ class Result(object): def one(self): """Return exactly one result or raise an exception. - Equivalent to :meth:`.Query.one`. + Equivalent to :meth:`_query.Query.one`. """ try: @@ -521,7 +522,7 @@ class Result(object): """Return one or zero results, or raise an exception for multiple rows. - Equivalent to :meth:`.Query.one_or_none`. + Equivalent to :meth:`_query.Query.one_or_none`. .. versionadded:: 1.0.9 @@ -541,7 +542,7 @@ class Result(object): def all(self): """Return all rows. - Equivalent to :meth:`.Query.all`. + Equivalent to :meth:`_query.Query.all`. """ return list(self) @@ -549,7 +550,7 @@ class Result(object): def get(self, ident): """Retrieve an object based on identity. - Equivalent to :meth:`.Query.get`. + Equivalent to :meth:`_query.Query.get`. """ @@ -646,7 +647,7 @@ def unbake_lazy_loaders(): This method now raises NotImplementedError() as the "baked" implementation is the only lazy load implementation. The - :paramref:`.relationship.bake_queries` flag may be used to disable + :paramref:`_orm.relationship.bake_queries` flag may be used to disable the caching of queries on a per-relationship basis. """ diff --git a/lib/sqlalchemy/ext/compiler.py b/lib/sqlalchemy/ext/compiler.py index b8b6f8dc0..32975a949 100644 --- a/lib/sqlalchemy/ext/compiler.py +++ b/lib/sqlalchemy/ext/compiler.py @@ -101,7 +101,7 @@ Produces:: The above ``InsertFromSelect`` construct is only an example, this actual functionality is already available using the - :meth:`.Insert.from_select` method. + :meth:`_expression.Insert.from_select` method. .. note:: @@ -140,7 +140,8 @@ supported. Enabling Autocommit on a Construct ================================== -Recall from the section :ref:`autocommit` that the :class:`.Engine`, when +Recall from the section :ref:`autocommit` that the :class:`_engine.Engine`, +when asked to execute a construct in the absence of a user-defined transaction, detects if the given construct represents DML or DDL, that is, a data modification or data definition statement, which requires (or may require, @@ -165,7 +166,7 @@ is a "frozen" dictionary which supplies a generative ``union()`` method):: More succinctly, if the construct is truly similar to an INSERT, UPDATE, or DELETE, :class:`.UpdateBase` can be used, which already is a subclass -of :class:`.Executable`, :class:`.ClauseElement` and includes the +of :class:`.Executable`, :class:`_expression.ClauseElement` and includes the ``autocommit`` flag:: from sqlalchemy.sql.expression import UpdateBase @@ -405,7 +406,7 @@ from ..sql import visitors def compiles(class_, *specs): """Register a function as a compiler for a - given :class:`.ClauseElement` type.""" + given :class:`_expression.ClauseElement` type.""" def decorate(fn): # get an existing @compiles handler @@ -455,7 +456,7 @@ def compiles(class_, *specs): def deregister(class_): """Remove all custom compilers associated with a given - :class:`.ClauseElement` type.""" + :class:`_expression.ClauseElement` type.""" if hasattr(class_, "_compiler_dispatcher"): # regenerate default _compiler_dispatch diff --git a/lib/sqlalchemy/ext/declarative/api.py b/lib/sqlalchemy/ext/declarative/api.py index 825c1d3f3..65d100bc7 100644 --- a/lib/sqlalchemy/ext/declarative/api.py +++ b/lib/sqlalchemy/ext/declarative/api.py @@ -82,10 +82,11 @@ class DeclarativeMeta(type): def synonym_for(name, map_column=False): - """Decorator that produces an :func:`.orm.synonym` attribute in conjunction + """Decorator that produces an :func:`_orm.synonym` + attribute in conjunction with a Python descriptor. - The function being decorated is passed to :func:`.orm.synonym` as the + The function being decorated is passed to :func:`_orm.synonym` as the :paramref:`.orm.synonym.descriptor` parameter:: class MyClass(Base): @@ -107,7 +108,7 @@ def synonym_for(name, map_column=False): :ref:`synonyms` - Overview of synonyms - :func:`.orm.synonym` - the mapper-level function + :func:`_orm.synonym` - the mapper-level function :ref:`mapper_hybrids` - The Hybrid Attribute extension provides an updated approach to augmenting attribute behavior more flexibly than @@ -323,7 +324,7 @@ def declarative_base( :param class_registry: optional dictionary that will serve as the registry of class names-> mapped classes when string names - are used to identify classes inside of :func:`.relationship` + are used to identify classes inside of :func:`_orm.relationship` and others. Allows two or more declarative base classes to share the same registry of class names for simplified inter-base relationships. @@ -505,7 +506,7 @@ class AbstractConcreteBase(ConcreteBase): .. seealso:: - :func:`.orm.configure_mappers` + :func:`_orm.configure_mappers` Example:: @@ -656,17 +657,17 @@ class DeferredReflection(object): a deferred reflection step. Normally, declarative can be used with reflection by - setting a :class:`.Table` object using autoload=True + setting a :class:`_schema.Table` object using autoload=True as the ``__table__`` attribute on a declarative class. - The caveat is that the :class:`.Table` must be fully + The caveat is that the :class:`_schema.Table` must be fully reflected, or at the very least have a primary key column, at the point at which a normal declarative mapping is - constructed, meaning the :class:`.Engine` must be available + constructed, meaning the :class:`_engine.Engine` must be available at class declaration time. The :class:`.DeferredReflection` mixin moves the construction of mappers to be at a later point, after a specific - method is called which first reflects all :class:`.Table` + method is called which first reflects all :class:`_schema.Table` objects created so far. Classes can define it as such:: from sqlalchemy.ext.declarative import declarative_base @@ -720,7 +721,7 @@ class DeferredReflection(object): @classmethod def prepare(cls, engine): - """Reflect all :class:`.Table` objects for all current + """Reflect all :class:`_schema.Table` objects for all current :class:`.DeferredReflection` subclasses""" to_map = _DeferredMapperConfig.classes_for_base(cls) diff --git a/lib/sqlalchemy/ext/declarative/clsregistry.py b/lib/sqlalchemy/ext/declarative/clsregistry.py index 219c4ba2e..20de3c636 100644 --- a/lib/sqlalchemy/ext/declarative/clsregistry.py +++ b/lib/sqlalchemy/ext/declarative/clsregistry.py @@ -7,7 +7,7 @@ """Routines to handle the string class registry used by declarative. This system allows specification of classes and expressions used in -:func:`.relationship` using strings. +:func:`_orm.relationship` using strings. """ import weakref diff --git a/lib/sqlalchemy/ext/horizontal_shard.py b/lib/sqlalchemy/ext/horizontal_shard.py index 56553c83d..cfb2fd687 100644 --- a/lib/sqlalchemy/ext/horizontal_shard.py +++ b/lib/sqlalchemy/ext/horizontal_shard.py @@ -197,7 +197,7 @@ class ShardedSession(Session): possible identity tokens (e.g. shard ids). .. versionchanged:: 1.4 Moved :meth:`.Session._identity_lookup` from - the :class:`.Query` object to the :class:`.Session`. + the :class:`_query.Query` object to the :class:`.Session`. """ diff --git a/lib/sqlalchemy/ext/hybrid.py b/lib/sqlalchemy/ext/hybrid.py index 7c523edbd..9f73b5d31 100644 --- a/lib/sqlalchemy/ext/hybrid.py +++ b/lib/sqlalchemy/ext/hybrid.py @@ -75,7 +75,8 @@ returns a new SQL expression:: FROM interval WHERE interval."end" - interval.start > :param_1 -ORM methods such as :meth:`~.Query.filter_by` generally use ``getattr()`` to +ORM methods such as :meth:`_query.Query.filter_by` +generally use ``getattr()`` to locate attributes, so can also be used with hybrid attributes:: >>> print(Session().query(Interval).filter_by(length=5)) @@ -213,10 +214,10 @@ Allowing Bulk ORM Update ------------------------ A hybrid can define a custom "UPDATE" handler for when using the -:meth:`.Query.update` method, allowing the hybrid to be used in the +:meth:`_query.Query.update` method, allowing the hybrid to be used in the SET clause of the update. -Normally, when using a hybrid with :meth:`.Query.update`, the SQL +Normally, when using a hybrid with :meth:`_query.Query.update`, the SQL expression is used as the column that's the target of the SET. If our ``Interval`` class had a hybrid ``start_point`` that linked to ``Interval.start``, this could be substituted directly:: @@ -225,7 +226,7 @@ expression is used as the column that's the target of the SET. If our However, when using a composite hybrid like ``Interval.length``, this hybrid represents more than one column. We can set up a handler that will -accommodate a value passed to :meth:`.Query.update` which can affect +accommodate a value passed to :meth:`_query.Query.update` which can affect this, using the :meth:`.hybrid_property.update_expression` decorator. A handler that works similarly to our setter would be:: @@ -628,9 +629,11 @@ measurement, currencies and encrypted passwords. Building Transformers ---------------------- -A *transformer* is an object which can receive a :class:`.Query` object and -return a new one. The :class:`.Query` object includes a method -:meth:`.with_transformation` that returns a new :class:`.Query` transformed by +A *transformer* is an object which can receive a :class:`_query.Query` +object and +return a new one. The :class:`_query.Query` object includes a method +:meth:`.with_transformation` that returns a new :class:`_query.Query` +transformed by the given function. We can combine this with the :class:`.Comparator` class to produce one type @@ -665,10 +668,11 @@ simple:: return self.parent.parent For the expression, things are not so clear. We'd need to construct a -:class:`.Query` where we :meth:`~.Query.join` twice along ``Node.parent`` to +:class:`_query.Query` where we :meth:`_query.Query.join` twice along ``Node. +parent`` to get to the ``grandparent``. We can instead return a transforming callable that we'll combine with the :class:`.Comparator` class to receive any -:class:`.Query` object, and return a new one that's joined to the +:class:`_query.Query` object, and return a new one that's joined to the ``Node.parent`` attribute and filtered based on the given criterion:: from sqlalchemy.ext.hybrid import Comparator @@ -704,9 +708,10 @@ transforming callable, which then runs the given comparison operation in a particular context. Such as, in the example above, the ``operate`` method is called, given the :attr:`.Operators.eq` callable as well as the right side of the comparison ``Node(id=5)``. A function ``transform`` is then returned which -will transform a :class:`.Query` first to join to ``Node.parent``, then to +will transform a :class:`_query.Query` first to join to ``Node.parent``, +then to compare ``parent_alias`` using :attr:`.Operators.eq` against the left and right -sides, passing into :class:`.Query.filter`: +sides, passing into :class:`_query.Query.filter`: .. sourcecode:: pycon+sql @@ -783,7 +788,7 @@ HYBRID_METHOD = util.symbol("HYBRID_METHOD") .. seealso:: - :attr:`.Mapper.all_orm_attributes` + :attr:`_orm.Mapper.all_orm_attributes` """ @@ -796,7 +801,7 @@ HYBRID_PROPERTY = util.symbol("HYBRID_PROPERTY") .. seealso:: - :attr:`.Mapper.all_orm_attributes` + :attr:`_orm.Mapper.all_orm_attributes` """ diff --git a/lib/sqlalchemy/ext/indexable.py b/lib/sqlalchemy/ext/indexable.py index 6eb7e1185..f58acceeb 100644 --- a/lib/sqlalchemy/ext/indexable.py +++ b/lib/sqlalchemy/ext/indexable.py @@ -6,20 +6,20 @@ # the MIT License: http://www.opensource.org/licenses/mit-license.php """Define attributes on ORM-mapped classes that have "index" attributes for -columns with :class:`~.types.Indexable` types. +columns with :class:`_types.Indexable` types. "index" means the attribute is associated with an element of an -:class:`~.types.Indexable` column with the predefined index to access it. -The :class:`~.types.Indexable` types include types such as -:class:`~.types.ARRAY`, :class:`~.types.JSON` and -:class:`~.postgresql.HSTORE`. +:class:`_types.Indexable` column with the predefined index to access it. +The :class:`_types.Indexable` types include types such as +:class:`_types.ARRAY`, :class:`_types.JSON` and +:class:`_postgresql.HSTORE`. The :mod:`~sqlalchemy.ext.indexable` extension provides -:class:`~.schema.Column`-like interface for any element of an -:class:`~.types.Indexable` typed column. In simple cases, it can be -treated as a :class:`~.schema.Column` - mapped attribute. +:class:`_schema.Column`-like interface for any element of an +:class:`_types.Indexable` typed column. In simple cases, it can be +treated as a :class:`_schema.Column` - mapped attribute. .. versionadded:: 1.1 @@ -192,7 +192,7 @@ where we want to also include automatic casting plus ``astext()``:: return expr.astext.cast(self.cast_type) The above subclass can be used with the PostgreSQL-specific -version of :class:`.postgresql.JSON`:: +version of :class:`_postgresql.JSON`:: from sqlalchemy import Column, Integer from sqlalchemy.ext.declarative import declarative_base @@ -234,7 +234,7 @@ __all__ = ["index_property"] class index_property(hybrid_property): # noqa """A property generator. The generated property describes an object - attribute that corresponds to an :class:`~.types.Indexable` + attribute that corresponds to an :class:`_types.Indexable` column. .. versionadded:: 1.1 diff --git a/lib/sqlalchemy/ext/mutable.py b/lib/sqlalchemy/ext/mutable.py index 5523fe75d..32a22a495 100644 --- a/lib/sqlalchemy/ext/mutable.py +++ b/lib/sqlalchemy/ext/mutable.py @@ -39,7 +39,7 @@ JSON strings before being persisted:: The usage of ``json`` is only for the purposes of example. The :mod:`sqlalchemy.ext.mutable` extension can be used with any type whose target Python type may be mutable, including -:class:`.PickleType`, :class:`.postgresql.ARRAY`, etc. +:class:`.PickleType`, :class:`_postgresql.ARRAY`, etc. When using the :mod:`sqlalchemy.ext.mutable` extension, the value itself tracks all parents which reference it. Below, we illustrate a simple @@ -270,7 +270,7 @@ and to also route attribute set events via ``__setattr__`` to the return not self.__eq__(other) The :class:`.MutableComposite` class uses a Python metaclass to automatically -establish listeners for any usage of :func:`.orm.composite` that specifies our +establish listeners for any usage of :func:`_orm.composite` that specifies our ``Point`` type. Below, when ``Point`` is mapped to the ``Vertex`` class, listeners are established which will route change events from ``Point`` objects to each of the ``Vertex.start`` and ``Vertex.end`` attributes:: diff --git a/lib/sqlalchemy/ext/orderinglist.py b/lib/sqlalchemy/ext/orderinglist.py index ac430c6b8..7b6b77997 100644 --- a/lib/sqlalchemy/ext/orderinglist.py +++ b/lib/sqlalchemy/ext/orderinglist.py @@ -11,7 +11,7 @@ elements. :author: Jason Kirtland ``orderinglist`` is a helper for mutable ordered relationships. It will -intercept list operations performed on a :func:`.relationship`-managed +intercept list operations performed on a :func:`_orm.relationship`-managed collection and automatically synchronize changes in list position onto a target scalar attribute. @@ -86,7 +86,7 @@ With the above mapping the ``Bullet.position`` attribute is managed:: The :class:`.OrderingList` construct only works with **changes** to a collection, and not the initial load from the database, and requires that the list be sorted when loaded. Therefore, be sure to specify ``order_by`` on the -:func:`.relationship` against the target ordering attribute, so that the +:func:`_orm.relationship` against the target ordering attribute, so that the ordering is correct when first loaded. .. warning:: @@ -212,7 +212,7 @@ class OrderingList(list): The :class:`.OrderingList` object is normally set up using the :func:`.ordering_list` factory function, used in conjunction with - the :func:`.relationship` function. + the :func:`_orm.relationship` function. """ diff --git a/lib/sqlalchemy/inspection.py b/lib/sqlalchemy/inspection.py index 5013d1c4d..270f189be 100644 --- a/lib/sqlalchemy/inspection.py +++ b/lib/sqlalchemy/inspection.py @@ -5,23 +5,24 @@ # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php -"""The inspection module provides the :func:`.inspect` function, +"""The inspection module provides the :func:`_sa.inspect` function, which delivers runtime information about a wide variety of SQLAlchemy objects, both within the Core as well as the ORM. -The :func:`.inspect` function is the entry point to SQLAlchemy's +The :func:`_sa.inspect` function is the entry point to SQLAlchemy's public API for viewing the configuration and construction of in-memory objects. Depending on the type of object -passed to :func:`.inspect`, the return value will either be +passed to :func:`_sa.inspect`, the return value will either be a related object which provides a known interface, or in many cases it will return the object itself. -The rationale for :func:`.inspect` is twofold. One is that +The rationale for :func:`_sa.inspect` is twofold. One is that it replaces the need to be aware of a large variety of "information -getting" functions in SQLAlchemy, such as :meth:`.Inspector.from_engine`, -:func:`.orm.attributes.instance_state`, :func:`.orm.class_mapper`, -and others. The other is that the return value of :func:`.inspect` +getting" functions in SQLAlchemy, such as +:meth:`_reflection.Inspector.from_engine`, +:func:`.orm.attributes.instance_state`, :func:`_orm.class_mapper`, +and others. The other is that the return value of :func:`_sa.inspect` is guaranteed to obey a documented API, thus allowing third party tools which build on top of SQLAlchemy configurations to be constructed in a forwards-compatible way. @@ -40,11 +41,11 @@ def inspect(subject, raiseerr=True): The returned value in some cases may be the same object as the one given, such as if a - :class:`.Mapper` object is passed. In other + :class:`_orm.Mapper` object is passed. In other cases, it will be an instance of the registered inspection type for the given object, such as - if an :class:`.engine.Engine` is passed, an - :class:`.Inspector` object is returned. + if an :class:`_engine.Engine` is passed, an + :class:`_reflection.Inspector` object is returned. :param subject: the subject to be inspected. :param raiseerr: When ``True``, if the given subject diff --git a/lib/sqlalchemy/log.py b/lib/sqlalchemy/log.py index a6d6cb4f1..42c8a2c29 100644 --- a/lib/sqlalchemy/log.py +++ b/lib/sqlalchemy/log.py @@ -12,8 +12,8 @@ Control of logging for SA can be performed from the regular python logging module. The regular dotted module namespace is used, starting at 'sqlalchemy'. For class-level logging, the class name is appended. -The "echo" keyword parameter, available on SQLA :class:`.Engine` -and :class:`.Pool` objects, corresponds to a logger specific to that +The "echo" keyword parameter, available on SQLA :class:`_engine.Engine` +and :class:`_pool.Pool` objects, corresponds to a logger specific to that instance only. """ diff --git a/lib/sqlalchemy/orm/__init__.py b/lib/sqlalchemy/orm/__init__.py index 53118c573..24945ef52 100644 --- a/lib/sqlalchemy/orm/__init__.py +++ b/lib/sqlalchemy/orm/__init__.py @@ -153,7 +153,8 @@ def deferred(*columns, **kw): not load unless accessed. :param \*columns: columns to be mapped. This is typically a single - :class:`.Column` object, however a collection is supported in order + :class:`_schema.Column` object, + however a collection is supported in order to support multiple columns mapped under the same attribute. :param raiseload: boolean, if True, indicates an exception should be raised diff --git a/lib/sqlalchemy/orm/attributes.py b/lib/sqlalchemy/orm/attributes.py index 82979b188..ec706d4d8 100644 --- a/lib/sqlalchemy/orm/attributes.py +++ b/lib/sqlalchemy/orm/attributes.py @@ -72,9 +72,9 @@ class QueryableAttribute( :class:`.MapperProperty` - :attr:`.Mapper.all_orm_descriptors` + :attr:`_orm.Mapper.all_orm_descriptors` - :attr:`.Mapper.attrs` + :attr:`_orm.Mapper.attrs` """ is_attribute = True @@ -134,12 +134,13 @@ class QueryableAttribute( * If the attribute is a column-mapped property, i.e. :class:`.ColumnProperty`, which is mapped directly - to a schema-level :class:`.Column` object, this attribute + to a schema-level :class:`_schema.Column` object, this attribute will return the :attr:`.SchemaItem.info` dictionary associated - with the core-level :class:`.Column` object. + with the core-level :class:`_schema.Column` object. * If the attribute is a :class:`.ColumnProperty` but is mapped to - any other kind of SQL expression other than a :class:`.Column`, + any other kind of SQL expression other than a + :class:`_schema.Column`, the attribute will refer to the :attr:`.MapperProperty.info` dictionary associated directly with the :class:`.ColumnProperty`, assuming the SQL expression itself does not have its own ``.info`` @@ -154,7 +155,7 @@ class QueryableAttribute( * To access the :attr:`.MapperProperty.info` dictionary of the :class:`.MapperProperty` unconditionally, including for a :class:`.ColumnProperty` that's associated directly with a - :class:`.schema.Column`, the attribute can be referred to using + :class:`_schema.Column`, the attribute can be referred to using :attr:`.QueryableAttribute.property` attribute, as ``MyClass.someattribute.property.info``. @@ -171,7 +172,7 @@ class QueryableAttribute( def parent(self): """Return an inspection instance representing the parent. - This will be either an instance of :class:`.Mapper` + This will be either an instance of :class:`_orm.Mapper` or :class:`.AliasedInsp`, depending upon the nature of the parent entity which this attribute is associated with. @@ -1608,7 +1609,7 @@ class History(util.namedtuple("History", ["added", "unchanged", "deleted"])): attribute. The easiest way to get a :class:`.History` object for a particular - attribute on an object is to use the :func:`.inspect` function:: + attribute on an object is to use the :func:`_sa.inspect` function:: from sqlalchemy import inspect diff --git a/lib/sqlalchemy/orm/base.py b/lib/sqlalchemy/orm/base.py index 6df8acf1e..07809282b 100644 --- a/lib/sqlalchemy/orm/base.py +++ b/lib/sqlalchemy/orm/base.py @@ -166,7 +166,7 @@ EXT_SKIP = util.symbol("EXT_SKIP") ONETOMANY = util.symbol( "ONETOMANY", - """Indicates the one-to-many direction for a :func:`.relationship`. + """Indicates the one-to-many direction for a :func:`_orm.relationship`. This symbol is typically used by the internals but may be exposed within certain API features. @@ -176,7 +176,7 @@ ONETOMANY = util.symbol( MANYTOONE = util.symbol( "MANYTOONE", - """Indicates the many-to-one direction for a :func:`.relationship`. + """Indicates the many-to-one direction for a :func:`_orm.relationship`. This symbol is typically used by the internals but may be exposed within certain API features. @@ -186,7 +186,7 @@ MANYTOONE = util.symbol( MANYTOMANY = util.symbol( "MANYTOMANY", - """Indicates the many-to-many direction for a :func:`.relationship`. + """Indicates the many-to-many direction for a :func:`_orm.relationship`. This symbol is typically used by the internals but may be exposed within certain API features. @@ -298,7 +298,7 @@ def object_state(instance): Raises :class:`sqlalchemy.orm.exc.UnmappedInstanceError` if no mapping is configured. - Equivalent functionality is available via the :func:`.inspect` + Equivalent functionality is available via the :func:`_sa.inspect` function as:: inspect(instance) @@ -336,7 +336,7 @@ def _class_to_mapper(class_or_mapper): def _mapper_or_none(entity): - """Return the :class:`.Mapper` for the given class or None if the + """Return the :class:`_orm.Mapper` for the given class or None if the class is not mapped. """ @@ -349,7 +349,7 @@ def _mapper_or_none(entity): def _is_mapped_class(entity): """Return True if the given object is a mapped class, - :class:`.Mapper`, or :class:`.AliasedClass`. + :class:`_orm.Mapper`, or :class:`.AliasedClass`. """ insp = inspection.inspect(entity, False) @@ -422,14 +422,14 @@ def _inspect_mapped_class(class_, configure=False): def class_mapper(class_, configure=True): - """Given a class, return the primary :class:`.Mapper` associated + """Given a class, return the primary :class:`_orm.Mapper` associated with the key. Raises :exc:`.UnmappedClassError` if no mapping is configured on the given class, or :exc:`.ArgumentError` if a non-class object is passed. - Equivalent functionality is available via the :func:`.inspect` + Equivalent functionality is available via the :func:`_sa.inspect` function as:: inspect(some_mapped_class) @@ -451,7 +451,7 @@ def class_mapper(class_, configure=True): class InspectionAttr(object): """A base class applied to all ORM objects that can be returned - by the :func:`.inspect` function. + by the :func:`_sa.inspect` function. The attributes defined here allow the usage of simple boolean checks to test basic facts about the object returned. @@ -467,7 +467,8 @@ class InspectionAttr(object): __slots__ = () is_selectable = False - """Return True if this object is an instance of :class:`.Selectable`.""" + """Return True if this object is an instance of """ + """:class:`expression.Selectable`.""" is_aliased_class = False """True if this object is an instance of :class:`.AliasedClass`.""" @@ -476,7 +477,7 @@ class InspectionAttr(object): """True if this object is an instance of :class:`.InstanceState`.""" is_mapper = False - """True if this object is an instance of :class:`.Mapper`.""" + """True if this object is an instance of :class:`_orm.Mapper`.""" is_property = False """True if this object is an instance of :class:`.MapperProperty`.""" @@ -493,7 +494,7 @@ class InspectionAttr(object): .. seealso:: - :attr:`.Mapper.all_orm_descriptors` + :attr:`_orm.Mapper.all_orm_descriptors` """ @@ -505,7 +506,8 @@ class InspectionAttr(object): """ is_clause_element = False - """True if this object is an instance of :class:`.ClauseElement`.""" + """True if this object is an instance of """ + """:class:`_expression.ClauseElement`.""" extension_type = NOT_EXTENSION """The extension type, if any. @@ -538,7 +540,8 @@ class InspectionAttrInfo(InspectionAttr): The dictionary is generated when first accessed. Alternatively, it can be specified as a constructor argument to the - :func:`.column_property`, :func:`.relationship`, or :func:`.composite` + :func:`.column_property`, :func:`_orm.relationship`, or + :func:`.composite` functions. .. versionchanged:: 1.0.0 :attr:`.MapperProperty.info` is also diff --git a/lib/sqlalchemy/orm/descriptor_props.py b/lib/sqlalchemy/orm/descriptor_props.py index 3bc009da8..7fff13101 100644 --- a/lib/sqlalchemy/orm/descriptor_props.py +++ b/lib/sqlalchemy/orm/descriptor_props.py @@ -550,14 +550,18 @@ class SynonymProperty(DescriptorProperty): :param map_column: **For classical mappings and mappings against an existing Table object only**. if ``True``, the :func:`.synonym` - construct will locate the :class:`.Column` object upon the mapped + construct will locate the :class:`_schema.Column` + object upon the mapped table that would normally be associated with the attribute name of this synonym, and produce a new :class:`.ColumnProperty` that instead - maps this :class:`.Column` to the alternate name given as the "name" + maps this :class:`_schema.Column` + to the alternate name given as the "name" argument of the synonym; in this way, the usual step of redefining - the mapping of the :class:`.Column` to be under a different name is + the mapping of the :class:`_schema.Column` + to be under a different name is unnecessary. This is usually intended to be used when a - :class:`.Column` is to be replaced with an attribute that also uses a + :class:`_schema.Column` + is to be replaced with an attribute that also uses a descriptor, that is, in conjunction with the :paramref:`.synonym.descriptor` parameter:: diff --git a/lib/sqlalchemy/orm/events.py b/lib/sqlalchemy/orm/events.py index a41ea49e8..f08ef085b 100644 --- a/lib/sqlalchemy/orm/events.py +++ b/lib/sqlalchemy/orm/events.py @@ -143,8 +143,8 @@ class InstanceEvents(event.Events): * mapped classes * unmapped superclasses of mapped or to-be-mapped classes (using the ``propagate=True`` flag) - * :class:`.Mapper` objects - * the :class:`.Mapper` class itself and the :func:`.mapper` + * :class:`_orm.Mapper` objects + * the :class:`_orm.Mapper` class itself and the :func:`.mapper` function indicate listening for all mappers. Instance events are closely related to mapper events, but @@ -369,15 +369,15 @@ class InstanceEvents(event.Events): The :meth:`.InstanceEvents.load` event is also available in a - class-method decorator format called :func:`.orm.reconstructor`. + class-method decorator format called :func:`_orm.reconstructor`. :param target: the mapped instance. If the event is configured with ``raw=True``, this will instead be the :class:`.InstanceState` state-management object associated with the instance. :param context: the :class:`.QueryContext` corresponding to the - current :class:`.Query` in progress. This argument may be - ``None`` if the load does not correspond to a :class:`.Query`, + current :class:`_query.Query` in progress. This argument may be + ``None`` if the load does not correspond to a :class:`_query.Query`, such as during :meth:`.Session.merge`. .. seealso:: @@ -413,7 +413,7 @@ class InstanceEvents(event.Events): instead be the :class:`.InstanceState` state-management object associated with the instance. :param context: the :class:`.QueryContext` corresponding to the - current :class:`.Query` in progress. + current :class:`_query.Query` in progress. :param attrs: sequence of attribute names which were populated, or None if all column-mapped, non-deferred attributes were populated. @@ -617,8 +617,8 @@ class MapperEvents(event.Events): * mapped classes * unmapped superclasses of mapped or to-be-mapped classes (using the ``propagate=True`` flag) - * :class:`.Mapper` objects - * the :class:`.Mapper` class itself and the :func:`.mapper` + * :class:`_orm.Mapper` objects + * the :class:`_orm.Mapper` class itself and the :func:`.mapper` function indicate listening for all mappers. Mapper events provide hooks into critical sections of the @@ -747,7 +747,7 @@ class MapperEvents(event.Events): This event is the earliest phase of mapper construction. Most attributes of the mapper are not yet initialized. - This listener can either be applied to the :class:`.Mapper` + This listener can either be applied to the :class:`_orm.Mapper` class overall, or to any un-mapped class which serves as a base for classes that will be mapped (using the ``propagate=True`` flag):: @@ -757,7 +757,7 @@ class MapperEvents(event.Events): def on_new_class(mapper, cls_): " ... " - :param mapper: the :class:`.Mapper` which is the target + :param mapper: the :class:`_orm.Mapper` which is the target of this event. :param class\_: the mapped class. @@ -817,9 +817,9 @@ class MapperEvents(event.Events): The :meth:`.MapperEvents.mapper_configured` event is invoked for each mapper that is encountered when the - :func:`.orm.configure_mappers` function proceeds through the current + :func:`_orm.configure_mappers` function proceeds through the current list of not-yet-configured mappers. - :func:`.orm.configure_mappers` is typically invoked + :func:`_orm.configure_mappers` is typically invoked automatically as mappings are first used, as well as each time new mappers have been made available and new mapper use is detected. @@ -850,7 +850,7 @@ class MapperEvents(event.Events): on a specific mapper basis, which don't require that "backref" configurations are necessarily ready yet. - :param mapper: the :class:`.Mapper` which is the target + :param mapper: the :class:`_orm.Mapper` which is the target of this event. :param class\_: the mapped class. @@ -869,14 +869,14 @@ class MapperEvents(event.Events): """Called before a series of mappers have been configured. The :meth:`.MapperEvents.before_configured` event is invoked - each time the :func:`.orm.configure_mappers` function is + each time the :func:`_orm.configure_mappers` function is invoked, before the function has done any of its work. - :func:`.orm.configure_mappers` is typically invoked + :func:`_orm.configure_mappers` is typically invoked automatically as mappings are first used, as well as each time new mappers have been made available and new mapper use is detected. - This event can **only** be applied to the :class:`.Mapper` class + This event can **only** be applied to the :class:`_orm.Mapper` class or :func:`.mapper` function, and not to individual mappings or mapped classes. It is only invoked for all mappings as a whole:: @@ -894,7 +894,7 @@ class MapperEvents(event.Events): Theoretically this event is called once per application, but is actually called any time new mappers - are to be affected by a :func:`.orm.configure_mappers` + are to be affected by a :func:`_orm.configure_mappers` call. If new mappings are constructed after existing ones have already been used, this event will likely be called again. To ensure that a particular event is only called once and no further, the @@ -924,9 +924,9 @@ class MapperEvents(event.Events): """Called after a series of mappers have been configured. The :meth:`.MapperEvents.after_configured` event is invoked - each time the :func:`.orm.configure_mappers` function is + each time the :func:`_orm.configure_mappers` function is invoked, after the function has completed its work. - :func:`.orm.configure_mappers` is typically invoked + :func:`_orm.configure_mappers` is typically invoked automatically as mappings are first used, as well as each time new mappers have been made available and new mapper use is detected. @@ -939,7 +939,7 @@ class MapperEvents(event.Events): Also contrast to :meth:`.MapperEvents.before_configured`, which is invoked before the series of mappers has been configured. - This event can **only** be applied to the :class:`.Mapper` class + This event can **only** be applied to the :class:`_orm.Mapper` class or :func:`.mapper` function, and not to individual mappings or mapped classes. It is only invoked for all mappings as a whole:: @@ -951,7 +951,7 @@ class MapperEvents(event.Events): Theoretically this event is called once per application, but is actually called any time new mappers - have been affected by a :func:`.orm.configure_mappers` + have been affected by a :func:`_orm.configure_mappers` call. If new mappings are constructed after existing ones have already been used, this event will likely be called again. To ensure that a particular event is only called once and no further, the @@ -996,14 +996,14 @@ class MapperEvents(event.Events): Mapper-level flush events only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given - :class:`.Connection`. **Please read fully** the notes + :class:`_engine.Connection`. **Please read fully** the notes at :ref:`session_persistence_mapper` for guidelines on using these methods; generally, the :meth:`.SessionEvents.before_flush` method should be preferred for general on-flush changes. - :param mapper: the :class:`.Mapper` which is the target + :param mapper: the :class:`_orm.Mapper` which is the target of this event. - :param connection: the :class:`.Connection` being used to + :param connection: the :class:`_engine.Connection` being used to emit INSERT statements for this instance. This provides a handle into the current transaction on the target database specific to this instance. @@ -1042,14 +1042,14 @@ class MapperEvents(event.Events): Mapper-level flush events only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given - :class:`.Connection`. **Please read fully** the notes + :class:`_engine.Connection`. **Please read fully** the notes at :ref:`session_persistence_mapper` for guidelines on using these methods; generally, the :meth:`.SessionEvents.before_flush` method should be preferred for general on-flush changes. - :param mapper: the :class:`.Mapper` which is the target + :param mapper: the :class:`_orm.Mapper` which is the target of this event. - :param connection: the :class:`.Connection` being used to + :param connection: the :class:`_engine.Connection` being used to emit INSERT statements for this instance. This provides a handle into the current transaction on the target database specific to this instance. @@ -1107,14 +1107,14 @@ class MapperEvents(event.Events): Mapper-level flush events only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given - :class:`.Connection`. **Please read fully** the notes + :class:`_engine.Connection`. **Please read fully** the notes at :ref:`session_persistence_mapper` for guidelines on using these methods; generally, the :meth:`.SessionEvents.before_flush` method should be preferred for general on-flush changes. - :param mapper: the :class:`.Mapper` which is the target + :param mapper: the :class:`_orm.Mapper` which is the target of this event. - :param connection: the :class:`.Connection` being used to + :param connection: the :class:`_engine.Connection` being used to emit UPDATE statements for this instance. This provides a handle into the current transaction on the target database specific to this instance. @@ -1171,14 +1171,14 @@ class MapperEvents(event.Events): Mapper-level flush events only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given - :class:`.Connection`. **Please read fully** the notes + :class:`_engine.Connection`. **Please read fully** the notes at :ref:`session_persistence_mapper` for guidelines on using these methods; generally, the :meth:`.SessionEvents.before_flush` method should be preferred for general on-flush changes. - :param mapper: the :class:`.Mapper` which is the target + :param mapper: the :class:`_orm.Mapper` which is the target of this event. - :param connection: the :class:`.Connection` being used to + :param connection: the :class:`_engine.Connection` being used to emit UPDATE statements for this instance. This provides a handle into the current transaction on the target database specific to this instance. @@ -1211,14 +1211,14 @@ class MapperEvents(event.Events): Mapper-level flush events only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given - :class:`.Connection`. **Please read fully** the notes + :class:`_engine.Connection`. **Please read fully** the notes at :ref:`session_persistence_mapper` for guidelines on using these methods; generally, the :meth:`.SessionEvents.before_flush` method should be preferred for general on-flush changes. - :param mapper: the :class:`.Mapper` which is the target + :param mapper: the :class:`_orm.Mapper` which is the target of this event. - :param connection: the :class:`.Connection` being used to + :param connection: the :class:`_engine.Connection` being used to emit DELETE statements for this instance. This provides a handle into the current transaction on the target database specific to this instance. @@ -1251,14 +1251,14 @@ class MapperEvents(event.Events): Mapper-level flush events only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given - :class:`.Connection`. **Please read fully** the notes + :class:`_engine.Connection`. **Please read fully** the notes at :ref:`session_persistence_mapper` for guidelines on using these methods; generally, the :meth:`.SessionEvents.before_flush` method should be preferred for general on-flush changes. - :param mapper: the :class:`.Mapper` which is the target + :param mapper: the :class:`_orm.Mapper` which is the target of this event. - :param connection: the :class:`.Connection` being used to + :param connection: the :class:`_engine.Connection` being used to emit DELETE statements for this instance. This provides a handle into the current transaction on the target database specific to this instance. @@ -1666,7 +1666,7 @@ class SessionEvents(event.Events): :param session: The target :class:`.Session`. :param transaction: The :class:`.SessionTransaction`. - :param connection: The :class:`~.engine.Connection` object + :param connection: The :class:`_engine.Connection` object which will be used for SQL statements. .. seealso:: @@ -1734,16 +1734,17 @@ class SessionEvents(event.Events): def after_bulk_update(self, update_context): """Execute after a bulk update operation to the session. - This is called as a result of the :meth:`.Query.update` method. + This is called as a result of the :meth:`_query.Query.update` method. :param update_context: an "update context" object which contains details about the update, including these attributes: * ``session`` - the :class:`.Session` involved - * ``query`` -the :class:`.Query` object that this update operation + * ``query`` -the :class:`_query.Query` + object that this update operation was called upon. * ``values`` The "values" dictionary that was passed to - :meth:`.Query.update`. + :meth:`_query.Query.update`. * ``context`` The :class:`.QueryContext` object, corresponding to the invocation of an ORM query. * ``result`` the :class:`.ResultProxy` returned as a result of the @@ -1770,13 +1771,14 @@ class SessionEvents(event.Events): def after_bulk_delete(self, delete_context): """Execute after a bulk delete operation to the session. - This is called as a result of the :meth:`.Query.delete` method. + This is called as a result of the :meth:`_query.Query.delete` method. :param delete_context: a "delete context" object which contains details about the update, including these attributes: * ``session`` - the :class:`.Session` involved - * ``query`` -the :class:`.Query` object that this update operation + * ``query`` -the :class:`_query.Query` + object that this update operation was called upon. * ``context`` The :class:`.QueryContext` object, corresponding to the invocation of an ORM query. @@ -2098,7 +2100,7 @@ class AttributeEvents(event.Events): replaced unconditionally, even if this requires firing off database loads. Note that ``active_history`` can also be set directly via :func:`.column_property` and - :func:`.relationship`. + :func:`_orm.relationship`. :param propagate=False: When True, the listener function will be established not just for the class attribute given, but @@ -2338,10 +2340,12 @@ class AttributeEvents(event.Events): Python's usual behavior of raising ``AttributeError``. The event here can be used to customize what value is actually returned, with the assumption that the event listener would be mirroring - a default generator that is configured on the Core :class:`.Column` + a default generator that is configured on the Core + :class:`_schema.Column` object as well. - Since a default generator on a :class:`.Column` might also produce + Since a default generator on a :class:`_schema.Column` + might also produce a changing value such as a timestamp, the :meth:`.AttributeEvents.init_scalar` event handler can also be used to **set** the newly returned value, so @@ -2375,7 +2379,7 @@ class AttributeEvents(event.Events): * By setting the value ``SOME_CONSTANT`` in the given ``dict_``, we indicate that this value is to be persisted to the database. This supersedes the use of ``SOME_CONSTANT`` in the default generator - for the :class:`.Column`. The ``active_column_defaults.py`` + for the :class:`_schema.Column`. The ``active_column_defaults.py`` example given at :ref:`examples_instrumentation` illustrates using the same approach for a changing default, e.g. a timestamp generator. In this particular example, it is not strictly @@ -2394,7 +2398,7 @@ class AttributeEvents(event.Events): In the above example, the attribute set event :meth:`.AttributeEvents.set` as well as the related validation feature - provided by :obj:`.orm.validates` is **not** invoked when we apply our + provided by :obj:`_orm.validates` is **not** invoked when we apply our value to the given ``dict_``. To have these events to invoke in response to our newly generated value, apply the value to the given object as a normal attribute set operation:: @@ -2467,7 +2471,7 @@ class AttributeEvents(event.Events): be the :class:`.InstanceState` object. :param collection: the new collection. This will always be generated from what was specified as - :paramref:`.relationship.collection_class`, and will always + :paramref:`_orm.relationship.collection_class`, and will always be empty. :param collection_adapter: the :class:`.CollectionAdapter` that will mediate internal access to the collection. @@ -2537,10 +2541,11 @@ class AttributeEvents(event.Events): class QueryEvents(event.Events): - """Represent events within the construction of a :class:`.Query` object. + """Represent events within the construction of a :class:`_query.Query` + object. The events here are intended to be used with an as-yet-unreleased - inspection system for :class:`.Query`. Some very basic operations + inspection system for :class:`_query.Query`. Some very basic operations are possible now, however the inspection system is intended to allow complex query manipulations to be automated. @@ -2552,8 +2557,9 @@ class QueryEvents(event.Events): _dispatch_target = Query def before_compile(self, query): - """Receive the :class:`.Query` object before it is composed into a - core :class:`.Select` object. + """Receive the :class:`_query.Query` + object before it is composed into a + core :class:`_expression.Select` object. This event is intended to allow changes to the query given:: @@ -2570,7 +2576,8 @@ class QueryEvents(event.Events): The :meth:`.QueryEvents.before_compile` event by default will disallow "baked" queries from caching a query, if the event - hook returns a new :class:`.Query` object. This affects both direct + hook returns a new :class:`_query.Query` object. + This affects both direct use of the baked query extension as well as its operation within lazy loaders and eager loaders for relationships. In order to re-establish the query being cached, apply the event adding the @@ -2592,7 +2599,7 @@ class QueryEvents(event.Events): .. versionadded:: 1.3.11 - added the "bake_ok" flag to the :meth:`.QueryEvents.before_compile` event and disallowed caching via the "baked" extension from occurring for event handlers that - return a new :class:`.Query` object if this flag is not set. + return a new :class:`_query.Query` object if this flag is not set. .. seealso:: @@ -2605,13 +2612,13 @@ class QueryEvents(event.Events): """ def before_compile_update(self, query, update_context): - """Allow modifications to the :class:`.Query` object within - :meth:`.Query.update`. + """Allow modifications to the :class:`_query.Query` object within + :meth:`_query.Query.update`. Like the :meth:`.QueryEvents.before_compile` event, if the event - is to be used to alter the :class:`.Query` object, it should + is to be used to alter the :class:`_query.Query` object, it should be configured with ``retval=True``, and the modified - :class:`.Query` object returned, as in :: + :class:`_query.Query` object returned, as in :: @event.listens_for(Query, "before_compile_update", retval=True) def no_deleted(query, update_context): @@ -2626,7 +2633,7 @@ class QueryEvents(event.Events): The ``.values`` dictionary of the "update context" object can also be modified in place as illustrated above. - :param query: a :class:`.Query` instance; this is also + :param query: a :class:`_query.Query` instance; this is also the ``.query`` attribute of the given "update context" object. @@ -2634,7 +2641,8 @@ class QueryEvents(event.Events): the same kind of object as described in :paramref:`.QueryEvents.after_bulk_update.update_context`. The object has a ``.values`` attribute in an UPDATE context which is - the dictionary of parameters passed to :meth:`.Query.update`. This + the dictionary of parameters passed to :meth:`_query.Query.update`. + This dictionary can be modified to alter the VALUES clause of the resulting UPDATE statement. @@ -2650,12 +2658,12 @@ class QueryEvents(event.Events): """ def before_compile_delete(self, query, delete_context): - """Allow modifications to the :class:`.Query` object within - :meth:`.Query.delete`. + """Allow modifications to the :class:`_query.Query` object within + :meth:`_query.Query.delete`. Like the :meth:`.QueryEvents.before_compile` event, this event should be configured with ``retval=True``, and the modified - :class:`.Query` object returned, as in :: + :class:`_query.Query` object returned, as in :: @event.listens_for(Query, "before_compile_delete", retval=True) def no_deleted(query, delete_context): @@ -2665,7 +2673,7 @@ class QueryEvents(event.Events): query = query.filter(entity.deleted == False) return query - :param query: a :class:`.Query` instance; this is also + :param query: a :class:`_query.Query` instance; this is also the ``.query`` attribute of the given "delete context" object. diff --git a/lib/sqlalchemy/orm/exc.py b/lib/sqlalchemy/orm/exc.py index 0c2565487..b04b844b3 100644 --- a/lib/sqlalchemy/orm/exc.py +++ b/lib/sqlalchemy/orm/exc.py @@ -111,7 +111,7 @@ class ObjectDeletedError(sa_exc.InvalidRequestError): row corresponding to an object's known primary key identity. A refresh operation proceeds when an expired attribute is - accessed on an object, or when :meth:`.Query.get` is + accessed on an object, or when :meth:`_query.Query.get` is used to retrieve an object which is, upon retrieval, detected as expired. A SELECT is emitted for the target row based on primary key; if no row is returned, this diff --git a/lib/sqlalchemy/orm/interfaces.py b/lib/sqlalchemy/orm/interfaces.py index 57c192a5d..612724357 100644 --- a/lib/sqlalchemy/orm/interfaces.py +++ b/lib/sqlalchemy/orm/interfaces.py @@ -65,12 +65,12 @@ __all__ = ( class MapperProperty( HasCacheKey, _MappedAttribute, InspectionAttr, util.MemoizedSlots ): - """Represent a particular class attribute mapped by :class:`.Mapper`. + """Represent a particular class attribute mapped by :class:`_orm.Mapper`. The most common occurrences of :class:`.MapperProperty` are the - mapped :class:`.Column`, which is represented in a mapping as + mapped :class:`_schema.Column`, which is represented in a mapping as an instance of :class:`.ColumnProperty`, - and a reference to another class produced by :func:`.relationship`, + and a reference to another class produced by :func:`_orm.relationship`, represented in the mapping as an instance of :class:`.RelationshipProperty`. @@ -110,7 +110,8 @@ class MapperProperty( The dictionary is generated when first accessed. Alternatively, it can be specified as a constructor argument to the - :func:`.column_property`, :func:`.relationship`, or :func:`.composite` + :func:`.column_property`, :func:`_orm.relationship`, or + :func:`.composite` functions. .. versionchanged:: 1.0.0 :attr:`.MapperProperty.info` is also @@ -389,7 +390,8 @@ class PropComparator(operators.ColumnOperators): """Receive a SQL expression that represents a value in the SET clause of an UPDATE statement. - Return a tuple that can be passed to a :class:`.Update` construct. + Return a tuple that can be passed to a :class:`_expression.Update` + construct. """ @@ -655,7 +657,7 @@ class MapperOption(object): """ def process_query(self, query): - """Apply a modification to the given :class:`.Query`.""" + """Apply a modification to the given :class:`_query.Query`.""" def process_query_conditionally(self, query): """same as process_query(), except that this option may not @@ -673,14 +675,15 @@ class MapperOption(object): def _generate_path_cache_key(self, path): """Used by the "baked lazy loader" to see if this option can be cached. - The "baked lazy loader" refers to the :class:`.Query` that is + The "baked lazy loader" refers to the :class:`_query.Query` that is produced during a lazy load operation for a mapped relationship. It does not yet apply to the "lazy" load operation for deferred or expired column attributes, however this may change in the future. This loader generates SQL for a query only once and attempts to cache it; from that point on, if the SQL has been cached it will no longer - run the :meth:`.Query.options` method of the :class:`.Query`. The + run the :meth:`_query.Query.options` method of the + :class:`_query.Query`. The :class:`.MapperOption` object that wishes to participate within a lazy load operation therefore needs to tell the baked loader that it either needs to forego this caching, or that it needs to include the state of @@ -694,7 +697,7 @@ class MapperOption(object): not cache the SQL when this :class:`.MapperOption` is present. This is the safest option and ensures both that the option is invoked every time, and also that the cache isn't filled up with - an unlimited number of :class:`.Query` objects for an unlimited + an unlimited number of :class:`_query.Query` objects for an unlimited number of :class:`.MapperOption` objects. .. versionchanged:: 1.2.8 the default return value of @@ -702,7 +705,8 @@ class MapperOption(object): was ``None`` indicating "safe to cache, don't include as part of the cache key" - To enable caching of :class:`.Query` objects within lazy loaders, a + To enable caching of :class:`_query.Query` objects within lazy loaders + , a given :class:`.MapperOption` that returns a cache key must return a key that uniquely identifies the complete state of this option, which will match any other :class:`.MapperOption` that itself retains the @@ -712,7 +716,7 @@ class MapperOption(object): If the :class:`.MapperOption` does not apply to the given path and would not affect query results on such a path, it should return None, - indicating the :class:`.Query` is safe to cache for this given + indicating the :class:`_query.Query` is safe to cache for this given loader path and that this :class:`.MapperOption` need not be part of the cache key. diff --git a/lib/sqlalchemy/orm/loading.py b/lib/sqlalchemy/orm/loading.py index b7ef96e1a..5ef2f10ec 100644 --- a/lib/sqlalchemy/orm/loading.py +++ b/lib/sqlalchemy/orm/loading.py @@ -106,7 +106,7 @@ def instances(query, cursor, context): @util.preload_module("sqlalchemy.orm.query") def merge_result(query, iterator, load=True): - """Merge a result into this :class:`.Query` object's Session.""" + """Merge a result into this :class:`_query.Query` object's Session.""" querylib = util.preloaded.orm_query session = query.session diff --git a/lib/sqlalchemy/orm/mapper.py b/lib/sqlalchemy/orm/mapper.py index 3e4c3a5d5..31f005769 100644 --- a/lib/sqlalchemy/orm/mapper.py +++ b/lib/sqlalchemy/orm/mapper.py @@ -74,9 +74,9 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): """Define the correlation of class attributes to database table columns. - The :class:`.Mapper` object is instantiated using the + The :class:`_orm.Mapper` object is instantiated using the :func:`~sqlalchemy.orm.mapper` function. For information - about instantiating new :class:`.Mapper` objects, see + about instantiating new :class:`_orm.Mapper` objects, see that function's documentation. @@ -89,8 +89,8 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): makes usage of :func:`.mapper` behind the scenes. Given a particular class known to be mapped by the ORM, - the :class:`.Mapper` which maintains it can be acquired - using the :func:`.inspect` function:: + the :class:`_orm.Mapper` which maintains it can be acquired + using the :func:`_sa.inspect` function:: from sqlalchemy import inspect @@ -113,7 +113,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): "and will be removed in a future release. The functionality " "of non primary mappers is now better suited using the " ":class:`.AliasedClass` construct, which can also be used " - "as the target of a :func:`.relationship` in 1.3.", + "as the target of a :func:`_orm.relationship` in 1.3.", ), ) def __init__( @@ -147,7 +147,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): legacy_is_orphan=False, _compiled_cache_size=100, ): - r"""Return a new :class:`~.Mapper` object. + r"""Return a new :class:`_orm.Mapper` object. This function is typically used behind the scenes via the Declarative extension. When using Declarative, @@ -196,21 +196,22 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): this argument is automatically passed as the declared class itself. - :param local_table: The :class:`.Table` or other selectable + :param local_table: The :class:`_schema.Table` or other selectable to which the class is mapped. May be ``None`` if this mapper inherits from another mapper using single-table inheritance. When using Declarative, this argument is automatically passed by the extension, based on what is configured via the ``__table__`` argument or via the - :class:`.Table` produced as a result of the ``__tablename__`` - and :class:`.Column` arguments present. + :class:`_schema.Table` + produced as a result of the ``__tablename__`` + and :class:`_schema.Column` arguments present. :param always_refresh: If True, all query operations for this mapped class will overwrite all data within object instances that already exist within the session, erasing any in-memory changes with whatever information was loaded from the database. Usage of this flag is highly discouraged; as an alternative, see the method - :meth:`.Query.populate_existing`. + :meth:`_query.Query.populate_existing`. :param allow_partial_pks: Defaults to True. Indicates that a composite primary key with some NULL values should be considered as @@ -229,7 +230,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): in between individual row persistence operations. :param column_prefix: A string which will be prepended - to the mapped attribute name when :class:`.Column` + to the mapped attribute name when :class:`_schema.Column` objects are automatically assigned as attributes to the mapped class. Does not affect explicitly specified column-based properties. @@ -283,8 +284,9 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): See :ref:`include_exclude_cols` for an example. - :param inherits: A mapped class or the corresponding :class:`.Mapper` - of one indicating a superclass to which this :class:`.Mapper` + :param inherits: A mapped class or the corresponding + :class:`_orm.Mapper` + of one indicating a superclass to which this :class:`_orm.Mapper` should *inherit* from. The mapped class here must be a subclass of the other mapper's class. When using Declarative, this argument is passed automatically as a result of the natural class @@ -300,7 +302,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): between the two tables. :param inherit_foreign_keys: When ``inherit_condition`` is used and - the columns present are missing a :class:`.ForeignKey` + the columns present are missing a :class:`_schema.ForeignKey` configuration, this parameter can be used to specify which columns are "foreign". In most cases can be left as ``None``. @@ -320,14 +322,15 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): See the change note and example at :ref:`legacy_is_orphan_addition` for more detail on this change. - :param non_primary: Specify that this :class:`.Mapper` is in addition + :param non_primary: Specify that this :class:`_orm.Mapper` + is in addition to the "primary" mapper, that is, the one used for persistence. - The :class:`.Mapper` created here may be used for ad-hoc + The :class:`_orm.Mapper` created here may be used for ad-hoc mapping of the class to an alternate selectable, for loading only. - :paramref:`.Mapper.non_primary` is not an often used option, but - is useful in some specific :func:`.relationship` cases. + :paramref:`_orm.Mapper.non_primary` is not an often used option, but + is useful in some specific :func:`_orm.relationship` cases. .. seealso:: @@ -362,7 +365,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): .. seealso:: :ref:`passive_deletes` - description of similar feature as - used with :func:`.relationship` + used with :func:`_orm.relationship` :paramref:`.mapper.passive_updates` - supporting ON UPDATE CASCADE for joined-table inheritance mappers @@ -385,7 +388,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): .. seealso:: :ref:`passive_updates` - description of a similar feature as - used with :func:`.relationship` + used with :func:`_orm.relationship` :paramref:`.mapper.passive_deletes` - supporting ON DELETE CASCADE for joined-table inheritance mappers @@ -415,8 +418,8 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): SQL expression used to determine the target class for an incoming row, when inheriting classes are present. - This value is commonly a :class:`.Column` object that's - present in the mapped :class:`.Table`:: + This value is commonly a :class:`_schema.Column` object that's + present in the mapped :class:`_schema.Table`:: class Employee(Base): __tablename__ = 'employee' @@ -471,7 +474,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): When setting ``polymorphic_on`` to reference an attribute or expression that's not present in the - locally mapped :class:`.Table`, yet the value + locally mapped :class:`_schema.Table`, yet the value of the discriminator should be persisted to the database, the value of the discriminator is not automatically set on new @@ -513,20 +516,22 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): :param properties: A dictionary mapping the string names of object attributes to :class:`.MapperProperty` instances, which define the - persistence behavior of that attribute. Note that :class:`.Column` + persistence behavior of that attribute. Note that + :class:`_schema.Column` objects present in - the mapped :class:`.Table` are automatically placed into + the mapped :class:`_schema.Table` are automatically placed into ``ColumnProperty`` instances upon mapping, unless overridden. When using Declarative, this argument is passed automatically, based on all those :class:`.MapperProperty` instances declared in the declared class body. - :param primary_key: A list of :class:`.Column` objects which define + :param primary_key: A list of :class:`_schema.Column` + objects which define the primary key to be used against this mapper's selectable unit. This is normally simply the primary key of the ``local_table``, but can be overridden here. - :param version_id_col: A :class:`.Column` + :param version_id_col: A :class:`_schema.Column` that will be used to keep a running version id of rows in the table. This is used to detect concurrent updates or the presence of stale data in a flush. The methodology is to @@ -721,34 +726,38 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): return self.class_ local_table = None - """The :class:`.Selectable` which this :class:`.Mapper` manages. + """The :class:`expression.Selectable` which this :class:`_orm.Mapper` + manages. - Typically is an instance of :class:`.Table` or :class:`.Alias`. + Typically is an instance of :class:`_schema.Table` or + :class:`_expression.Alias`. May also be ``None``. The "local" table is the - selectable that the :class:`.Mapper` is directly responsible for + selectable that the :class:`_orm.Mapper` is directly responsible for managing from an attribute access and flush perspective. For non-inheriting mappers, the local table is the same as the "mapped" table. For joined-table inheritance mappers, local_table will be the particular sub-table of the overall "join" which - this :class:`.Mapper` represents. If this mapper is a + this :class:`_orm.Mapper` represents. If this mapper is a single-table inheriting mapper, local_table will be ``None``. .. seealso:: - :attr:`~.Mapper.persist_selectable`. + :attr:`_orm.Mapper.persist_selectable`. """ persist_selectable = None - """The :class:`.Selectable` to which this :class:`.Mapper` is mapped. + """The :class:`expression.Selectable` to which this :class:`_orm.Mapper` + is mapped. - Typically an instance of :class:`.Table`, :class:`.Join`, or - :class:`.Alias`. + Typically an instance of :class:`_schema.Table`, :class:`_expression.Join` + , or + :class:`_expression.Alias`. - The :attr:`.Mapper.persist_selectable` is separate from - :attr:`.Mapper.selectable` in that the former represents columns + The :attr:`_orm.Mapper.persist_selectable` is separate from + :attr:`_orm.Mapper.selectable` in that the former represents columns that are mapped on this class or its superclasses, whereas the latter may be a "polymorphic" selectable that contains additional columns which are in fact mapped on subclasses only. @@ -756,21 +765,21 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): "persist selectable" is the "thing the mapper writes to" and "selectable" is the "thing the mapper selects from". - :attr:`.Mapper.persist_selectable` is also separate from - :attr:`.Mapper.local_table`, which represents the set of columns that + :attr:`_orm.Mapper.persist_selectable` is also separate from + :attr:`_orm.Mapper.local_table`, which represents the set of columns that are locally mapped on this class directly. .. seealso:: - :attr:`~.Mapper.selectable`. + :attr:`_orm.Mapper.selectable`. - :attr:`~.Mapper.local_table`. + :attr:`_orm.Mapper.local_table`. """ inherits = None - """References the :class:`.Mapper` which this :class:`.Mapper` + """References the :class:`_orm.Mapper` which this :class:`_orm.Mapper` inherits from, if any. This is a *read only* attribute determined during mapper construction. @@ -779,7 +788,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): """ configured = None - """Represent ``True`` if this :class:`.Mapper` has been configured. + """Represent ``True`` if this :class:`_orm.Mapper` has been configured. This is a *read only* attribute determined during mapper construction. Behavior is undefined if directly modified. @@ -791,7 +800,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): """ concrete = None - """Represent ``True`` if this :class:`.Mapper` is a concrete + """Represent ``True`` if this :class:`_orm.Mapper` is a concrete inheritance mapper. This is a *read only* attribute determined during mapper construction. @@ -800,11 +809,13 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): """ tables = None - """An iterable containing the collection of :class:`.Table` objects - which this :class:`.Mapper` is aware of. + """An iterable containing the collection of :class:`_schema.Table` objects + which this :class:`_orm.Mapper` is aware of. - If the mapper is mapped to a :class:`.Join`, or an :class:`.Alias` - representing a :class:`.Select`, the individual :class:`.Table` + If the mapper is mapped to a :class:`_expression.Join`, or an + :class:`_expression.Alias` + representing a :class:`_expression.Select`, the individual + :class:`_schema.Table` objects that comprise the full construct will be represented here. This is a *read only* attribute determined during mapper construction. @@ -813,20 +824,23 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): """ primary_key = None - """An iterable containing the collection of :class:`.Column` objects + """An iterable containing the collection of :class:`_schema.Column` + objects which comprise the 'primary key' of the mapped table, from the - perspective of this :class:`.Mapper`. + perspective of this :class:`_orm.Mapper`. - This list is against the selectable in :attr:`~.Mapper.persist_selectable`. + This list is against the selectable in + :attr:`_orm.Mapper.persist_selectable`. In the case of inheriting mappers, some columns may be managed by a - superclass mapper. For example, in the case of a :class:`.Join`, the + superclass mapper. For example, in the case of a + :class:`_expression.Join`, the primary key is determined by all of the primary key columns across all - tables referenced by the :class:`.Join`. + tables referenced by the :class:`_expression.Join`. The list is also not necessarily the same as the primary key column - collection associated with the underlying tables; the :class:`.Mapper` + collection associated with the underlying tables; the :class:`_orm.Mapper` features a ``primary_key`` argument that can override what the - :class:`.Mapper` considers as primary key columns. + :class:`_orm.Mapper` considers as primary key columns. This is a *read only* attribute determined during mapper construction. Behavior is undefined if directly modified. @@ -834,7 +848,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): """ class_ = None - """The Python class which this :class:`.Mapper` maps. + """The Python class which this :class:`_orm.Mapper` maps. This is a *read only* attribute determined during mapper construction. Behavior is undefined if directly modified. @@ -843,7 +857,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): class_manager = None """The :class:`.ClassManager` which maintains event listeners - and class-bound descriptors for this :class:`.Mapper`. + and class-bound descriptors for this :class:`_orm.Mapper`. This is a *read only* attribute determined during mapper construction. Behavior is undefined if directly modified. @@ -851,10 +865,10 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): """ single = None - """Represent ``True`` if this :class:`.Mapper` is a single table + """Represent ``True`` if this :class:`_orm.Mapper` is a single table inheritance mapper. - :attr:`~.Mapper.local_table` will be ``None`` if this flag is set. + :attr:`_orm.Mapper.local_table` will be ``None`` if this flag is set. This is a *read only* attribute determined during mapper construction. Behavior is undefined if directly modified. @@ -862,7 +876,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): """ non_primary = None - """Represent ``True`` if this :class:`.Mapper` is a "non-primary" + """Represent ``True`` if this :class:`_orm.Mapper` is a "non-primary" mapper, e.g. a mapper that is used only to select rows but not for persistence management. @@ -872,11 +886,11 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): """ polymorphic_on = None - """The :class:`.Column` or SQL expression specified as the + """The :class:`_schema.Column` or SQL expression specified as the ``polymorphic_on`` argument - for this :class:`.Mapper`, within an inheritance scenario. + for this :class:`_orm.Mapper`, within an inheritance scenario. - This attribute is normally a :class:`.Column` instance but + This attribute is normally a :class:`_schema.Column` instance but may also be an expression, such as one derived from :func:`.cast`. @@ -887,10 +901,10 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): polymorphic_map = None """A mapping of "polymorphic identity" identifiers mapped to - :class:`.Mapper` instances, within an inheritance scenario. + :class:`_orm.Mapper` instances, within an inheritance scenario. The identifiers can be of any type which is comparable to the - type of column represented by :attr:`~.Mapper.polymorphic_on`. + type of column represented by :attr:`_orm.Mapper.polymorphic_on`. An inheritance chain of mappers will all reference the same polymorphic map object. The object is used to correlate incoming @@ -903,11 +917,11 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): polymorphic_identity = None """Represent an identifier which is matched against the - :attr:`~.Mapper.polymorphic_on` column during result row loading. + :attr:`_orm.Mapper.polymorphic_on` column during result row loading. Used only with inheritance, this object can be of any type which is comparable to the type of column represented by - :attr:`~.Mapper.polymorphic_on`. + :attr:`_orm.Mapper.polymorphic_on`. This is a *read only* attribute determined during mapper construction. Behavior is undefined if directly modified. @@ -915,11 +929,11 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): """ base_mapper = None - """The base-most :class:`.Mapper` in an inheritance chain. + """The base-most :class:`_orm.Mapper` in an inheritance chain. In a non-inheriting scenario, this attribute will always be this - :class:`.Mapper`. In an inheritance scenario, it references - the :class:`.Mapper` which is parent to all other :class:`.Mapper` + :class:`_orm.Mapper`. In an inheritance scenario, it references + the :class:`_orm.Mapper` which is parent to all other :class:`_orm.Mapper` objects in the inheritance chain. This is a *read only* attribute determined during mapper construction. @@ -928,14 +942,15 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): """ columns = None - """A collection of :class:`.Column` or other scalar expression - objects maintained by this :class:`.Mapper`. + """A collection of :class:`_schema.Column` or other scalar expression + objects maintained by this :class:`_orm.Mapper`. The collection behaves the same as that of the ``c`` attribute on - any :class:`.Table` object, except that only those columns included in + any :class:`_schema.Table` object, + except that only those columns included in this mapping are present, and are keyed based on the attribute name defined in the mapping, not necessarily the ``key`` attribute of the - :class:`.Column` itself. Additionally, scalar expressions mapped + :class:`_schema.Column` itself. Additionally, scalar expressions mapped by :func:`.column_property` are also present here. This is a *read only* attribute determined during mapper construction. @@ -945,7 +960,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): validators = None """An immutable dictionary of attributes which have been decorated - using the :func:`~.orm.validates` decorator. + using the :func:`_orm.validates` decorator. The dictionary contains string attribute names as keys mapped to the actual validation method. @@ -953,7 +968,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): """ c = None - """A synonym for :attr:`~.Mapper.columns`.""" + """A synonym for :attr:`_orm.Mapper.columns`.""" @property @util.deprecated("1.3", "Use .persist_selectable") @@ -1139,8 +1154,8 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): ) def _set_concrete_base(self, mapper): - """Set the given :class:`.Mapper` as the 'inherits' for this - :class:`.Mapper`, assuming this :class:`.Mapper` is concrete + """Set the given :class:`_orm.Mapper` as the 'inherits' for this + :class:`_orm.Mapper`, assuming this :class:`_orm.Mapper` is concrete and does not already have an inherits.""" assert self.concrete @@ -1778,7 +1793,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): @util.preload_module("sqlalchemy.orm.descriptor_props") def _property_from_column(self, key, prop): """generate/update a :class:`.ColumnProperty` given a - :class:`.Column` object. """ + :class:`_schema.Column` object. """ descriptor_props = util.preloaded.orm_descriptor_props # we were passed a Column or a list of Columns; # generate a properties.ColumnProperty @@ -1979,7 +1994,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): ) def get_property_by_column(self, column): - """Given a :class:`.Column` object, return the + """Given a :class:`_schema.Column` object, return the :class:`.MapperProperty` which maps this column.""" return self._columntoproperty[column] @@ -2083,7 +2098,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): ) with_polymorphic_mappers = _with_polymorphic_mappers - """The list of :class:`.Mapper` objects included in the + """The list of :class:`_orm.Mapper` objects included in the default "polymorphic" query. """ @@ -2201,8 +2216,8 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): @property def selectable(self): - """The :func:`~.sql.expression.select` construct this - :class:`.Mapper` selects from by default. + """The :func:`_expression.select` construct this + :class:`_orm.Mapper` selects from by default. Normally, this is equivalent to :attr:`.persist_selectable`, unless the ``with_polymorphic`` feature is in use, in which case the @@ -2281,14 +2296,14 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): column. The namespace object can also be iterated, which would yield each :class:`.MapperProperty`. - :class:`.Mapper` has several pre-filtered views + :class:`_orm.Mapper` has several pre-filtered views of this attribute which limit the types of properties returned, including :attr:`.synonyms`, :attr:`.column_attrs`, :attr:`.relationships`, and :attr:`.composites`. .. warning:: - The :attr:`.Mapper.attrs` accessor namespace is an + The :attr:`_orm.Mapper.attrs` accessor namespace is an instance of :class:`.OrderedProperties`. This is a dictionary-like object which includes a small number of named methods such as :meth:`.OrderedProperties.items` @@ -2299,7 +2314,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): .. seealso:: - :attr:`.Mapper.all_orm_descriptors` + :attr:`_orm.Mapper.all_orm_descriptors` """ if Mapper._new_mappers: @@ -2330,11 +2345,12 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): :attr:`.QueryableAttribute.property` attribute refers to the :class:`.MapperProperty` property, which is what you get when referring to the collection of mapped properties via - :attr:`.Mapper.attrs`. + :attr:`_orm.Mapper.attrs`. .. warning:: - The :attr:`.Mapper.all_orm_descriptors` accessor namespace is an + The :attr:`_orm.Mapper.all_orm_descriptors` + accessor namespace is an instance of :class:`.OrderedProperties`. This is a dictionary-like object which includes a small number of named methods such as :meth:`.OrderedProperties.items` @@ -2346,7 +2362,7 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): .. seealso:: - :attr:`.Mapper.attrs` + :attr:`_orm.Mapper.attrs` """ return util.ImmutableProperties( @@ -2357,11 +2373,12 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): @util.preload_module("sqlalchemy.orm.descriptor_props") def synonyms(self): """Return a namespace of all :class:`.SynonymProperty` - properties maintained by this :class:`.Mapper`. + properties maintained by this :class:`_orm.Mapper`. .. seealso:: - :attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty` + :attr:`_orm.Mapper.attrs` - namespace of all + :class:`.MapperProperty` objects. """ @@ -2372,11 +2389,12 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): @HasMemoized.memoized_attribute def column_attrs(self): """Return a namespace of all :class:`.ColumnProperty` - properties maintained by this :class:`.Mapper`. + properties maintained by this :class:`_orm.Mapper`. .. seealso:: - :attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty` + :attr:`_orm.Mapper.attrs` - namespace of all + :class:`.MapperProperty` objects. """ @@ -2386,11 +2404,11 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): @HasMemoized.memoized_attribute def relationships(self): """A namespace of all :class:`.RelationshipProperty` properties - maintained by this :class:`.Mapper`. + maintained by this :class:`_orm.Mapper`. .. warning:: - the :attr:`.Mapper.relationships` accessor namespace is an + the :attr:`_orm.Mapper.relationships` accessor namespace is an instance of :class:`.OrderedProperties`. This is a dictionary-like object which includes a small number of named methods such as :meth:`.OrderedProperties.items` @@ -2402,7 +2420,8 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): .. seealso:: - :attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty` + :attr:`_orm.Mapper.attrs` - namespace of all + :class:`.MapperProperty` objects. """ @@ -2414,11 +2433,12 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): @util.preload_module("sqlalchemy.orm.descriptor_props") def composites(self): """Return a namespace of all :class:`.CompositeProperty` - properties maintained by this :class:`.Mapper`. + properties maintained by this :class:`_orm.Mapper`. .. seealso:: - :attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty` + :attr:`_orm.Mapper.attrs` - namespace of all + :class:`.MapperProperty` objects. """ @@ -2638,9 +2658,10 @@ class Mapper(sql_base.HasCacheKey, InspectionAttr): item from the identity map. :param row: A :class:`.Row` instance. The columns which are - mapped by this :class:`.Mapper` should be locatable in the row, - preferably via the :class:`.Column` object directly (as is the case - when a :func:`~.sql.expression.select` construct is executed), or + mapped by this :class:`_orm.Mapper` should be locatable in the row, + preferably via the :class:`_schema.Column` + object directly (as is the case + when a :func:`_expression.select` construct is executed), or via string names of the form ``<tablename>_<colname>``. """ @@ -3157,13 +3178,13 @@ def configure_mappers(): proceeds. * :meth:`.MapperEvents.mapper_configured` - called as each individual - :class:`.Mapper` is configured within the process; will include all + :class:`_orm.Mapper` is configured within the process; will include all mapper state except for backrefs set up by other mappers that are still to be configured. * :meth:`.MapperEvents.after_configured` - called once after :func:`.configure_mappers` is complete; at this stage, all - :class:`.Mapper` objects that are known to SQLAlchemy will be fully + :class:`_orm.Mapper` objects that are known to SQLAlchemy will be fully configured. Note that the calling application may still have other mappings that haven't been produced yet, such as if they are in modules as yet unimported. diff --git a/lib/sqlalchemy/orm/persistence.py b/lib/sqlalchemy/orm/persistence.py index 1460ae208..87bc8ea1d 100644 --- a/lib/sqlalchemy/orm/persistence.py +++ b/lib/sqlalchemy/orm/persistence.py @@ -6,7 +6,7 @@ # the MIT License: http://www.opensource.org/licenses/mit-license.php """private module containing functions used to emit INSERT, UPDATE -and DELETE statements on behalf of a :class:`.Mapper` and its descending +and DELETE statements on behalf of a :class:`_orm.Mapper` and its descending mappers. The functions here are called only by the unit of work functions @@ -1649,7 +1649,7 @@ def _sort_states(mapper, states): class BulkUD(object): - """Handle bulk update and deletes via a :class:`.Query`.""" + """Handle bulk update and deletes via a :class:`_query.Query`.""" def __init__(self, query): self.query = query.enable_eagerloads(False) diff --git a/lib/sqlalchemy/orm/properties.py b/lib/sqlalchemy/orm/properties.py index 05904d1a9..1022f4ef6 100644 --- a/lib/sqlalchemy/orm/properties.py +++ b/lib/sqlalchemy/orm/properties.py @@ -40,7 +40,7 @@ __all__ = [ class ColumnProperty(StrategizedProperty): """Describes an object attribute that corresponds to a table column. - Public constructor is the :func:`.orm.column_property` function. + Public constructor is the :func:`_orm.column_property` function. """ @@ -71,12 +71,13 @@ class ColumnProperty(StrategizedProperty): r"""Provide a column-level property for use with a mapping. Column-based properties can normally be applied to the mapper's - ``properties`` dictionary using the :class:`.Column` element directly. + ``properties`` dictionary using the :class:`_schema.Column` + element directly. Use this function when the given column is not directly present within the mapper's selectable; examples include SQL expressions, functions, and scalar SELECT queries. - The :func:`.orm.column_property` function returns an instance of + The :func:`_orm.column_property` function returns an instance of :class:`.ColumnProperty`. Columns that aren't present in the mapper's selectable won't be diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py index e131a4aa3..ce051cdcb 100644 --- a/lib/sqlalchemy/orm/query.py +++ b/lib/sqlalchemy/orm/query.py @@ -7,11 +7,11 @@ """The Query class and support. -Defines the :class:`.Query` class, the central +Defines the :class:`_query.Query` class, the central construct used by the ORM to construct database queries. -The :class:`.Query` class should not be confused with the -:class:`.Select` class, which defines database +The :class:`_query.Query` class should not be confused with the +:class:`_expression.Select` class, which defines database SELECT operations at the SQL (non-ORM) level. ``Query`` differs from ``Select`` in that it returns ORM-mapped objects and interacts with an ORM session, whereas the ``Select`` construct interacts directly with the @@ -70,20 +70,22 @@ _path_registry = PathRegistry.root class Query(Generative): """ORM-level SQL construction object. - :class:`.Query` is the source of all SELECT statements generated by the + :class:`_query.Query` + is the source of all SELECT statements generated by the ORM, both those formulated by end-user query operations as well as by high level internal operations such as related collection loading. It features a generative interface whereby successive calls return a new - :class:`.Query` object, a copy of the former with additional + :class:`_query.Query` object, a copy of the former with additional criteria and options associated with it. - :class:`.Query` objects are normally initially generated using the + :class:`_query.Query` objects are normally initially generated using the :meth:`~.Session.query` method of :class:`.Session`, and in - less common cases by instantiating the :class:`.Query` directly and - associating with a :class:`.Session` using the :meth:`.Query.with_session` + less common cases by instantiating the :class:`_query.Query` directly and + associating with a :class:`.Session` using the + :meth:`_query.Query.with_session` method. - For a full walkthrough of :class:`.Query` usage, see the + For a full walkthrough of :class:`_query.Query` usage, see the :ref:`ormtutorial_toplevel`. """ @@ -131,7 +133,8 @@ class Query(Generative): _bake_ok = True lazy_loaded_from = None - """An :class:`.InstanceState` that is using this :class:`.Query` for a + """An :class:`.InstanceState` that is using this :class:`_query.Query` + for a lazy load operation. The primary rationale for this attribute is to support the horizontal @@ -143,7 +146,8 @@ class Query(Generative): .. note:: - Within the realm of regular :class:`.Query` usage, this attribute is + Within the realm of regular :class:`_query.Query` usage, + this attribute is set by the lazy loader strategy before the query is invoked. However there is no established hook that is available to reliably intercept this value programmatically. It is set by the lazy loading strategy @@ -152,12 +156,14 @@ class Query(Generative): cache SQL compilation, the :meth:`.QueryEvents.before_compile` hook is also not reliable. - Currently, setting the :paramref:`.relationship.bake_queries` to - ``False`` on the target :func:`.relationship`, and then making use of + Currently, setting the :paramref:`_orm.relationship.bake_queries` to + ``False`` on the target :func:`_orm.relationship`, + and then making use of the :meth:`.QueryEvents.before_compile` event hook, is the only available programmatic path to intercepting this attribute. In future releases, there will be new hooks available that allow interception of - the :class:`.Query` before it is executed, rather than before it is + the :class:`_query.Query` before it is executed, + rather than before it is compiled. .. versionadded:: 1.2.9 @@ -165,7 +171,7 @@ class Query(Generative): """ def __init__(self, entities, session=None): - """Construct a :class:`.Query` directly. + """Construct a :class:`_query.Query` directly. E.g.:: @@ -177,16 +183,18 @@ class Query(Generative): :param entities: a sequence of entities and/or SQL expressions. - :param session: a :class:`.Session` with which the :class:`.Query` - will be associated. Optional; a :class:`.Query` can be associated + :param session: a :class:`.Session` with which the + :class:`_query.Query` + will be associated. Optional; a :class:`_query.Query` + can be associated with a :class:`.Session` generatively via the - :meth:`.Query.with_session` method as well. + :meth:`_query.Query.with_session` method as well. .. seealso:: :meth:`.Session.query` - :meth:`.Query.with_session` + :meth:`_query.Query.with_session` """ self.session = session @@ -535,21 +543,23 @@ class Query(Generative): def subquery(self, name=None, with_labels=False, reduce_columns=False): """return the full SELECT statement represented by - this :class:`.Query`, embedded within an :class:`.Alias`. + this :class:`_query.Query`, embedded within an + :class:`_expression.Alias`. Eager JOIN generation within the query is disabled. :param name: string name to be assigned as the alias; - this is passed through to :meth:`.FromClause.alias`. + this is passed through to :meth:`_expression.FromClause.alias`. If ``None``, a name will be deterministically generated at compile time. :param with_labels: if True, :meth:`.with_labels` will be called - on the :class:`.Query` first to apply table-qualified labels + on the :class:`_query.Query` first to apply table-qualified labels to all columns. - :param reduce_columns: if True, :meth:`.Select.reduce_columns` will - be called on the resulting :func:`~.sql.expression.select` construct, + :param reduce_columns: if True, + :meth:`_expression.Select.reduce_columns` will + be called on the resulting :func:`_expression.select` construct, to remove same-named columns where one also refers to the other via foreign key or WHERE clause equivalence. @@ -565,10 +575,10 @@ class Query(Generative): def cte(self, name=None, recursive=False): r"""Return the full SELECT statement represented by this - :class:`.Query` represented as a common table expression (CTE). + :class:`_query.Query` represented as a common table expression (CTE). Parameters and usage are the same as those of the - :meth:`.SelectBase.cte` method; see that method for + :meth:`_expression.SelectBase.cte` method; see that method for further details. Here is the `PostgreSQL WITH @@ -577,7 +587,7 @@ class Query(Generative): Note that, in this example, the ``included_parts`` cte and the ``incl_alias`` alias of it are Core selectables, which means the columns are accessed via the ``.c.`` attribute. The - ``parts_alias`` object is an :func:`.orm.aliased` instance of the + ``parts_alias`` object is an :func:`_orm.aliased` instance of the ``Part`` entity, so column-mapped attributes are available directly:: @@ -615,7 +625,7 @@ class Query(Generative): .. seealso:: - :meth:`.HasCTE.cte` + :meth:`_expression.HasCTE.cte` """ return self.enable_eagerloads(False).statement.cte( @@ -624,7 +634,7 @@ class Query(Generative): def label(self, name): """Return the full SELECT statement represented by this - :class:`.Query`, converted + :class:`_query.Query`, converted to a scalar subquery with a label of the given name. Analogous to :meth:`sqlalchemy.sql.expression.SelectBase.label`. @@ -635,26 +645,27 @@ class Query(Generative): @util.deprecated( "1.4", - "The :meth:`.Query.as_scalar` method is deprecated and will be " + "The :meth:`_query.Query.as_scalar` method is deprecated and will be " "removed in a future release. Please refer to " - ":meth:`.Query.scalar_subquery`.", + ":meth:`_query.Query.scalar_subquery`.", ) def as_scalar(self): """Return the full SELECT statement represented by this - :class:`.Query`, converted to a scalar subquery. + :class:`_query.Query`, converted to a scalar subquery. """ return self.scalar_subquery() def scalar_subquery(self): """Return the full SELECT statement represented by this - :class:`.Query`, converted to a scalar subquery. + :class:`_query.Query`, converted to a scalar subquery. Analogous to :meth:`sqlalchemy.sql.expression.SelectBase.scalar_subquery`. - .. versionchanged:: 1.4 the :meth:`.Query.scalar_subquery` method - replaces the :meth:`.Query.as_scalar` method. + .. versionchanged:: 1.4 the :meth:`_query.Query.scalar_subquery` + method + replaces the :meth:`_query.Query.as_scalar` method. """ return self.enable_eagerloads(False).statement.scalar_subquery() @@ -672,14 +683,15 @@ class Query(Generative): .. seealso:: - :meth:`.Query.is_single_entity` + :meth:`_query.Query.is_single_entity` """ self._only_return_tuples = value @property def is_single_entity(self): - """Indicates if this :class:`.Query` returns tuples or single entities. + """Indicates if this :class:`_query.Query` + returns tuples or single entities. Returns True if this query returns a single entity for each instance in its result list, and False if this query returns a tuple of entities @@ -689,7 +701,7 @@ class Query(Generative): .. seealso:: - :meth:`.Query.only_return_tuples` + :meth:`_query.Query.only_return_tuples` """ return ( @@ -711,7 +723,7 @@ class Query(Generative): This is used primarily when nesting the Query's statement into a subquery or other - selectable, or when using :meth:`.Query.yield_per`. + selectable, or when using :meth:`_query.Query.yield_per`. """ self._enable_eagerloads = value @@ -738,12 +750,14 @@ class Query(Generative): When the `Query` actually issues SQL to load rows, it always uses column labeling. - .. note:: The :meth:`.Query.with_labels` method *only* applies - the output of :attr:`.Query.statement`, and *not* to any of - the result-row invoking systems of :class:`.Query` itself, e.g. - :meth:`.Query.first`, :meth:`.Query.all`, etc. To execute - a query using :meth:`.Query.with_labels`, invoke the - :attr:`.Query.statement` using :meth:`.Session.execute`:: + .. note:: The :meth:`_query.Query.with_labels` method *only* applies + the output of :attr:`_query.Query.statement`, and *not* to any of + the result-row invoking systems of :class:`_query.Query` itself, e. + g. + :meth:`_query.Query.first`, :meth:`_query.Query.all`, etc. + To execute + a query using :meth:`_query.Query.with_labels`, invoke the + :attr:`_query.Query.statement` using :meth:`.Session.execute`:: result = session.execute(query.with_labels().statement) @@ -803,9 +817,9 @@ class Query(Generative): ): """Load columns for inheriting classes. - :meth:`.Query.with_polymorphic` applies transformations - to the "main" mapped class represented by this :class:`.Query`. - The "main" mapped class here means the :class:`.Query` + :meth:`_query.Query.with_polymorphic` applies transformations + to the "main" mapped class represented by this :class:`_query.Query`. + The "main" mapped class here means the :class:`_query.Query` object's first argument is a full class, i.e. ``session.query(SomeClass)``. These transformations allow additional tables to be present in the FROM clause so that columns for a @@ -849,7 +863,7 @@ class Query(Generative): (e.g. approximately 1000) is used, even with DBAPIs that buffer rows (which are most). - The :meth:`.Query.yield_per` method **is not compatible + The :meth:`_query.Query.yield_per` method **is not compatible subqueryload eager loading or joinedload eager loading when using collections**. It is potentially compatible with "select in" eager loading, **provided the database driver supports multiple, @@ -858,7 +872,7 @@ class Query(Generative): Therefore in some cases, it may be helpful to disable eager loads, either unconditionally with - :meth:`.Query.enable_eagerloads`:: + :meth:`_query.Query.enable_eagerloads`:: q = sess.query(Object).yield_per(100).enable_eagerloads(False) @@ -898,7 +912,7 @@ class Query(Generative): .. seealso:: - :meth:`.Query.enable_eagerloads` + :meth:`_query.Query.enable_eagerloads` """ self._yield_per = count @@ -919,7 +933,7 @@ class Query(Generative): some_object = session.query(VersionedFoo).get( {"id": 5, "version_id": 10}) - :meth:`~.Query.get` is special in that it provides direct + :meth:`_query.Query.get` is special in that it provides direct access to the identity map of the owning :class:`.Session`. If the given primary key identifier is present in the local identity map, the object is returned @@ -928,28 +942,28 @@ class Query(Generative): If not present, a SELECT is performed in order to locate the object. - :meth:`~.Query.get` also will perform a check if + :meth:`_query.Query.get` also will perform a check if the object is present in the identity map and marked as expired - a SELECT is emitted to refresh the object as well as to ensure that the row is still present. If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised. - :meth:`~.Query.get` is only used to return a single + :meth:`_query.Query.get` is only used to return a single mapped instance, not multiple instances or individual column constructs, and strictly on a single primary key value. The originating - :class:`.Query` must be constructed in this way, + :class:`_query.Query` must be constructed in this way, i.e. against a single mapped entity, with no additional filtering criterion. Loading - options via :meth:`~.Query.options` may be applied + options via :meth:`_query.Query.options` may be applied however, and will be used if the object is not yet locally present. A lazy-loading, many-to-one attribute configured - by :func:`.relationship`, using a simple + by :func:`_orm.relationship`, using a simple foreign-key-to-primary-key criterion, will also use an - operation equivalent to :meth:`~.Query.get` in order to retrieve + operation equivalent to :meth:`_query.Query.get` in order to retrieve the target value from the local identity map before querying the database. See :doc:`/orm/loading_relationships` for further details on relationship loading. @@ -965,9 +979,11 @@ class Query(Generative): my_object = query.get(5) The tuple form contains primary key values typically in - the order in which they correspond to the mapped :class:`.Table` + the order in which they correspond to the mapped + :class:`_schema.Table` object's primary key columns, or if the - :paramref:`.Mapper.primary_key` configuration parameter were used, in + :paramref:`_orm.Mapper.primary_key` configuration parameter were used + , in the order used for that parameter. For example, if the primary key of a row is represented by the integer digits "5, 10" the call would look like:: @@ -981,7 +997,8 @@ class Query(Generative): my_object = query.get({"id": 5, "version_id": 10}) - .. versionadded:: 1.3 the :meth:`.Query.get` method now optionally + .. versionadded:: 1.3 the :meth:`_query.Query.get` + method now optionally accepts a dictionary of attribute names to values in order to indicate a primary key identifier. @@ -1056,9 +1073,10 @@ class Query(Generative): @_generative def correlate(self, *args): - """Return a :class:`.Query` construct which will correlate the given - FROM clauses to that of an enclosing :class:`.Query` or - :func:`~.expression.select`. + """Return a :class:`_query.Query` + construct which will correlate the given + FROM clauses to that of an enclosing :class:`_query.Query` or + :func:`_expression.select`. The method here accepts mapped classes, :func:`.aliased` constructs, and :func:`.mapper` constructs as arguments, which are resolved into @@ -1066,12 +1084,13 @@ class Query(Generative): constructs. The correlation arguments are ultimately passed to - :meth:`.Select.correlate` after coercion to expression constructs. + :meth:`_expression.Select.correlate` + after coercion to expression constructs. The correlation arguments take effect in such cases - as when :meth:`.Query.from_self` is used, or when - a subquery as returned by :meth:`.Query.subquery` is - embedded in another :func:`~.expression.select` construct. + as when :meth:`_query.Query.from_self` is used, or when + a subquery as returned by :meth:`_query.Query.subquery` is + embedded in another :func:`_expression.select` construct. """ @@ -1099,7 +1118,8 @@ class Query(Generative): @_generative def populate_existing(self): - """Return a :class:`.Query` that will expire and refresh all instances + """Return a :class:`_query.Query` + that will expire and refresh all instances as they are loaded, or reused from the current :class:`.Session`. :meth:`.populate_existing` does not improve behavior when @@ -1117,7 +1137,7 @@ class Query(Generative): subquery loaders to traverse into already-loaded related objects and collections. - Default is that of :attr:`.Query._invoke_all_eagers`. + Default is that of :attr:`_query.Query._invoke_all_eagers`. """ self._invoke_all_eagers = value @@ -1126,18 +1146,19 @@ class Query(Generative): def with_parent(self, instance, property=None, from_entity=None): # noqa """Add filtering criterion that relates the given instance to a child object or collection, using its attribute state - as well as an established :func:`.relationship()` + as well as an established :func:`_orm.relationship()` configuration. The method uses the :func:`.with_parent` function to generate - the clause, the result of which is passed to :meth:`.Query.filter`. + the clause, the result of which is passed to + :meth:`_query.Query.filter`. Parameters are the same as :func:`.with_parent`, with the exception that the given property can be None, in which case a search is - performed against this :class:`.Query` object's target mapper. + performed against this :class:`_query.Query` object's target mapper. :param instance: - An instance which has some :func:`.relationship`. + An instance which has some :func:`_orm.relationship`. :param property: String property name, or class-bound attribute, which indicates @@ -1146,7 +1167,7 @@ class Query(Generative): :param from_entity: Entity in which to consider as the left side. This defaults to the - "zero" entity of the :class:`.Query` itself. + "zero" entity of the :class:`_query.Query` itself. """ relationships = util.preloaded.orm_relationships @@ -1191,13 +1212,18 @@ class Query(Generative): @_generative def with_session(self, session): - """Return a :class:`.Query` that will use the given :class:`.Session`. + """Return a :class:`_query.Query` that will use the given + :class:`.Session`. - While the :class:`.Query` object is normally instantiated using the - :meth:`.Session.query` method, it is legal to build the :class:`.Query` + While the :class:`_query.Query` + object is normally instantiated using the + :meth:`.Session.query` method, it is legal to build the + :class:`_query.Query` directly without necessarily using a :class:`.Session`. Such a - :class:`.Query` object, or any :class:`.Query` already associated - with a different :class:`.Session`, can produce a new :class:`.Query` + :class:`_query.Query` object, or any :class:`_query.Query` + already associated + with a different :class:`.Session`, can produce a new + :class:`_query.Query` object associated with a target session using this method:: from sqlalchemy.orm import Query @@ -1211,7 +1237,7 @@ class Query(Generative): self.session = session @util.deprecated_20( - ":meth:`.Query.from_self`", + ":meth:`_query.Query.from_self`", alternative="The new approach is to use the :func:`.orm.aliased` " "construct in conjunction with a subquery. See the section " ":ref:`Selecting from the query itself as a subquery " @@ -1222,12 +1248,12 @@ class Query(Generative): r"""return a Query that selects from this Query's SELECT statement. - :meth:`.Query.from_self` essentially turns the SELECT statement + :meth:`_query.Query.from_self` essentially turns the SELECT statement into a SELECT of itself. Given a query such as:: q = session.query(User).filter(User.name.like('e%')) - Given the :meth:`.Query.from_self` version:: + Given the :meth:`_query.Query.from_self` version:: q = session.query(User).filter(User.name.like('e%')).from_self() @@ -1241,7 +1267,8 @@ class Query(Generative): FROM "user" WHERE "user".name LIKE :name_1) AS anon_1 - There are lots of cases where :meth:`.Query.from_self` may be useful. + There are lots of cases where :meth:`_query.Query.from_self` + may be useful. A simple one is where above, we may want to apply a row LIMIT to the set of user objects we query against, and then apply additional joins against that row-limited set:: @@ -1266,7 +1293,8 @@ class Query(Generative): **Automatic Aliasing** - Another key behavior of :meth:`.Query.from_self` is that it applies + Another key behavior of :meth:`_query.Query.from_self` + is that it applies **automatic aliasing** to the entities inside the subquery, when they are referenced on the outside. Above, if we continue to refer to the ``User`` entity without any additional aliasing applied @@ -1295,13 +1323,15 @@ class Query(Generative): for simple filters and orderings. More ambitious constructions such as referring to the entity in joins should prefer to use explicit subquery objects, typically making use of the - :meth:`.Query.subquery` method to produce an explicit subquery object. + :meth:`_query.Query.subquery` + method to produce an explicit subquery object. Always test the structure of queries by viewing the SQL to ensure a particular structure does what's expected! **Changing the Entities** - :meth:`.Query.from_self` also includes the ability to modify what + :meth:`_query.Query.from_self` + also includes the ability to modify what columns are being queried. In our example, we want ``User.id`` to be queried by the inner query, so that we can join to the ``Address`` entity on the outside, but we only wanted the outer @@ -1340,8 +1370,9 @@ class Query(Generative): q = q.add_entity(User).from_self().\ options(contains_eager(Address.user)) - We use :meth:`.Query.add_entity` above **before** we call - :meth:`.Query.from_self` so that the ``User`` columns are present + We use :meth:`_query.Query.add_entity` above **before** we call + :meth:`_query.Query.from_self` + so that the ``User`` columns are present in the inner subquery, so that they are available to the :func:`.contains_eager` modifier we are using on the outside, producing: @@ -1457,7 +1488,8 @@ class Query(Generative): @_generative def with_entities(self, *entities): - r"""Return a new :class:`.Query` replacing the SELECT list with the + r"""Return a new :class:`_query.Query` + replacing the SELECT list with the given entities. e.g.:: @@ -1493,8 +1525,9 @@ class Query(Generative): @util.deprecated( "1.4", - ":meth:`.Query.add_column` is deprecated and will be removed in a " - "future release. Please use :meth:`.Query.add_columns`", + ":meth:`_query.Query.add_column` " + "is deprecated and will be removed in a " + "future release. Please use :meth:`_query.Query.add_columns`", ) def add_column(self, column): """Add a column expression to the list of result columns to be @@ -1504,7 +1537,8 @@ class Query(Generative): return self.add_columns(column) def options(self, *args): - """Return a new :class:`.Query` object, applying the given list of + """Return a new :class:`_query.Query` object, + applying the given list of mapper options. Most supplied options regard changing how column- and @@ -1539,7 +1573,7 @@ class Query(Generative): opt.process_query(self) def with_transformation(self, fn): - """Return a new :class:`.Query` object transformed by + """Return a new :class:`_query.Query` object transformed by the given function. E.g.:: @@ -1551,7 +1585,7 @@ class Query(Generative): q = q.with_transformation(filter_something(x==5)) - This allows ad-hoc recipes to be created for :class:`.Query` + This allows ad-hoc recipes to be created for :class:`_query.Query` objects. See the example at :ref:`hybrid_transformers`. """ @@ -1561,17 +1595,18 @@ class Query(Generative): def with_hint(self, selectable, text, dialect_name="*"): """Add an indexing or other executional context hint for the given entity or selectable to - this :class:`.Query`. + this :class:`_query.Query`. Functionality is passed straight through to :meth:`~sqlalchemy.sql.expression.Select.with_hint`, with the addition that ``selectable`` can be a - :class:`.Table`, :class:`.Alias`, or ORM entity / mapped class + :class:`_schema.Table`, :class:`_expression.Alias`, + or ORM entity / mapped class /etc. .. seealso:: - :meth:`.Query.with_statement_hint` + :meth:`_query.Query.with_statement_hint` :meth:.`.Query.prefix_with` - generic SELECT prefixing which also can suit some database-specific HINT syntaxes such as MySQL @@ -1584,19 +1619,21 @@ class Query(Generative): self._with_hints += ((selectable, text, dialect_name),) def with_statement_hint(self, text, dialect_name="*"): - """add a statement hint to this :class:`.Select`. + """add a statement hint to this :class:`_expression.Select`. - This method is similar to :meth:`.Select.with_hint` except that + This method is similar to :meth:`_expression.Select.with_hint` + except that it does not require an individual table, and instead applies to the statement as a whole. - This feature calls down into :meth:`.Select.with_statement_hint`. + This feature calls down into + :meth:`_expression.Select.with_statement_hint`. .. versionadded:: 1.0.0 .. seealso:: - :meth:`.Query.with_hint` + :meth:`_query.Query.with_hint` """ return self.with_hint(None, text, dialect_name) @@ -1608,7 +1645,7 @@ class Query(Generative): .. seealso:: - :meth:`.Query.execution_options` + :meth:`_query.Query.execution_options` """ return self._execution_options @@ -1617,7 +1654,7 @@ class Query(Generative): """ Set non-SQL options which take effect during execution. The options are the same as those accepted by - :meth:`.Connection.execution_options`. + :meth:`_engine.Connection.execution_options`. Note that the ``stream_results`` execution option is enabled automatically if the :meth:`~sqlalchemy.orm.query.Query.yield_per()` @@ -1625,7 +1662,7 @@ class Query(Generative): .. seealso:: - :meth:`.Query.get_execution_options` + :meth:`_query.Query.get_execution_options` """ self._execution_options = self._execution_options.union(kwargs) @@ -1639,11 +1676,13 @@ class Query(Generative): skip_locked=False, key_share=False, ): - """return a new :class:`.Query` with the specified options for the + """return a new :class:`_query.Query` + with the specified options for the ``FOR UPDATE`` clause. The behavior of this method is identical to that of - :meth:`.SelectBase.with_for_update`. When called with no arguments, + :meth:`_expression.SelectBase.with_for_update`. + When called with no arguments, the resulting ``SELECT`` statement will have a ``FOR UPDATE`` clause appended. When additional arguments are specified, backend-specific options such as ``FOR UPDATE NOWAIT`` or ``LOCK IN SHARE MODE`` @@ -1659,7 +1698,8 @@ class Query(Generative): .. seealso:: - :meth:`.GenerativeSelect.with_for_update` - Core level method with + :meth:`_expression.GenerativeSelect.with_for_update` + - Core level method with full argument and behavioral description. """ @@ -1696,7 +1736,7 @@ class Query(Generative): @_assertions(_no_statement_condition, _no_limit_offset) def filter(self, *criterion): r"""apply the given filtering criterion to a copy - of this :class:`.Query`, using SQL expressions. + of this :class:`_query.Query`, using SQL expressions. e.g.:: @@ -1711,11 +1751,12 @@ class Query(Generative): The criterion is any SQL expression object applicable to the WHERE clause of a select. String expressions are coerced - into SQL expression constructs via the :func:`.text` construct. + into SQL expression constructs via the :func:`_expression.text` + construct. .. seealso:: - :meth:`.Query.filter_by` - filter on keyword expressions. + :meth:`_query.Query.filter_by` - filter on keyword expressions. """ for criterion in list(criterion): @@ -1729,7 +1770,7 @@ class Query(Generative): def filter_by(self, **kwargs): r"""apply the given filtering criterion to a copy - of this :class:`.Query`, using keyword expressions. + of this :class:`_query.Query`, using keyword expressions. e.g.:: @@ -1744,11 +1785,11 @@ class Query(Generative): The keyword expressions are extracted from the primary entity of the query, or the last entity that was the - target of a call to :meth:`.Query.join`. + target of a call to :meth:`_query.Query.join`. .. seealso:: - :meth:`.Query.filter` - filter on SQL expressions. + :meth:`_query.Query.filter` - filter on SQL expressions. """ @@ -1788,7 +1829,7 @@ class Query(Generative): @_assertions(_no_statement_condition, _no_limit_offset) def group_by(self, *criterion): """apply one or more GROUP BY criterion to the query and return - the newly resulting :class:`.Query` + the newly resulting :class:`_query.Query` All existing GROUP BY settings can be suppressed by passing ``None`` - this will suppress any GROUP BY configured @@ -1816,10 +1857,10 @@ class Query(Generative): @_assertions(_no_statement_condition, _no_limit_offset) def having(self, criterion): r"""apply a HAVING criterion to the query and return the - newly resulting :class:`.Query`. + newly resulting :class:`_query.Query`. - :meth:`~.Query.having` is used in conjunction with - :meth:`~.Query.group_by`. + :meth:`_query.Query.having` is used in conjunction with + :meth:`_query.Query.group_by`. HAVING criterion makes it possible to use filters on aggregate functions like COUNT, SUM, AVG, MAX, and MIN, eg.:: @@ -1884,7 +1925,7 @@ class Query(Generative): be rendered on a query called within UNION, EXCEPT, etc. To disable all ORDER BY clauses including those configured on mappers, issue ``query.order_by(None)`` - the resulting - :class:`.Query` object will not render ORDER BY within + :class:`_query.Query` object will not render ORDER BY within its SELECT statement. """ @@ -1936,27 +1977,31 @@ class Query(Generative): return self._set_op(expression.except_all, *q) def join(self, *props, **kwargs): - r"""Create a SQL JOIN against this :class:`.Query` object's criterion - and apply generatively, returning the newly resulting :class:`.Query`. + r"""Create a SQL JOIN against this :class:`_query.Query` + object's criterion + and apply generatively, returning the newly resulting + :class:`_query.Query`. **Simple Relationship Joins** Consider a mapping between two classes ``User`` and ``Address``, with a relationship ``User.addresses`` representing a collection of ``Address`` objects associated with each ``User``. The most - common usage of :meth:`~.Query.join` is to create a JOIN along this + common usage of :meth:`_query.Query.join` + is to create a JOIN along this relationship, using the ``User.addresses`` attribute as an indicator for how this should occur:: q = session.query(User).join(User.addresses) - Where above, the call to :meth:`~.Query.join` along ``User.addresses`` + Where above, the call to :meth:`_query.Query.join` along ``User. + addresses`` will result in SQL equivalent to:: SELECT user.* FROM user JOIN address ON user.id = address.user_id In the above example we refer to ``User.addresses`` as passed to - :meth:`~.Query.join` as the *on clause*, that is, it indicates + :meth:`_query.Query.join` as the *on clause*, that is, it indicates how the "ON" portion of the JOIN should be constructed. For a single-entity query such as the one above (i.e. we start by selecting only from ``User`` and nothing else), the relationship can also be @@ -1964,14 +2009,15 @@ class Query(Generative): q = session.query(User).join("addresses") - :meth:`~.Query.join` can also accommodate multiple + :meth:`_query.Query.join` can also accommodate multiple "on clause" arguments to produce a chain of joins, such as below where a join across four related entities is constructed:: q = session.query(User).join("orders", "items", "keywords") The above would be shorthand for three separate calls to - :meth:`~.Query.join`, each using an explicit attribute to indicate + :meth:`_query.Query.join`, + each using an explicit attribute to indicate the source entity:: q = session.query(User).\ @@ -1981,20 +2027,21 @@ class Query(Generative): **Joins to a Target Entity or Selectable** - A second form of :meth:`~.Query.join` allows any mapped entity + A second form of :meth:`_query.Query.join` allows any mapped entity or core selectable construct as a target. In this usage, - :meth:`~.Query.join` will attempt + :meth:`_query.Query.join` will attempt to create a JOIN along the natural foreign key relationship between two entities:: q = session.query(User).join(Address) - The above calling form of :meth:`~.Query.join` will raise an error if + The above calling form of :meth:`_query.Query.join` + will raise an error if either there are no foreign keys between the two entities, or if there are multiple foreign key linkages between them. In the - above calling form, :meth:`~.Query.join` is called upon to + above calling form, :meth:`_query.Query.join` is called upon to create the "on clause" automatically for us. The target can - be any mapped entity or selectable, such as a :class:`.Table`:: + be any mapped entity or selectable, such as a :class:`_schema.Table`:: q = session.query(User).join(addresses_table) @@ -2025,7 +2072,7 @@ class Query(Generative): WHERE address.email_address = :email_address_1 AND address_1.email_address = :email_address_2 - The two-argument calling form of :meth:`~.Query.join` + The two-argument calling form of :meth:`_query.Query.join` also allows us to construct arbitrary joins with SQL-oriented "on clause" expressions, not relying upon configured relationships at all. Any SQL expression can be passed as the ON clause @@ -2037,9 +2084,10 @@ class Query(Generative): **Advanced Join Targeting and Adaption** There is a lot of flexibility in what the "target" can be when using - :meth:`~.Query.join`. As noted previously, it also accepts - :class:`.Table` constructs and other selectables such as :func:`.alias` - and :func:`~.sql.expression.select` constructs, with either the one or + :meth:`_query.Query.join`. As noted previously, it also accepts + :class:`_schema.Table` constructs and other selectables such as + :func:`.alias` + and :func:`_expression.select` constructs, with either the one or two-argument forms:: addresses_q = select([Address.user_id]).\ @@ -2049,7 +2097,7 @@ class Query(Generative): q = session.query(User).\ join(addresses_q, addresses_q.c.user_id==User.id) - :meth:`~.Query.join` also features the ability to *adapt* a + :meth:`_query.Query.join` also features the ability to *adapt* a :meth:`~sqlalchemy.orm.relationship` -driven ON clause to the target selectable. Below we construct a JOIN from ``User`` to a subquery against ``Address``, allowing the relationship denoted by @@ -2080,12 +2128,12 @@ class Query(Generative): **Controlling what to Join From** - While :meth:`~.Query.join` exclusively deals with the "right" + While :meth:`_query.Query.join` exclusively deals with the "right" side of the JOIN, we can also control the "left" side, in those - cases where it's needed, using :meth:`~.Query.select_from`. + cases where it's needed, using :meth:`_query.Query.select_from`. Below we construct a query against ``Address`` but can still make usage of ``User.addresses`` as our ON clause by instructing - the :class:`.Query` to select first from the ``User`` + the :class:`_query.Query` to select first from the ``User`` entity:: q = session.query(Address).select_from(User).\ @@ -2100,7 +2148,7 @@ class Query(Generative): **Constructing Aliases Anonymously** - :meth:`~.Query.join` can construct anonymous aliases + :meth:`_query.Query.join` can construct anonymous aliases using the ``aliased=True`` flag. This feature is useful when a query is being joined algorithmically, such as when querying self-referentially to an arbitrary depth:: @@ -2110,7 +2158,7 @@ class Query(Generative): When ``aliased=True`` is used, the actual "alias" construct is not explicitly available. To work with it, methods such as - :meth:`.Query.filter` will adapt the incoming entity to + :meth:`_query.Query.filter` will adapt the incoming entity to the last join point:: q = session.query(Node).\ @@ -2119,7 +2167,7 @@ class Query(Generative): When using automatic aliasing, the ``from_joinpoint=True`` argument can allow a multi-node join to be broken into - multiple calls to :meth:`~.Query.join`, so that + multiple calls to :meth:`_query.Query.join`, so that each path along the way can be further filtered:: q = session.query(Node).\ @@ -2129,7 +2177,7 @@ class Query(Generative): filter(Node.name == 'grandchild 1') The filtering aliases above can then be reset back to the - original ``Node`` entity using :meth:`~.Query.reset_joinpoint`:: + original ``Node`` entity using :meth:`_query.Query.reset_joinpoint`:: q = session.query(Node).\ join("children", "children", aliased=True).\ @@ -2148,13 +2196,14 @@ class Query(Generative): A special two-argument calling form of the form ``target, onclause`` is also accepted. :param aliased=False: If True, indicate that the JOIN target should be - anonymously aliased. Subsequent calls to :meth:`~.Query.filter` + anonymously aliased. Subsequent calls to :meth:`_query.Query.filter` and similar will adapt the incoming criterion to the target - alias, until :meth:`~.Query.reset_joinpoint` is called. + alias, until :meth:`_query.Query.reset_joinpoint` is called. :param isouter=False: If True, the join used will be a left outer join, - just as if the :meth:`.Query.outerjoin` method were called. This + just as if the :meth:`_query.Query.outerjoin` method were called. + This flag is here to maintain consistency with the same flag as accepted - by :meth:`.FromClause.join` and other Core constructs. + by :meth:`_expression.FromClause.join` and other Core constructs. .. versionadded:: 1.0.0 @@ -2173,10 +2222,10 @@ class Query(Generative): :ref:`ormtutorial_joins` in the ORM tutorial. :ref:`inheritance_toplevel` for details on how - :meth:`~.Query.join` is used for inheritance relationships. + :meth:`_query.Query.join` is used for inheritance relationships. - :func:`.orm.join` - a standalone ORM-level join function, - used internally by :meth:`.Query.join`, which in previous + :func:`_orm.join` - a standalone ORM-level join function, + used internally by :meth:`_query.Query.join`, which in previous SQLAlchemy versions was the primary ORM-level joining interface. """ @@ -2809,12 +2858,12 @@ class Query(Generative): @_generative @_assertions(_no_statement_condition) def reset_joinpoint(self): - """Return a new :class:`.Query`, where the "join point" has + """Return a new :class:`_query.Query`, where the "join point" has been reset back to the base FROM entities of the query. This method is usually used in conjunction with the - ``aliased=True`` feature of the :meth:`~.Query.join` - method. See the example in :meth:`~.Query.join` for how + ``aliased=True`` feature of the :meth:`_query.Query.join` + method. See the example in :meth:`_query.Query.join` for how this is used. """ @@ -2823,16 +2872,16 @@ class Query(Generative): @_generative @_assertions(_no_clauseelement_condition) def select_from(self, *from_obj): - r"""Set the FROM clause of this :class:`.Query` explicitly. + r"""Set the FROM clause of this :class:`_query.Query` explicitly. - :meth:`.Query.select_from` is often used in conjunction with - :meth:`.Query.join` in order to control which entity is selected + :meth:`_query.Query.select_from` is often used in conjunction with + :meth:`_query.Query.join` in order to control which entity is selected from on the "left" side of the join. The entity or selectable object here effectively replaces the - "left edge" of any calls to :meth:`~.Query.join`, when no + "left edge" of any calls to :meth:`_query.Query.join`, when no joinpoint is otherwise established - usually, the default "join - point" is the leftmost entity in the :class:`~.Query` object's + point" is the leftmost entity in the :class:`_query.Query` object's list of entities to be selected. A typical example:: @@ -2849,8 +2898,9 @@ class Query(Generative): :param \*from_obj: collection of one or more entities to apply to the FROM clause. Entities can be mapped classes, - :class:`.AliasedClass` objects, :class:`.Mapper` objects - as well as core :class:`.FromClause` elements like subqueries. + :class:`.AliasedClass` objects, :class:`_orm.Mapper` objects + as well as core :class:`_expression.FromClause` + elements like subqueries. .. versionchanged:: 0.9 This method no longer applies the given FROM object @@ -2861,9 +2911,9 @@ class Query(Generative): .. seealso:: - :meth:`~.Query.join` + :meth:`_query.Query.join` - :meth:`.Query.select_entity_from` + :meth:`_query.Query.select_entity_from` """ @@ -2872,15 +2922,16 @@ class Query(Generative): @_generative @_assertions(_no_clauseelement_condition) def select_entity_from(self, from_obj): - r"""Set the FROM clause of this :class:`.Query` to a + r"""Set the FROM clause of this :class:`_query.Query` to a core selectable, applying it as a replacement FROM clause for corresponding mapped entities. - The :meth:`.Query.select_entity_from` method supplies an alternative + The :meth:`_query.Query.select_entity_from` + method supplies an alternative approach to the use case of applying an :func:`.aliased` construct explicitly throughout a query. Instead of referring to the :func:`.aliased` construct explicitly, - :meth:`.Query.select_entity_from` automatically *adapts* all + :meth:`_query.Query.select_entity_from` automatically *adapts* all occurrences of the entity to the target selectable. Given a case for :func:`.aliased` such as selecting ``User`` @@ -2894,7 +2945,8 @@ class Query(Generative): Above, we apply the ``user_alias`` object explicitly throughout the query. When it's not feasible for ``user_alias`` to be referenced - explicitly in many places, :meth:`.Query.select_entity_from` may be + explicitly in many places, :meth:`_query.Query.select_entity_from` + may be used at the start of the query to adapt the existing ``User`` entity:: q = session.query(User).\ @@ -2912,11 +2964,12 @@ class Query(Generative): WHERE "user".id = :id_1) AS anon_1 WHERE anon_1.name = :name_1 - The :meth:`.Query.select_entity_from` method is similar to the - :meth:`.Query.select_from` method, in that it sets the FROM clause + The :meth:`_query.Query.select_entity_from` method is similar to the + :meth:`_query.Query.select_from` method, + in that it sets the FROM clause of the query. The difference is that it additionally applies adaptation to the other parts of the query that refer to the - primary entity. If above we had used :meth:`.Query.select_from` + primary entity. If above we had used :meth:`_query.Query.select_from` instead, the SQL generated would have been: .. sourcecode:: sql @@ -2928,24 +2981,30 @@ class Query(Generative): WHERE "user".id = :id_1) AS anon_1 WHERE "user".name = :name_1 - To supply textual SQL to the :meth:`.Query.select_entity_from` method, - we can make use of the :func:`.text` construct. However, the - :func:`.text` construct needs to be aligned with the columns of our + To supply textual SQL to the :meth:`_query.Query.select_entity_from` + method, + we can make use of the :func:`_expression.text` construct. However, + the + :func:`_expression.text` + construct needs to be aligned with the columns of our entity, which is achieved by making use of the - :meth:`.TextClause.columns` method:: + :meth:`_expression.TextClause.columns` method:: text_stmt = text("select id, name from user").columns( User.id, User.name).subquery() q = session.query(User).select_entity_from(text_stmt) - :meth:`.Query.select_entity_from` itself accepts an :func:`.aliased` + :meth:`_query.Query.select_entity_from` itself accepts an + :func:`.aliased` object, so that the special options of :func:`.aliased` such as :paramref:`.aliased.adapt_on_names` may be used within the - scope of the :meth:`.Query.select_entity_from` method's adaptation + scope of the :meth:`_query.Query.select_entity_from` + method's adaptation services. Suppose a view ``user_view`` also returns rows from ``user``. If - we reflect this view into a :class:`.Table`, this view has no - relationship to the :class:`.Table` to which we are mapped, however + we reflect this view into a :class:`_schema.Table`, this view has no + relationship to the :class:`_schema.Table` to which we are mapped, + however we can use name matching to select from it:: user_view = Table('user_view', metadata, @@ -2956,19 +3015,21 @@ class Query(Generative): select_entity_from(user_view_alias).\ order_by(User.name) - .. versionchanged:: 1.1.7 The :meth:`.Query.select_entity_from` + .. versionchanged:: 1.1.7 The :meth:`_query.Query.select_entity_from` method now accepts an :func:`.aliased` object as an alternative - to a :class:`.FromClause` object. + to a :class:`_expression.FromClause` object. - :param from_obj: a :class:`.FromClause` object that will replace - the FROM clause of this :class:`.Query`. It also may be an instance + :param from_obj: a :class:`_expression.FromClause` + object that will replace + the FROM clause of this :class:`_query.Query`. + It also may be an instance of :func:`.aliased`. .. seealso:: - :meth:`.Query.select_from` + :meth:`_query.Query.select_from` """ @@ -3006,8 +3067,8 @@ class Query(Generative): @_generative @_assertions(_no_statement_condition) def slice(self, start, stop): - """Computes the "slice" of the :class:`.Query` represented by - the given indices and returns the resulting :class:`.Query`. + """Computes the "slice" of the :class:`_query.Query` represented by + the given indices and returns the resulting :class:`_query.Query`. The start and stop indices behave like the argument to Python's built-in :func:`range` function. This method provides an @@ -3030,9 +3091,9 @@ class Query(Generative): .. seealso:: - :meth:`.Query.limit` + :meth:`_query.Query.limit` - :meth:`.Query.offset` + :meth:`_query.Query.offset` """ if start is not None and stop is not None: @@ -3082,9 +3143,10 @@ class Query(Generative): columns clause of the SELECT statement, to satisfy the common need of the database backend that ORDER BY columns be part of the SELECT list when DISTINCT is used. These columns *are not* added to the - list of columns actually fetched by the :class:`.Query`, however, + list of columns actually fetched by the :class:`_query.Query`, + however, so would not affect results. The columns are passed through when - using the :attr:`.Query.statement` accessor, however. + using the :attr:`_query.Query.statement` accessor, however. .. deprecated:: 2.0 This logic is deprecated and will be removed in SQLAlchemy 2.0. See :ref:`migration_20_query_distinct` @@ -3127,7 +3189,7 @@ class Query(Generative): .. seealso:: - :meth:`.HasPrefixes.prefix_with` + :meth:`_expression.HasPrefixes.prefix_with` """ if self._prefixes: @@ -3147,9 +3209,9 @@ class Query(Generative): .. seealso:: - :meth:`.Query.prefix_with` + :meth:`_query.Query.prefix_with` - :meth:`.HasSuffixes.suffix_with` + :meth:`_expression.HasSuffixes.suffix_with` """ if self._suffixes: @@ -3158,11 +3220,13 @@ class Query(Generative): self._suffixes = suffixes def all(self): - """Return the results represented by this :class:`.Query` as a list. + """Return the results represented by this :class:`_query.Query` + as a list. This results in an execution of the underlying SQL statement. - .. warning:: The :class:`.Query` object, when asked to return either + .. warning:: The :class:`_query.Query` object, + when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will **deduplicate entries based on primary key**. See the FAQ for more details. @@ -3181,10 +3245,11 @@ class Query(Generative): This method bypasses all internal statement compilation, and the statement is executed without modification. - The statement is typically either a :func:`~.expression.text` - or :func:`~.expression.select` construct, and should return the set + The statement is typically either a :func:`_expression.text` + or :func:`_expression.select` construct, and should return the set of columns - appropriate to the entity class represented by this :class:`.Query`. + appropriate to the entity class represented by this + :class:`_query.Query`. .. seealso:: @@ -3204,14 +3269,15 @@ class Query(Generative): (note this may consist of multiple result rows if join-loaded collections are present). - Calling :meth:`.Query.first` results in an execution of the underlying + Calling :meth:`_query.Query.first` + results in an execution of the underlying query. .. seealso:: - :meth:`.Query.one` + :meth:`_query.Query.one` - :meth:`.Query.one_or_none` + :meth:`_query.Query.one_or_none` """ if self._statement is not None: @@ -3232,18 +3298,19 @@ class Query(Generative): rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities. - Calling :meth:`.Query.one_or_none` results in an execution of the + Calling :meth:`_query.Query.one_or_none` + results in an execution of the underlying query. .. versionadded:: 1.0.9 - Added :meth:`.Query.one_or_none` + Added :meth:`_query.Query.one_or_none` .. seealso:: - :meth:`.Query.first` + :meth:`_query.Query.first` - :meth:`.Query.one` + :meth:`_query.Query.one` """ ret = list(self) @@ -3271,9 +3338,9 @@ class Query(Generative): .. seealso:: - :meth:`.Query.first` + :meth:`_query.Query.first` - :meth:`.Query.one_or_none` + :meth:`_query.Query.one_or_none` """ try: @@ -3365,7 +3432,7 @@ class Query(Generative): @property def column_descriptions(self): """Return metadata about the columns which would be - returned by this :class:`.Query`. + returned by this :class:`_query.Query`. Format is a list of dictionaries:: @@ -3435,7 +3502,7 @@ class Query(Generative): util.warn_deprecated( "Using the Query.instances() method without a context " "is deprecated and will be disallowed in a future release. " - "Please make use of :meth:`.Query.from_statement` " + "Please make use of :meth:`_query.Query.from_statement` " "for linking ORM results to arbitrary select constructs.", version="1.4", ) @@ -3444,9 +3511,10 @@ class Query(Generative): return loading.instances(self, result_proxy, context) def merge_result(self, iterator, load=True): - """Merge a result into this :class:`.Query` object's Session. + """Merge a result into this :class:`_query.Query` object's Session. - Given an iterator returned by a :class:`.Query` of the same structure + Given an iterator returned by a :class:`_query.Query` + of the same structure as this one, return an identical iterator of results, with all mapped instances merged into the session using :meth:`.Session.merge`. This is an optimized method which will merge all mapped instances, @@ -3455,14 +3523,15 @@ class Query(Generative): explicitly for each value. The structure of the results is determined based on the column list of - this :class:`.Query` - if these do not correspond, unchecked errors + this :class:`_query.Query` - if these do not correspond, + unchecked errors will occur. The 'load' argument is the same as that of :meth:`.Session.merge`. - For an example of how :meth:`~.Query.merge_result` is used, see + For an example of how :meth:`_query.Query.merge_result` is used, see the source code for the example :ref:`examples_caching`, where - :meth:`~.Query.merge_result` is used to efficiently restore state + :meth:`_query.Query.merge_result` is used to efficiently restore state from a cache back into a target :class:`.Session`. """ @@ -3544,7 +3613,8 @@ class Query(Generative): ) AS anon_1 The above SQL returns a single row, which is the aggregate value - of the count function; the :meth:`.Query.count` method then returns + of the count function; the :meth:`_query.Query.count` + method then returns that single integer value. .. warning:: @@ -3552,7 +3622,8 @@ class Query(Generative): It is important to note that the value returned by count() is **not the same as the number of ORM objects that this Query would return from a method such as the .all() method**. - The :class:`.Query` object, when asked to return full entities, + The :class:`_query.Query` object, + when asked to return full entities, will **deduplicate entries based on primary key**, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present. This does @@ -3602,7 +3673,8 @@ class Query(Generative): sess.query(User).filter(User.age == 25).\ delete(synchronize_session='evaluate') - .. warning:: The :meth:`.Query.delete` method is a "bulk" operation, + .. warning:: The :meth:`_query.Query.delete` + method is a "bulk" operation, which bypasses ORM unit-of-work automation in favor of greater performance. **Please read all caveats and warnings below.** @@ -3702,7 +3774,7 @@ class Query(Generative): .. seealso:: - :meth:`.Query.update` + :meth:`_query.Query.update` :ref:`inserts_and_updates` - Core SQL tutorial @@ -3726,7 +3798,8 @@ class Query(Generative): update({"age": User.age - 10}, synchronize_session='evaluate') - .. warning:: The :meth:`.Query.update` method is a "bulk" operation, + .. warning:: The :meth:`_query.Query.update` + method is a "bulk" operation, which bypasses ORM unit-of-work automation in favor of greater performance. **Please read all caveats and warnings below.** @@ -3768,7 +3841,8 @@ class Query(Generative): string collations between the database and Python. :param update_args: Optional dictionary, if present will be passed - to the underlying :func:`.update` construct as the ``**kw`` for + to the underlying :func:`_expression.update` + construct as the ``**kw`` for the object. May be used to pass dialect-specific arguments such as ``mysql_limit``, as well as other special arguments such as :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`. @@ -3834,7 +3908,7 @@ class Query(Generative): .. seealso:: - :meth:`.Query.delete` + :meth:`_query.Query.delete` :ref:`inserts_and_updates` - Core SQL tutorial @@ -4272,11 +4346,13 @@ class _MapperEntity(_QueryEntity): @inspection._self_inspects class Bundle(InspectionAttr): - """A grouping of SQL expressions that are returned by a :class:`.Query` + """A grouping of SQL expressions that are returned by a + :class:`_query.Query` under one namespace. The :class:`.Bundle` essentially allows nesting of the tuple-based - results returned by a column-oriented :class:`.Query` object. It also + results returned by a column-oriented :class:`_query.Query` object. + It also is extensible via simple subclassing, where the primary capability to override is that of how the set of expressions should be returned, allowing post-processing as well as custom return types, without @@ -4765,7 +4841,8 @@ class QueryContext(object): class AliasOption(interfaces.MapperOption): def __init__(self, alias): - r"""Return a :class:`.MapperOption` that will indicate to the :class:`.Query` + r"""Return a :class:`.MapperOption` that will indicate to the + :class:`_query.Query` that the main table has been aliased. This is a seldom-used option to suit the @@ -4793,7 +4870,7 @@ class AliasOption(interfaces.MapperOption): results = query.from_statement(statement).all() :param alias: is the string name of an alias, or a - :class:`~.sql.expression.Alias` object representing + :class:`_expression.Alias` object representing the alias. """ diff --git a/lib/sqlalchemy/orm/relationships.py b/lib/sqlalchemy/orm/relationships.py index c6f3bc30a..7d33c4649 100644 --- a/lib/sqlalchemy/orm/relationships.py +++ b/lib/sqlalchemy/orm/relationships.py @@ -6,11 +6,11 @@ # the MIT License: http://www.opensource.org/licenses/mit-license.php """Heuristics related to join conditions as used in -:func:`.relationship`. +:func:`_orm.relationship`. Provides the :class:`.JoinCondition` object, which encapsulates SQL annotation and aliasing behavior focused on the `primaryjoin` -and `secondaryjoin` aspects of :func:`.relationship`. +and `secondaryjoin` aspects of :func:`_orm.relationship`. """ from __future__ import absolute_import @@ -98,7 +98,7 @@ class RelationshipProperty(StrategizedProperty): """Describes an object property that holds a single item or list of items that correspond to a related database table. - Public constructor is the :func:`.orm.relationship` function. + Public constructor is the :func:`_orm.relationship` function. .. seealso:: @@ -160,15 +160,16 @@ class RelationshipProperty(StrategizedProperty): The constructed class is an instance of :class:`.RelationshipProperty`. - A typical :func:`.relationship`, used in a classical mapping:: + A typical :func:`_orm.relationship`, used in a classical mapping:: mapper(Parent, properties={ 'children': relationship(Child) }) - Some arguments accepted by :func:`.relationship` optionally accept a + Some arguments accepted by :func:`_orm.relationship` + optionally accept a callable function, which when called produces the desired value. - The callable is invoked by the parent :class:`.Mapper` at "mapper + The callable is invoked by the parent :class:`_orm.Mapper` at "mapper initialization" time, which happens only when mappers are first used, and is assumed to be after all mappings have been constructed. This can be used to resolve order-of-declaration and other dependency @@ -182,7 +183,7 @@ class RelationshipProperty(StrategizedProperty): When using the :ref:`declarative_toplevel` extension, the Declarative initializer allows string arguments to be passed to - :func:`.relationship`. These string arguments are converted into + :func:`_orm.relationship`. These string arguments are converted into callables that evaluate the string as Python code, using the Declarative class-registry as a namespace. This allows the lookup of related classes to be automatic via their string name, and removes the @@ -191,7 +192,8 @@ class RelationshipProperty(StrategizedProperty): that the modules in which these related classes appear are imported anywhere in the application at some point before the related mappings are actually used, else a lookup error will be raised when the - :func:`.relationship` attempts to resolve the string reference to the + :func:`_orm.relationship` + attempts to resolve the string reference to the related class. An example of a string- resolved class is as follows:: @@ -207,15 +209,17 @@ class RelationshipProperty(StrategizedProperty): .. seealso:: :ref:`relationship_config_toplevel` - Full introductory and - reference documentation for :func:`.relationship`. + reference documentation for :func:`_orm.relationship`. :ref:`orm_tutorial_relationship` - ORM tutorial introduction. :param argument: - a mapped class, or actual :class:`.Mapper` instance, representing + a mapped class, or actual :class:`_orm.Mapper` instance, + representing the target of the relationship. - :paramref:`~.relationship.argument` may also be passed as a callable + :paramref:`_orm.relationship.argument` + may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a string name when using Declarative. @@ -223,7 +227,7 @@ class RelationshipProperty(StrategizedProperty): using Python's ``eval()`` function. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. See :ref:`declarative_relationship_eval` for details on - declarative evaluation of :func:`.relationship` arguments. + declarative evaluation of :func:`_orm.relationship` arguments. .. versionchanged 1.3.16:: @@ -238,30 +242,35 @@ class RelationshipProperty(StrategizedProperty): :param secondary: for a many-to-many relationship, specifies the intermediary - table, and is typically an instance of :class:`.Table`. + table, and is typically an instance of :class:`_schema.Table`. In less common circumstances, the argument may also be specified - as an :class:`.Alias` construct, or even a :class:`.Join` construct. + as an :class:`_expression.Alias` construct, or even a + :class:`_expression.Join` construct. - :paramref:`~.relationship.secondary` may + :paramref:`_orm.relationship.secondary` may also be passed as a callable function which is evaluated at mapper initialization time. When using Declarative, it may also - be a string argument noting the name of a :class:`.Table` that is - present in the :class:`.MetaData` collection associated with the - parent-mapped :class:`.Table`. + be a string argument noting the name of a :class:`_schema.Table` + that is + present in the :class:`_schema.MetaData` + collection associated with the + parent-mapped :class:`_schema.Table`. .. warning:: When passed as a Python-evaluable string, the argument is interpreted using Python's ``eval()`` function. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. See :ref:`declarative_relationship_eval` for details on - declarative evaluation of :func:`.relationship` arguments. + declarative evaluation of :func:`_orm.relationship` arguments. - The :paramref:`~.relationship.secondary` keyword argument is - typically applied in the case where the intermediary :class:`.Table` + The :paramref:`_orm.relationship.secondary` keyword argument is + typically applied in the case where the intermediary + :class:`_schema.Table` is not otherwise expressed in any direct class mapping. If the "secondary" table is also explicitly mapped elsewhere (e.g. as in :ref:`association_pattern`), one should consider applying the - :paramref:`~.relationship.viewonly` flag so that this - :func:`.relationship` is not used for persistence operations which + :paramref:`_orm.relationship.viewonly` flag so that this + :func:`_orm.relationship` + is not used for persistence operations which may conflict with those of the association object pattern. .. seealso:: @@ -279,16 +288,19 @@ class RelationshipProperty(StrategizedProperty): Declarative. :ref:`association_pattern` - an alternative to - :paramref:`~.relationship.secondary` when composing association + :paramref:`_orm.relationship.secondary` + when composing association table relationships, allowing additional attributes to be specified on the association table. :ref:`composite_secondary_join` - a lesser-used pattern which - in some cases can enable complex :func:`.relationship` SQL + in some cases can enable complex :func:`_orm.relationship` SQL conditions to be used. - .. versionadded:: 0.9.2 :paramref:`~.relationship.secondary` works - more effectively when referring to a :class:`.Join` instance. + .. versionadded:: 0.9.2 :paramref:`_orm.relationship.secondary` + works + more effectively when referring to a :class:`_expression.Join` + instance. :param active_history=False: When ``True``, indicates that the "previous" value for a @@ -313,20 +325,20 @@ class RelationshipProperty(StrategizedProperty): :ref:`relationships_backref` - Introductory documentation and examples. - :paramref:`~.relationship.back_populates` - alternative form + :paramref:`_orm.relationship.back_populates` - alternative form of backref specification. - :func:`.backref` - allows control over :func:`.relationship` - configuration when using :paramref:`~.relationship.backref`. + :func:`.backref` - allows control over :func:`_orm.relationship` + configuration when using :paramref:`_orm.relationship.backref`. :param back_populates: Takes a string name and has the same meaning as - :paramref:`~.relationship.backref`, except the complementing + :paramref:`_orm.relationship.backref`, except the complementing property is **not** created automatically, and instead must be configured explicitly on the other mapper. The complementing property should also indicate - :paramref:`~.relationship.back_populates` to this relationship to + :paramref:`_orm.relationship.back_populates` to this relationship to ensure proper functioning. .. seealso:: @@ -334,7 +346,7 @@ class RelationshipProperty(StrategizedProperty): :ref:`relationships_backref` - Introductory documentation and examples. - :paramref:`~.relationship.backref` - alternative form + :paramref:`_orm.relationship.backref` - alternative form of backref specification. :param overlaps: @@ -397,7 +409,7 @@ class RelationshipProperty(StrategizedProperty): .. seealso:: :ref:`backref_cascade` - Full discussion and examples on how - the :paramref:`~.relationship.cascade_backrefs` option is used. + the :paramref:`_orm.relationship.cascade_backrefs` option is used. :param collection_class: a class or callable that returns a new list-holding object. will @@ -434,7 +446,7 @@ class RelationshipProperty(StrategizedProperty): duplicate innermost rows may be causing. .. versionchanged:: 0.9.0 - - :paramref:`~.relationship.distinct_target_key` now defaults to + :paramref:`_orm.relationship.distinct_target_key` now defaults to ``None``, so that the feature enables itself automatically for those cases where the innermost query targets a non-unique key. @@ -451,51 +463,55 @@ class RelationshipProperty(StrategizedProperty): a list of columns which are to be used as "foreign key" columns, or columns which refer to the value in a remote - column, within the context of this :func:`.relationship` - object's :paramref:`~.relationship.primaryjoin` condition. - That is, if the :paramref:`~.relationship.primaryjoin` - condition of this :func:`.relationship` is ``a.id == + column, within the context of this :func:`_orm.relationship` + object's :paramref:`_orm.relationship.primaryjoin` condition. + That is, if the :paramref:`_orm.relationship.primaryjoin` + condition of this :func:`_orm.relationship` is ``a.id == b.a_id``, and the values in ``b.a_id`` are required to be present in ``a.id``, then the "foreign key" column of this - :func:`.relationship` is ``b.a_id``. + :func:`_orm.relationship` is ``b.a_id``. - In normal cases, the :paramref:`~.relationship.foreign_keys` - parameter is **not required.** :func:`.relationship` will + In normal cases, the :paramref:`_orm.relationship.foreign_keys` + parameter is **not required.** :func:`_orm.relationship` will automatically determine which columns in the - :paramref:`~.relationship.primaryjoin` condition are to be + :paramref:`_orm.relationship.primaryjoin` condition are to be considered "foreign key" columns based on those - :class:`.Column` objects that specify :class:`.ForeignKey`, + :class:`_schema.Column` objects that specify + :class:`_schema.ForeignKey`, or are otherwise listed as referencing columns in a - :class:`.ForeignKeyConstraint` construct. - :paramref:`~.relationship.foreign_keys` is only needed when: + :class:`_schema.ForeignKeyConstraint` construct. + :paramref:`_orm.relationship.foreign_keys` is only needed when: 1. There is more than one way to construct a join from the local table to the remote table, as there are multiple foreign key references present. Setting ``foreign_keys`` will limit the - :func:`.relationship` to consider just those columns specified + :func:`_orm.relationship` + to consider just those columns specified here as "foreign". - 2. The :class:`.Table` being mapped does not actually have - :class:`.ForeignKey` or :class:`.ForeignKeyConstraint` + 2. The :class:`_schema.Table` being mapped does not actually have + :class:`_schema.ForeignKey` or + :class:`_schema.ForeignKeyConstraint` constructs present, often because the table was reflected from a database that does not support foreign key reflection (MySQL MyISAM). - 3. The :paramref:`~.relationship.primaryjoin` argument is used to + 3. The :paramref:`_orm.relationship.primaryjoin` + argument is used to construct a non-standard join condition, which makes use of columns or expressions that do not normally refer to their "parent" column, such as a join condition expressed by a complex comparison using a SQL function. - The :func:`.relationship` construct will raise informative + The :func:`_orm.relationship` construct will raise informative error messages that suggest the use of the - :paramref:`~.relationship.foreign_keys` parameter when + :paramref:`_orm.relationship.foreign_keys` parameter when presented with an ambiguous condition. In typical cases, - if :func:`.relationship` doesn't raise any exceptions, the - :paramref:`~.relationship.foreign_keys` parameter is usually + if :func:`_orm.relationship` doesn't raise any exceptions, the + :paramref:`_orm.relationship.foreign_keys` parameter is usually not needed. - :paramref:`~.relationship.foreign_keys` may also be passed as a + :paramref:`_orm.relationship.foreign_keys` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative. @@ -504,7 +520,7 @@ class RelationshipProperty(StrategizedProperty): argument is interpreted using Python's ``eval()`` function. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. See :ref:`declarative_relationship_eval` for details on - declarative evaluation of :func:`.relationship` arguments. + declarative evaluation of :func:`_orm.relationship` arguments. .. seealso:: @@ -513,7 +529,8 @@ class RelationshipProperty(StrategizedProperty): :ref:`relationship_custom_foreign` :func:`.foreign` - allows direct annotation of the "foreign" - columns within a :paramref:`~.relationship.primaryjoin` condition. + columns within a :paramref:`_orm.relationship.primaryjoin` + condition. :param info: Optional data dictionary which will be populated into the :attr:`.MapperProperty.info` attribute of this object. @@ -530,12 +547,12 @@ class RelationshipProperty(StrategizedProperty): is guaranteed to have one or at least one entry. The option supports the same "nested" and "unnested" options as - that of :paramref:`.joinedload.innerjoin`. See that flag + that of :paramref:`_orm.joinedload.innerjoin`. See that flag for details on nested / unnested behaviors. .. seealso:: - :paramref:`.joinedload.innerjoin` - the option as specified by + :paramref:`_orm.joinedload.innerjoin` - the option as specified by loader option, including detail on nesting behavior. :ref:`what_kind_of_loading` - Discussion of some details of @@ -572,7 +589,7 @@ class RelationshipProperty(StrategizedProperty): * ``joined`` - items should be loaded "eagerly" in the same query as that of the parent, using a JOIN or LEFT OUTER JOIN. Whether the join is "outer" or not is determined by the - :paramref:`~.relationship.innerjoin` parameter. + :paramref:`_orm.relationship.innerjoin` parameter. * ``subquery`` - items should be loaded "eagerly" as the parents are loaded, using one additional SQL statement, which issues a JOIN to @@ -611,7 +628,7 @@ class RelationshipProperty(StrategizedProperty): .. versionadded:: 1.1 * ``dynamic`` - the attribute will return a pre-configured - :class:`.Query` object for all read + :class:`_query.Query` object for all read operations, onto which further filtering operations can be applied before iterating the results. See the section :ref:`dynamic_relationship` for more details. @@ -641,7 +658,8 @@ class RelationshipProperty(StrategizedProperty): "attached" to a :class:`.Session` but is not part of its pending collection. - The :paramref:`~.relationship.load_on_pending` flag does not improve + The :paramref:`_orm.relationship.load_on_pending` + flag does not improve behavior when the ORM is used normally - object references should be constructed at the object level, not at the foreign key level, so that they are present in an ordinary way before a flush proceeds. @@ -656,12 +674,15 @@ class RelationshipProperty(StrategizedProperty): :param order_by: indicates the ordering that should be applied when loading these - items. :paramref:`~.relationship.order_by` is expected to refer to - one of the :class:`.Column` objects to which the target class is + items. :paramref:`_orm.relationship.order_by` + is expected to refer to + one of the :class:`_schema.Column` + objects to which the target class is mapped, or the attribute itself bound to the target class which refers to the column. - :paramref:`~.relationship.order_by` may also be passed as a callable + :paramref:`_orm.relationship.order_by` + may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative. @@ -669,7 +690,7 @@ class RelationshipProperty(StrategizedProperty): argument is interpreted using Python's ``eval()`` function. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. See :ref:`declarative_relationship_eval` for details on - declarative evaluation of :func:`.relationship` arguments. + declarative evaluation of :func:`_orm.relationship` arguments. :param passive_deletes=False: Indicates loading behavior during delete operations. @@ -706,7 +727,8 @@ class RelationshipProperty(StrategizedProperty): When True, it is assumed that ``ON UPDATE CASCADE`` is configured on the foreign key in the database, and that the database will handle propagation of an UPDATE from a source column to - dependent rows. When False, the SQLAlchemy :func:`.relationship` + dependent rows. When False, the SQLAlchemy + :func:`_orm.relationship` construct will attempt to emit its own UPDATE statements to modify related targets. However note that SQLAlchemy **cannot** emit an UPDATE for more than one level of cascade. Also, @@ -744,7 +766,7 @@ class RelationshipProperty(StrategizedProperty): list (i.e. both tables contain a foreign key to each other). If a flush operation returns an error that a "cyclical dependency" was detected, this is a cue that you might want to - use :paramref:`~.relationship.post_update` to "break" the cycle. + use :paramref:`_orm.relationship.post_update` to "break" the cycle. .. seealso:: @@ -758,7 +780,7 @@ class RelationshipProperty(StrategizedProperty): foreign key relationships of the parent and child tables (or association table). - :paramref:`~.relationship.primaryjoin` may also be passed as a + :paramref:`_orm.relationship.primaryjoin` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative. @@ -767,7 +789,7 @@ class RelationshipProperty(StrategizedProperty): argument is interpreted using Python's ``eval()`` function. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. See :ref:`declarative_relationship_eval` for details on - declarative evaluation of :func:`.relationship` arguments. + declarative evaluation of :func:`_orm.relationship` arguments. .. seealso:: @@ -777,7 +799,7 @@ class RelationshipProperty(StrategizedProperty): used for self-referential relationships, indicates the column or list of columns that form the "remote side" of the relationship. - :paramref:`.relationship.remote_side` may also be passed as a + :paramref:`_orm.relationship.remote_side` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative. @@ -786,24 +808,26 @@ class RelationshipProperty(StrategizedProperty): argument is interpreted using Python's ``eval()`` function. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. See :ref:`declarative_relationship_eval` for details on - declarative evaluation of :func:`.relationship` arguments. + declarative evaluation of :func:`_orm.relationship` arguments. .. seealso:: :ref:`self_referential` - in-depth explanation of how - :paramref:`~.relationship.remote_side` + :paramref:`_orm.relationship.remote_side` is used to configure self-referential relationships. :func:`.remote` - an annotation function that accomplishes the - same purpose as :paramref:`~.relationship.remote_side`, typically - when a custom :paramref:`~.relationship.primaryjoin` condition + same purpose as :paramref:`_orm.relationship.remote_side`, + typically + when a custom :paramref:`_orm.relationship.primaryjoin` condition is used. :param query_class: - a :class:`.Query` subclass that will be used as the base of the + a :class:`_query.Query` + subclass that will be used as the base of the "appender query" returned by a "dynamic" relationship, that is, a relationship that specifies ``lazy="dynamic"`` or was - otherwise constructed using the :func:`.orm.dynamic_loader` + otherwise constructed using the :func:`_orm.dynamic_loader` function. .. seealso:: @@ -817,7 +841,7 @@ class RelationshipProperty(StrategizedProperty): computed based on the foreign key relationships of the association and child tables. - :paramref:`~.relationship.secondaryjoin` may also be passed as a + :paramref:`_orm.relationship.secondaryjoin` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative. @@ -826,7 +850,7 @@ class RelationshipProperty(StrategizedProperty): argument is interpreted using Python's ``eval()`` function. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. See :ref:`declarative_relationship_eval` for details on - declarative evaluation of :func:`.relationship` arguments. + declarative evaluation of :func:`_orm.relationship` arguments. .. seealso:: @@ -837,31 +861,36 @@ class RelationshipProperty(StrategizedProperty): from being associated with more than one parent at a time. This is used for many-to-one or many-to-many relationships that should be treated either as one-to-one or one-to-many. Its usage - is optional, except for :func:`.relationship` constructs which + is optional, except for :func:`_orm.relationship` constructs which are many-to-one or many-to-many and also specify the ``delete-orphan`` cascade option. The - :func:`.relationship` construct itself will raise an error + :func:`_orm.relationship` construct itself will raise an error instructing when this option is required. .. seealso:: :ref:`unitofwork_cascades` - includes detail on when the - :paramref:`~.relationship.single_parent` flag may be appropriate. + :paramref:`_orm.relationship.single_parent` + flag may be appropriate. :param uselist: a boolean that indicates if this property should be loaded as a list or a scalar. In most cases, this value is determined - automatically by :func:`.relationship` at mapper configuration + automatically by :func:`_orm.relationship` at mapper configuration time, based on the type and direction of the relationship - one to many forms a list, many to one forms a scalar, many to many is a list. If a scalar is desired where normally a list would be present, such as a bi-directional - one-to-one relationship, set :paramref:`~.relationship.uselist` to + one-to-one relationship, set :paramref:`_orm.relationship.uselist` + to False. - The :paramref:`~.relationship.uselist` flag is also available on an - existing :func:`.relationship` construct as a read-only attribute, - which can be used to determine if this :func:`.relationship` deals + The :paramref:`_orm.relationship.uselist` + flag is also available on an + existing :func:`_orm.relationship` + construct as a read-only attribute, + which can be used to determine if this :func:`_orm.relationship` + deals with collections or scalar attributes:: >>> User.addresses.property.uselist @@ -871,18 +900,20 @@ class RelationshipProperty(StrategizedProperty): :ref:`relationships_one_to_one` - Introduction to the "one to one" relationship pattern, which is typically when the - :paramref:`~.relationship.uselist` flag is needed. + :paramref:`_orm.relationship.uselist` flag is needed. :param viewonly=False: when set to True, the relationship is used only for loading objects, - and not for any persistence operation. A :func:`.relationship` - which specifies :paramref:`~.relationship.viewonly` can work + and not for any persistence operation. A :func:`_orm.relationship` + which specifies :paramref:`_orm.relationship.viewonly` can work with a wider range of SQL operations within the - :paramref:`~.relationship.primaryjoin` condition, including + :paramref:`_orm.relationship.primaryjoin` condition, including operations that feature the use of a variety of comparison operators - as well as SQL functions such as :func:`~.sql.expression.cast`. The - :paramref:`~.relationship.viewonly` flag is also of general use when - defining any kind of :func:`~.relationship` that doesn't represent + as well as SQL functions such as :func:`_expression.cast`. The + :paramref:`_orm.relationship.viewonly` + flag is also of general use when + defining any kind of :func:`_orm.relationship` + that doesn't represent the full set of related objects, to prevent modifications of the collection from resulting in persistence operations. @@ -893,8 +924,8 @@ class RelationshipProperty(StrategizedProperty): be accessed via read. Towards this behavior, it is also not appropriate for the viewonly=True relationship to have any kind of persistence cascade settings, nor should it be the target of - either :paramref:`.relationship.backref` or - :paramref:`.relationship.back_populates`, as backrefs imply + either :paramref:`_orm.relationship.backref` or + :paramref:`_orm.relationship.back_populates`, as backrefs imply in-Python mutation of the attribute. SQLAlchemy may emit warnings for some or all of these conditions as of the 1.3 and 1.4 series of SQLAlchemy and will eventually be disallowed. @@ -1077,22 +1108,22 @@ class RelationshipProperty(StrategizedProperty): """The target entity referred to by this :class:`.RelationshipProperty.Comparator`. - This is either a :class:`.Mapper` or :class:`.AliasedInsp` + This is either a :class:`_orm.Mapper` or :class:`.AliasedInsp` object. This is the "target" or "remote" side of the - :func:`.relationship`. + :func:`_orm.relationship`. """ return self.property.entity @util.memoized_property def mapper(self): - """The target :class:`.Mapper` referred to by this + """The target :class:`_orm.Mapper` referred to by this :class:`.RelationshipProperty.Comparator`. This is the "target" or "remote" side of the - :func:`.relationship`. + :func:`_orm.relationship`. """ return self.property.mapper @@ -1147,7 +1178,7 @@ class RelationshipProperty(StrategizedProperty): def in_(self, other): """Produce an IN clause - this is not implemented - for :func:`~.orm.relationship`-based attributes at this time. + for :func:`_orm.relationship`-based attributes at this time. """ raise NotImplementedError( @@ -1337,7 +1368,7 @@ class RelationshipProperty(StrategizedProperty): related.my_id=my_table.id)) :meth:`~.RelationshipProperty.Comparator.any` is only - valid for collections, i.e. a :func:`.relationship` + valid for collections, i.e. a :func:`_orm.relationship` that has ``uselist=True``. For scalar references, use :meth:`~.RelationshipProperty.Comparator.has`. @@ -1373,7 +1404,7 @@ class RelationshipProperty(StrategizedProperty): using a join. :meth:`~.RelationshipProperty.Comparator.has` is only - valid for scalar references, i.e. a :func:`.relationship` + valid for scalar references, i.e. a :func:`_orm.relationship` that has ``uselist=False``. For collection references, use :meth:`~.RelationshipProperty.Comparator.any`. @@ -1390,7 +1421,7 @@ class RelationshipProperty(StrategizedProperty): :meth:`~.RelationshipProperty.Comparator.contains` is only valid for a collection, i.e. a - :func:`~.orm.relationship` that implements + :func:`_orm.relationship` that implements one-to-many or many-to-many with ``uselist=True``. When used in a simple one-to-many context, an @@ -1436,7 +1467,8 @@ class RelationshipProperty(StrategizedProperty): explicit "outer joins" will need to be used instead. See :meth:`~.RelationshipProperty.Comparator.any` for a less-performant alternative using EXISTS, or refer - to :meth:`.Query.outerjoin` as well as :ref:`ormtutorial_joins` + to :meth:`_query.Query.outerjoin` + as well as :ref:`ormtutorial_joins` for more details on constructing outer joins. """ @@ -1521,7 +1553,7 @@ class RelationshipProperty(StrategizedProperty): * Comparisons against collections are not supported. Use :meth:`~.RelationshipProperty.Comparator.contains` - in conjunction with :func:`~.expression.not_`. + in conjunction with :func:`_expression.not_`. * Compared to a scalar one-to-many, will produce a clause that compares the target columns in the parent to the given target. @@ -1533,7 +1565,7 @@ class RelationshipProperty(StrategizedProperty): comparisons, such as those which use OR. Use explicit joins, outerjoins, or :meth:`~.RelationshipProperty.Comparator.has` in - conjunction with :func:`~.expression.not_` for + conjunction with :func:`_expression.not_` for more comprehensive non-many-to-one scalar membership tests. * Comparisons against ``None`` given in a one-to-many @@ -1984,7 +2016,7 @@ class RelationshipProperty(StrategizedProperty): @util.memoized_property def mapper(self): - """Return the targeted :class:`.Mapper` for this + """Return the targeted :class:`_orm.Mapper` for this :class:`.RelationshipProperty`. This is a lazy-initializing static attribute. @@ -2210,7 +2242,7 @@ class RelationshipProperty(StrategizedProperty): def _generate_backref(self): """Interpret the 'backref' instruction to create a - :func:`.relationship` complementary to this one.""" + :func:`_orm.relationship` complementary to this one.""" if self.parent.non_primary: return diff --git a/lib/sqlalchemy/orm/scoping.py b/lib/sqlalchemy/orm/scoping.py index 0d1e2a965..1090501ca 100644 --- a/lib/sqlalchemy/orm/scoping.py +++ b/lib/sqlalchemy/orm/scoping.py @@ -27,7 +27,7 @@ class scoped_session(object): session_factory = None """The `session_factory` provided to `__init__` is stored in this attribute and may be accessed at a later time. This can be useful when - a new non-scoped :class:`.Session` or :class:`.Connection` to the + a new non-scoped :class:`.Session` or :class:`_engine.Connection` to the database is needed.""" def __init__(self, session_factory, scopefunc=None): @@ -112,7 +112,8 @@ class scoped_session(object): self.session_factory.configure(**kwargs) def query_property(self, query_cls=None): - """return a class property which produces a :class:`.Query` object + """return a class property which produces a :class:`_query.Query` + object against the class and the current :class:`.Session` when called. e.g.:: diff --git a/lib/sqlalchemy/orm/session.py b/lib/sqlalchemy/orm/session.py index 98fa819b1..61442756d 100644 --- a/lib/sqlalchemy/orm/session.py +++ b/lib/sqlalchemy/orm/session.py @@ -103,7 +103,7 @@ class SessionTransaction(object): :class:`.SessionTransaction` is a mostly behind-the-scenes object not normally referenced directly by application code. It coordinates - among multiple :class:`.Connection` objects, maintaining a database + among multiple :class:`_engine.Connection` objects, maintaining a database transaction for each one individually, committing or rolling them back all at once. It also provides optional two-phase commit behavior which can augment this coordination operation. @@ -127,8 +127,10 @@ class SessionTransaction(object): its default mode of ``autocommit=False`` whenever the "autobegin" process takes place, associated with no database connections. As the :class:`.Session` is called upon to emit SQL on behalf of various - :class:`.Engine` or :class:`.Connection` objects, a corresponding - :class:`.Connection` and associated :class:`.Transaction` is added to a + :class:`_engine.Engine` or :class:`_engine.Connection` objects, + a corresponding + :class:`_engine.Connection` and associated :class:`.Transaction` + is added to a collection within the :class:`.SessionTransaction` object, becoming one of the connection/transaction pairs maintained by the :class:`.SessionTransaction`. The start of a :class:`.SessionTransaction` @@ -698,22 +700,27 @@ class Session(_SessionClassMethods): :meth:`~.Session.flush` are rarely needed; you usually only need to call :meth:`~.Session.commit` (which flushes) to finalize changes. - :param bind: An optional :class:`.Engine` or :class:`.Connection` to + :param bind: An optional :class:`_engine.Engine` or + :class:`_engine.Connection` to which this ``Session`` should be bound. When specified, all SQL operations performed by this session will execute via this connectable. :param binds: A dictionary which may specify any number of - :class:`.Engine` or :class:`.Connection` objects as the source of + :class:`_engine.Engine` or :class:`_engine.Connection` + objects as the source of connectivity for SQL operations on a per-entity basis. The keys of the dictionary consist of any series of mapped classes, arbitrary Python classes that are bases for mapped classes, - :class:`.Table` objects and :class:`.Mapper` objects. The - values of the dictionary are then instances of :class:`.Engine` - or less commonly :class:`.Connection` objects. Operations which + :class:`_schema.Table` objects and :class:`_orm.Mapper` objects. + The + values of the dictionary are then instances of + :class:`_engine.Engine` + or less commonly :class:`_engine.Connection` objects. + Operations which proceed relative to a particular mapped class will consult this dictionary for the closest matching entity in order to determine - which :class:`.Engine` should be used for a particular SQL + which :class:`_engine.Engine` should be used for a particular SQL operation. The complete heuristics for resolution are described at :meth:`.Session.get_bind`. Usage looks like:: @@ -772,7 +779,7 @@ class Session(_SessionClassMethods): :param query_cls: Class which should be used to create new Query objects, as returned by the :meth:`~.Session.query` method. - Defaults to :class:`.Query`. + Defaults to :class:`_query.Query`. :param twophase: When ``True``, all transactions will be started as a "two phase" transaction, i.e. using the "two phase" semantics @@ -1023,27 +1030,28 @@ class Session(_SessionClassMethods): execution_options=None, **kw ): - r"""Return a :class:`.Connection` object corresponding to this + r"""Return a :class:`_engine.Connection` object corresponding to this :class:`.Session` object's transactional state. If this :class:`.Session` is configured with ``autocommit=False``, - either the :class:`.Connection` corresponding to the current + either the :class:`_engine.Connection` corresponding to the current transaction is returned, or if no transaction is in progress, a new - one is begun and the :class:`.Connection` returned (note that no + one is begun and the :class:`_engine.Connection` + returned (note that no transactional state is established with the DBAPI until the first SQL statement is emitted). Alternatively, if this :class:`.Session` is configured with - ``autocommit=True``, an ad-hoc :class:`.Connection` is returned - using :meth:`.Engine.connect` on the underlying - :class:`.Engine`. + ``autocommit=True``, an ad-hoc :class:`_engine.Connection` is returned + using :meth:`_engine.Engine.connect` on the underlying + :class:`_engine.Engine`. Ambiguity in multi-bind or unbound :class:`.Session` objects can be resolved through any of the optional keyword arguments. This ultimately makes usage of the :meth:`.get_bind` method for resolution. :param bind: - Optional :class:`.Engine` to be used as the bind. If + Optional :class:`_engine.Engine` to be used as the bind. If this engine is already involved in an ongoing transaction, that connection will be used. This argument takes precedence over ``mapper``, ``clause``. @@ -1054,20 +1062,21 @@ class Session(_SessionClassMethods): ``clause``. :param clause: - A :class:`.ClauseElement` (i.e. :func:`~.sql.expression.select`, - :func:`~.sql.expression.text`, + A :class:`_expression.ClauseElement` (i.e. + :func:`_expression.select`, + :func:`_expression.text`, etc.) which will be used to locate a bind, if a bind cannot otherwise be identified. - :param close_with_result: Passed to :meth:`.Engine.connect`, - indicating the :class:`.Connection` should be considered + :param close_with_result: Passed to :meth:`_engine.Engine.connect`, + indicating the :class:`_engine.Connection` should be considered "single use", automatically closing when the first result set is closed. This flag only has an effect if this :class:`.Session` is configured with ``autocommit=True`` and does not already have a transaction in progress. :param execution_options: a dictionary of execution options that will - be passed to :meth:`.Connection.execution_options`, **when the + be passed to :meth:`_engine.Connection.execution_options`, **when the connection is first procured only**. If the connection is already present within the :class:`.Session`, a warning is emitted and the arguments are ignored. @@ -1112,8 +1121,8 @@ class Session(_SessionClassMethods): Returns a :class:`.ResultProxy` representing results of the statement execution, in the same manner as that of an - :class:`.Engine` or - :class:`.Connection`. + :class:`_engine.Engine` or + :class:`_engine.Connection`. E.g.:: @@ -1122,14 +1131,14 @@ class Session(_SessionClassMethods): ) :meth:`~.Session.execute` accepts any executable clause construct, - such as :func:`~.sql.expression.select`, - :func:`~.sql.expression.insert`, - :func:`~.sql.expression.update`, - :func:`~.sql.expression.delete`, and - :func:`~.sql.expression.text`. Plain SQL strings can be passed + such as :func:`_expression.select`, + :func:`_expression.insert`, + :func:`_expression.update`, + :func:`_expression.delete`, and + :func:`_expression.text`. Plain SQL strings can be passed as well, which in the case of :meth:`.Session.execute` only will be interpreted the same as if it were passed via a - :func:`~.expression.text` construct. That is, the following usage:: + :func:`_expression.text` construct. That is, the following usage:: result = session.execute( "SELECT * FROM user WHERE id=:param", @@ -1146,7 +1155,7 @@ class Session(_SessionClassMethods): The second positional argument to :meth:`.Session.execute` is an optional parameter set. Similar to that of - :meth:`.Connection.execute`, whether this is passed as a single + :meth:`_engine.Connection.execute`, whether this is passed as a single dictionary, or a sequence of dictionaries, determines whether the DBAPI cursor's ``execute()`` or ``executemany()`` is used to execute the statement. An INSERT construct may be invoked for a single row:: @@ -1163,14 +1172,16 @@ class Session(_SessionClassMethods): ]) The statement is executed within the current transactional context of - this :class:`.Session`. The :class:`.Connection` which is used + this :class:`.Session`. The :class:`_engine.Connection` + which is used to execute the statement can also be acquired directly by calling the :meth:`.Session.connection` method. Both methods use a rule-based resolution scheme in order to determine the - :class:`.Connection`, which in the average case is derived directly + :class:`_engine.Connection`, + which in the average case is derived directly from the "bind" of the :class:`.Session` itself, and in other cases can be based on the :func:`.mapper` - and :class:`.Table` objects passed to the method; see the + and :class:`_schema.Table` objects passed to the method; see the documentation for :meth:`.Session.get_bind` for a full description of this scheme. @@ -1180,7 +1191,8 @@ class Session(_SessionClassMethods): method is returned with the "close_with_result" flag set to true; the significance of this flag is that if this :class:`.Session` is autocommitting and does not have a transaction-dedicated - :class:`.Connection` available, a temporary :class:`.Connection` is + :class:`_engine.Connection` available, a temporary + :class:`_engine.Connection` is established for the statement execution, which is closed (meaning, returned to the connection pool) when the :class:`.ResultProxy` has consumed all available data. This applies *only* when the @@ -1189,7 +1201,7 @@ class Session(_SessionClassMethods): :param clause: An executable statement (i.e. an :class:`.Executable` expression - such as :func:`.expression.select`) or string SQL statement + such as :func:`_expression.select`) or string SQL statement to be executed. :param params: @@ -1206,7 +1218,7 @@ class Session(_SessionClassMethods): for more details. :param bind: - Optional :class:`.Engine` to be used as the bind. If + Optional :class:`_engine.Engine` to be used as the bind. If this engine is already involved in an ongoing transaction, that connection will be used. This argument takes precedence over ``mapper`` and ``clause`` when locating @@ -1224,7 +1236,8 @@ class Session(_SessionClassMethods): :ref:`connections_toplevel` - Further information on direct statement execution. - :meth:`.Connection.execute` - core level statement execution + :meth:`_engine.Connection.execute` + - core level statement execution method, which is :meth:`.Session.execute` ultimately uses in order to execute the statement. @@ -1266,8 +1279,9 @@ class Session(_SessionClassMethods): """Close this Session, using connection invalidation. This is a variant of :meth:`.Session.close` that will additionally - ensure that the :meth:`.Connection.invalidate` method will be called - on all :class:`.Connection` objects. This can be called when + ensure that the :meth:`_engine.Connection.invalidate` + method will be called + on all :class:`_engine.Connection` objects. This can be called when the database is known to be in a state where the connections are no longer safe to be used. @@ -1342,17 +1356,20 @@ class Session(_SessionClassMethods): ) def bind_mapper(self, mapper, bind): - """Associate a :class:`.Mapper` or arbitrary Python class with a - "bind", e.g. an :class:`.Engine` or :class:`.Connection`. + """Associate a :class:`_orm.Mapper` or arbitrary Python class with a + "bind", e.g. an :class:`_engine.Engine` or :class:`_engine.Connection` + . The given entity is added to a lookup used by the :meth:`.Session.get_bind` method. - :param mapper: a :class:`.Mapper` object, or an instance of a mapped + :param mapper: a :class:`_orm.Mapper` object, + or an instance of a mapped class, or any Python class that is the base of a set of mapped classes. - :param bind: an :class:`.Engine` or :class:`.Connection` object. + :param bind: an :class:`_engine.Engine` or :class:`_engine.Connection` + object. .. seealso:: @@ -1367,17 +1384,20 @@ class Session(_SessionClassMethods): self._add_bind(mapper, bind) def bind_table(self, table, bind): - """Associate a :class:`.Table` with a "bind", e.g. an :class:`.Engine` - or :class:`.Connection`. + """Associate a :class:`_schema.Table` with a "bind", e.g. an + :class:`_engine.Engine` + or :class:`_engine.Connection`. - The given :class:`.Table` is added to a lookup used by the + The given :class:`_schema.Table` is added to a lookup used by the :meth:`.Session.get_bind` method. - :param table: a :class:`.Table` object, which is typically the target + :param table: a :class:`_schema.Table` object, + which is typically the target of an ORM mapping, or is present within a selectable that is mapped. - :param bind: an :class:`.Engine` or :class:`.Connection` object. + :param bind: an :class:`_engine.Engine` or :class:`_engine.Connection` + object. .. seealso:: @@ -1394,9 +1414,9 @@ class Session(_SessionClassMethods): def get_bind(self, mapper=None, clause=None): """Return a "bind" to which this :class:`.Session` is bound. - The "bind" is usually an instance of :class:`.Engine`, + The "bind" is usually an instance of :class:`_engine.Engine`, except in the case where the :class:`.Session` has been - explicitly bound directly to a :class:`.Connection`. + explicitly bound directly to a :class:`_engine.Connection`. For a multiply-bound or unbound :class:`.Session`, the ``mapper`` or ``clause`` arguments are used to determine the @@ -1416,15 +1436,15 @@ class Session(_SessionClassMethods): present in the ``__mro__`` of the mapped class, from more specific superclasses to more general. 2. if clause given and session.binds is present, - locate a bind based on :class:`.Table` objects + locate a bind based on :class:`_schema.Table` objects found in the given clause present in session.binds. 3. if session.bind is present, return that. 4. if clause given, attempt to return a bind - linked to the :class:`.MetaData` ultimately + linked to the :class:`_schema.MetaData` ultimately associated with the clause. 5. if mapper given, attempt to return a bind - linked to the :class:`.MetaData` ultimately - associated with the :class:`.Table` or other + linked to the :class:`_schema.MetaData` ultimately + associated with the :class:`_schema.Table` or other selectable to which the mapper is mapped. 6. No bind can be found, :exc:`~sqlalchemy.exc.UnboundExecutionError` is raised. @@ -1436,19 +1456,24 @@ class Session(_SessionClassMethods): :param mapper: Optional :func:`.mapper` mapped class or instance of - :class:`.Mapper`. The bind can be derived from a :class:`.Mapper` + :class:`_orm.Mapper`. The bind can be derived from a + :class:`_orm.Mapper` first by consulting the "binds" map associated with this - :class:`.Session`, and secondly by consulting the :class:`.MetaData` - associated with the :class:`.Table` to which the :class:`.Mapper` + :class:`.Session`, and secondly by consulting the + :class:`_schema.MetaData` + associated with the :class:`_schema.Table` to which the + :class:`_orm.Mapper` is mapped for a bind. :param clause: - A :class:`.ClauseElement` (i.e. :func:`~.sql.expression.select`, - :func:`~.sql.expression.text`, + A :class:`_expression.ClauseElement` (i.e. + :func:`_expression.select`, + :func:`_expression.text`, etc.). If the ``mapper`` argument is not present or could not produce a bind, the given expression construct will be searched - for a bound element, typically a :class:`.Table` associated with - bound :class:`.MetaData`. + for a bound element, typically a :class:`_schema.Table` + associated with + bound :class:`_schema.MetaData`. .. seealso:: @@ -1517,7 +1542,7 @@ class Session(_SessionClassMethods): ) def query(self, *entities, **kwargs): - """Return a new :class:`.Query` object corresponding to this + """Return a new :class:`_query.Query` object corresponding to this :class:`.Session`.""" return self._query_cls(entities, self, **kwargs) @@ -1564,9 +1589,9 @@ class Session(_SessionClassMethods): PASSIVE_NO_RESULT. In all other cases the instance is returned. .. versionchanged:: 1.4.0 - the :meth:`.Session._identity_lookup` - method was moved from :class:`.Query` to + method was moved from :class:`_query.Query` to :class:`.Session`, to avoid having to instantiate the - :class:`.Query` object. + :class:`_query.Query` object. """ @@ -1647,7 +1672,8 @@ class Session(_SessionClassMethods): :param with_for_update: optional boolean ``True`` indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT; - flags should match the parameters of :meth:`.Query.with_for_update`. + flags should match the parameters of + :meth:`_query.Query.with_for_update`. Supersedes the :paramref:`.Session.refresh.lockmode` parameter. .. versionadded:: 1.2 @@ -2342,7 +2368,7 @@ class Session(_SessionClassMethods): :meth:`.enable_relationship_loading` exists to serve special use cases and is not recommended for general use. - Accesses of attributes mapped with :func:`.relationship` + Accesses of attributes mapped with :func:`_orm.relationship` will attempt to load a value from the database using this :class:`.Session` as the source of connectivity. The values will be loaded based on foreign key and primary key values @@ -2360,7 +2386,7 @@ class Session(_SessionClassMethods): is what was already loaded from a foreign-key-holding value. The :meth:`.Session.enable_relationship_loading` method is - similar to the ``load_on_pending`` flag on :func:`.relationship`. + similar to the ``load_on_pending`` flag on :func:`_orm.relationship`. Unlike that flag, :meth:`.Session.enable_relationship_loading` allows an object to remain transient while still being able to load related items. @@ -2379,7 +2405,7 @@ class Session(_SessionClassMethods): .. seealso:: - ``load_on_pending`` at :func:`.relationship` - this flag + ``load_on_pending`` at :func:`_orm.relationship` - this flag allows per-relationship loading of many-to-ones on items that are pending. @@ -2743,7 +2769,8 @@ class Session(_SessionClassMethods): large numbers of simple rows. The values within the dictionaries as given are typically passed - without modification into Core :meth:`.Insert` constructs, after + without modification into Core :meth:`_expression.Insert` constructs, + after organizing the values within them across the tables to which the given mapper is mapped. @@ -2761,7 +2788,8 @@ class Session(_SessionClassMethods): **before using this method, and fully test and confirm the functionality of all code developed using these systems.** - :param mapper: a mapped class, or the actual :class:`.Mapper` object, + :param mapper: a mapped class, or the actual :class:`_orm.Mapper` + object, representing the single kind of object represented within the mapping list. @@ -2852,7 +2880,8 @@ class Session(_SessionClassMethods): **before using this method, and fully test and confirm the functionality of all code developed using these systems.** - :param mapper: a mapped class, or the actual :class:`.Mapper` object, + :param mapper: a mapped class, or the actual :class:`_orm.Mapper` + object, representing the single kind of object represented within the mapping list. @@ -3014,7 +3043,7 @@ class Session(_SessionClassMethods): :class:`.Session` has actually begun to use DBAPI resources is to implement a listener using the :meth:`.SessionEvents.after_begin` method, which will deliver both the :class:`.Session` as well as the - target :class:`.Connection` to a user-defined event listener. + target :class:`_engine.Connection` to a user-defined event listener. The "partial rollback" state refers to when an "inner" transaction, typically used during a flush, encounters an error and emits a @@ -3147,7 +3176,8 @@ class sessionmaker(_SessionClassMethods): The class also includes a method :meth:`.configure`, which can be used to specify additional keyword arguments to the factory, which will take effect for subsequent :class:`.Session` objects generated. - This is usually used to associate one or more :class:`.Engine` objects + This is usually used to associate one or more :class:`_engine.Engine` + objects with an existing :class:`.sessionmaker` factory before it is first used:: @@ -3183,7 +3213,8 @@ class sessionmaker(_SessionClassMethods): accepted by :class:`.Session` directly. See the :meth:`.Session.__init__` docstring for more details on parameters. - :param bind: a :class:`.Engine` or other :class:`.Connectable` with + :param bind: a :class:`_engine.Engine` or other :class:`.Connectable` + with which newly created :class:`.Session` objects will be associated. :param class\_: class to use in order to create new :class:`.Session` objects. Defaults to :class:`.Session`. diff --git a/lib/sqlalchemy/orm/state.py b/lib/sqlalchemy/orm/state.py index 5a885b118..48546f24e 100644 --- a/lib/sqlalchemy/orm/state.py +++ b/lib/sqlalchemy/orm/state.py @@ -47,7 +47,7 @@ class InstanceState(interfaces.InspectionAttrInfo): status within a particular :class:`.Session` and details about data on individual attributes. The public API in order to acquire a :class:`.InstanceState` object - is to use the :func:`.inspect` system:: + is to use the :func:`_sa.inspect` system:: >>> from sqlalchemy import inspect >>> insp = inspect(some_mapped_object) @@ -273,7 +273,7 @@ class InstanceState(interfaces.InspectionAttrInfo): """Return the mapped identity of the mapped object. This is the primary key identity as persisted by the ORM which can always be passed directly to - :meth:`.Query.get`. + :meth:`_query.Query.get`. Returns ``None`` if the object has no primary key identity. @@ -316,7 +316,7 @@ class InstanceState(interfaces.InspectionAttrInfo): @util.memoized_property def mapper(self): - """Return the :class:`.Mapper` used for this mapped object.""" + """Return the :class:`_orm.Mapper` used for this mapped object.""" return self.manager.mapper @property @@ -894,7 +894,8 @@ class AttributeState(object): The attribute history system tracks changes on a **per flush basis**. Each time the :class:`.Session` is flushed, the history of each attribute is reset to empty. The :class:`.Session` by - default autoflushes each time a :class:`.Query` is invoked. For + default autoflushes each time a :class:`_query.Query` is invoked. + For options on how to control this, see :ref:`session_flushing`. @@ -920,7 +921,8 @@ class AttributeState(object): The attribute history system tracks changes on a **per flush basis**. Each time the :class:`.Session` is flushed, the history of each attribute is reset to empty. The :class:`.Session` by - default autoflushes each time a :class:`.Query` is invoked. For + default autoflushes each time a :class:`_query.Query` is invoked. + For options on how to control this, see :ref:`session_flushing`. .. seealso:: diff --git a/lib/sqlalchemy/orm/strategies.py b/lib/sqlalchemy/orm/strategies.py index bb08d31ea..2e9b2f316 100644 --- a/lib/sqlalchemy/orm/strategies.py +++ b/lib/sqlalchemy/orm/strategies.py @@ -1374,7 +1374,7 @@ class SubqueryLoader(PostLoader): return q class _SubqCollections(object): - """Given a :class:`.Query` used to emit the "subquery load", + """Given a :class:`_query.Query` used to emit the "subquery load", provide a load interface that executes the query at the first moment a value is needed. diff --git a/lib/sqlalchemy/orm/strategy_options.py b/lib/sqlalchemy/orm/strategy_options.py index 6475f79de..2fd628d0b 100644 --- a/lib/sqlalchemy/orm/strategy_options.py +++ b/lib/sqlalchemy/orm/strategy_options.py @@ -34,26 +34,29 @@ from ..sql.traversals import HasCacheKey class Load(HasCacheKey, Generative, MapperOption): """Represents loader options which modify the state of a - :class:`.Query` in order to affect how various mapped attributes are + :class:`_query.Query` in order to affect how various mapped attributes are loaded. - The :class:`.Load` object is in most cases used implicitly behind the - scenes when one makes use of a query option like :func:`.joinedload`, - :func:`.defer`, or similar. However, the :class:`.Load` object + The :class:`_orm.Load` object is in most cases used implicitly behind the + scenes when one makes use of a query option like :func:`_orm.joinedload`, + :func:`.defer`, or similar. However, the :class:`_orm.Load` object can also be used directly, and in some cases can be useful. - To use :class:`.Load` directly, instantiate it with the target mapped + To use :class:`_orm.Load` directly, instantiate it with the target mapped class as the argument. This style of usage is - useful when dealing with a :class:`.Query` that has multiple entities:: + useful when dealing with a :class:`_query.Query` + that has multiple entities:: myopt = Load(MyClass).joinedload("widgets") - The above ``myopt`` can now be used with :meth:`.Query.options`, where it + The above ``myopt`` can now be used with :meth:`_query.Query.options`, + where it will only take effect for the ``MyClass`` entity:: session.query(MyClass, MyOtherClass).options(myopt) - One case where :class:`.Load` is useful as public API is when specifying + One case where :class:`_orm.Load` + is useful as public API is when specifying "wildcard" options that only take effect for a certain class:: session.query(Order).options(Load(Order).lazyload('*')) @@ -363,7 +366,8 @@ class Load(HasCacheKey, Generative, MapperOption): @_generative def options(self, *opts): - r"""Apply a series of options as sub-options to this :class:`.Load` + r"""Apply a series of options as sub-options to this + :class:`_orm.Load` object. E.g.:: @@ -379,8 +383,8 @@ class Load(HasCacheKey, Generative, MapperOption): ) :param \*opts: A series of loader option objects (ultimately - :class:`.Load` objects) which should be applied to the path - specified by this :class:`.Load` object. + :class:`_orm.Load` objects) which should be applied to the path + specified by this :class:`_orm.Load` object. .. versionadded:: 1.3.6 @@ -555,8 +559,8 @@ class Load(HasCacheKey, Generative, MapperOption): class _UnboundLoad(Load): """Represent a loader option that isn't tied to a root entity. - The loader option will produce an entity-linked :class:`.Load` - object when it is passed :meth:`.Query.options`. + The loader option will produce an entity-linked :class:`_orm.Load` + object when it is passed :meth:`_query.Query.options`. This provides compatibility with the traditional system of freestanding options, e.g. ``joinedload('x.y.z')``. @@ -981,7 +985,7 @@ class loader_option(object): def _add_unbound_fn(self, fn): self._unbound_fn = fn fn_doc = self.fn.__doc__ - self.fn.__doc__ = """Produce a new :class:`.Load` object with the + self.fn.__doc__ = """Produce a new :class:`_orm.Load` object with the :func:`_orm.%(name)s` option applied. See :func:`_orm.%(name)s` for usage examples. @@ -1029,7 +1033,7 @@ def contains_eager(loadopt, attr, alias=None): r"""Indicate that the given attribute should be eagerly loaded from columns stated manually in the query. - This function is part of the :class:`.Load` interface and supports + This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. The option is used in conjunction with an explicit join that loads @@ -1123,7 +1127,7 @@ def load_only(loadopt, *attrs): of column-based attribute names should be loaded; all others will be deferred. - This function is part of the :class:`.Load` interface and supports + This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. Example - given a class ``User``, load only the ``name`` and ``fullname`` @@ -1139,8 +1143,9 @@ def load_only(loadopt, *attrs): subqueryload("addresses").load_only("email_address") ) - For a :class:`.Query` that has multiple entities, the lead entity can be - specifically referred to using the :class:`.Load` constructor:: + For a :class:`_query.Query` that has multiple entities, + the lead entity can be + specifically referred to using the :class:`_orm.Load` constructor:: session.query(User, Address).join(User.addresses).options( Load(User).load_only("name", "fullname"), @@ -1170,7 +1175,7 @@ def joinedload(loadopt, attr, innerjoin=None): """Indicate that the given attribute should be loaded using joined eager loading. - This function is part of the :class:`.Load` interface and supports + This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. examples:: @@ -1221,7 +1226,7 @@ def joinedload(loadopt, attr, innerjoin=None): .. note:: The "unnested" flag does **not** affect the JOIN rendered from a many-to-many association table, e.g. a table configured - as :paramref:`.relationship.secondary`, to the target table; for + as :paramref:`_orm.relationship.secondary`, to the target table; for correctness of results, these joins are always INNER and are therefore right-nested if linked to an OUTER join. @@ -1233,15 +1238,17 @@ def joinedload(loadopt, attr, innerjoin=None): .. note:: - The joins produced by :func:`.orm.joinedload` are **anonymously + The joins produced by :func:`_orm.joinedload` are **anonymously aliased**. The criteria by which the join proceeds cannot be - modified, nor can the :class:`.Query` refer to these joins in any way, + modified, nor can the :class:`_query.Query` + refer to these joins in any way, including ordering. See :ref:`zen_of_eager_loading` for further detail. To produce a specific SQL JOIN which is explicitly available, use - :meth:`.Query.join`. To combine explicit JOINs with eager loading - of collections, use :func:`.orm.contains_eager`; see + :meth:`_query.Query.join`. + To combine explicit JOINs with eager loading + of collections, use :func:`_orm.contains_eager`; see :ref:`contains_eager`. .. seealso:: @@ -1267,7 +1274,7 @@ def subqueryload(loadopt, attr): """Indicate that the given attribute should be loaded using subquery eager loading. - This function is part of the :class:`.Load` interface and supports + This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. examples:: @@ -1305,7 +1312,7 @@ def selectinload(loadopt, attr): """Indicate that the given attribute should be loaded using SELECT IN eager loading. - This function is part of the :class:`.Load` interface and supports + This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. examples:: @@ -1344,7 +1351,7 @@ def lazyload(loadopt, attr): """Indicate that the given attribute should be loaded using "lazy" loading. - This function is part of the :class:`.Load` interface and supports + This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. .. seealso:: @@ -1371,7 +1378,7 @@ def immediateload(loadopt, attr): by the :func:`.selectinload` option, which performs the same task more efficiently by emitting a SELECT for all loaded objects. - This function is part of the :class:`.Load` interface and supports + This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. .. seealso:: @@ -1394,11 +1401,11 @@ def immediateload(*keys): def noload(loadopt, attr): """Indicate that the given relationship attribute should remain unloaded. - This function is part of the :class:`.Load` interface and supports + This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. - :func:`.orm.noload` applies to :func:`.relationship` attributes; for - column-based attributes, see :func:`.orm.defer`. + :func:`_orm.noload` applies to :func:`_orm.relationship` attributes; for + column-based attributes, see :func:`_orm.defer`. .. seealso:: @@ -1418,7 +1425,7 @@ def noload(*keys): def raiseload(loadopt, attr, sql_only=False): """Indicate that the given attribute should raise an error if accessed. - A relationship attribute configured with :func:`.orm.raiseload` will + A relationship attribute configured with :func:`_orm.raiseload` will raise an :exc:`~sqlalchemy.exc.InvalidRequestError` upon access. The typical way this is useful is when an application is attempting to ensure that all relationship attributes that are accessed in a particular context @@ -1426,7 +1433,8 @@ def raiseload(loadopt, attr, sql_only=False): to read through SQL logs to ensure lazy loads aren't occurring, this strategy will cause them to raise immediately. - :func:`.orm.raiseload` applies to :func:`.relationship` attributes only. + :func:`_orm.raiseload` applies to :func:`_orm.relationship` + attributes only. In order to apply raise-on-SQL behavior to a column-based attribute, use the :paramref:`.orm.defer.raiseload` parameter on the :func:`.defer` loader option. @@ -1436,7 +1444,7 @@ def raiseload(loadopt, attr, sql_only=False): related value should just be None due to missing keys. When False, the strategy will raise for all varieties of relationship loading. - This function is part of the :class:`.Load` interface and supports + This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. @@ -1487,7 +1495,7 @@ def defaultload(loadopt, attr): .. seealso:: - :meth:`.Load.options` - allows for complex hierarchical + :meth:`_orm.Load.options` - allows for complex hierarchical loader option structures with less verbosity than with individual :func:`.defaultload` directives. @@ -1509,7 +1517,7 @@ def defer(loadopt, key, raiseload=False): r"""Indicate that the given column-oriented attribute should be deferred, e.g. not loaded until accessed. - This function is part of the :class:`.Load` interface and supports + This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. e.g.:: @@ -1527,12 +1535,13 @@ def defer(loadopt, key, raiseload=False): To specify a deferred load of an attribute on a related class, the path can be specified one token at a time, specifying the loading style for each link along the chain. To leave the loading style - for a link unchanged, use :func:`.orm.defaultload`:: + for a link unchanged, use :func:`_orm.defaultload`:: session.query(MyClass).options(defaultload("someattr").defer("some_column")) - A :class:`.Load` object that is present on a certain path can have - :meth:`.Load.defer` called multiple times, each will operate on the same + A :class:`_orm.Load` object that is present on a certain path can have + :meth:`_orm.Load.defer` called multiple times, + each will operate on the same parent entity:: @@ -1559,7 +1568,7 @@ def defer(loadopt, key, raiseload=False): of specifying a path as a series of attributes, which is now superseded by the method-chained style. - .. deprecated:: 0.9 The \*addl_attrs on :func:`.orm.defer` is + .. deprecated:: 0.9 The \*addl_attrs on :func:`_orm.defer` is deprecated and will be removed in a future release. Please use method chaining in conjunction with defaultload() to indicate a path. @@ -1569,7 +1578,7 @@ def defer(loadopt, key, raiseload=False): :ref:`deferred` - :func:`.orm.undefer` + :func:`_orm.undefer` """ strategy = {"deferred": True, "instrument": True} @@ -1600,7 +1609,7 @@ def undefer(loadopt, key): The column being undeferred is typically set up on the mapping as a :func:`.deferred` attribute. - This function is part of the :class:`.Load` interface and supports + This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. Examples:: @@ -1622,7 +1631,7 @@ def undefer(loadopt, key): of specifying a path as a series of attributes, which is now superseded by the method-chained style. - .. deprecated:: 0.9 The \*addl_attrs on :func:`.orm.undefer` is + .. deprecated:: 0.9 The \*addl_attrs on :func:`_orm.undefer` is deprecated and will be removed in a future release. Please use method chaining in conjunction with defaultload() to indicate a path. @@ -1631,9 +1640,9 @@ def undefer(loadopt, key): :ref:`deferred` - :func:`.orm.defer` + :func:`_orm.defer` - :func:`.orm.undefer_group` + :func:`_orm.undefer_group` """ return loadopt.set_column_strategy( @@ -1669,21 +1678,21 @@ def undefer_group(loadopt, name): To undefer a group of attributes on a related entity, the path can be spelled out using relationship loader options, such as - :func:`.orm.defaultload`:: + :func:`_orm.defaultload`:: session.query(MyClass).options( defaultload("someattr").undefer_group("large_attrs")) - .. versionchanged:: 0.9.0 :func:`.orm.undefer_group` is now specific to a + .. versionchanged:: 0.9.0 :func:`_orm.undefer_group` is now specific to a particular entity load path. .. seealso:: :ref:`deferred` - :func:`.orm.defer` + :func:`_orm.defer` - :func:`.orm.undefer` + :func:`_orm.undefer` """ return loadopt.set_column_strategy( @@ -1700,7 +1709,7 @@ def undefer_group(name): def with_expression(loadopt, key, expression): r"""Apply an ad-hoc SQL expression to a "deferred expression" attribute. - This option is used in conjunction with the :func:`.orm.query_expression` + This option is used in conjunction with the :func:`_orm.query_expression` mapper-level construct that indicates an attribute which should be the target of an ad-hoc SQL expression. diff --git a/lib/sqlalchemy/orm/util.py b/lib/sqlalchemy/orm/util.py index 48e9b19bf..37d3c99cf 100644 --- a/lib/sqlalchemy/orm/util.py +++ b/lib/sqlalchemy/orm/util.py @@ -193,7 +193,7 @@ def polymorphic_union( this is used. :param table_map: mapping of polymorphic identities to - :class:`.Table` objects. + :class:`_schema.Table` objects. :param typecolname: string name of a "discriminator" column, which will be derived from the query, producing the polymorphic identity for each row. If ``None``, no polymorphic discriminator is generated. @@ -293,7 +293,7 @@ def identity_key(*args, **kwargs): (<class '__main__.MyClass'>, (1, 2), None) In this form, the given instance is ultimately run though - :meth:`.Mapper.identity_key_from_instance`, which will have the + :meth:`_orm.Mapper.identity_key_from_instance`, which will have the effect of performing a database check for the corresponding row if the object is expired. @@ -420,12 +420,12 @@ class AliasedClass(object): :class:`.AliasedClass` is also capable of mapping an existing mapped class to an entirely new selectable, provided this selectable is column- compatible with the existing mapped selectable, and it can also be - configured in a mapping as the target of a :func:`.relationship`. + configured in a mapping as the target of a :func:`_orm.relationship`. See the links below for examples. The :class:`.AliasedClass` object is constructed typically using the - :func:`.orm.aliased` function. It also is produced with additional - configuration when using the :func:`.orm.with_polymorphic` function. + :func:`_orm.aliased` function. It also is produced with additional + configuration when using the :func:`_orm.with_polymorphic` function. The resulting object is an instance of :class:`.AliasedClass`. This object implements an attribute scheme which produces the @@ -435,8 +435,8 @@ class AliasedClass(object): including hybrid attributes (see :ref:`hybrids_toplevel`). The :class:`.AliasedClass` can be inspected for its underlying - :class:`.Mapper`, aliased selectable, and other information - using :func:`.inspect`:: + :class:`_orm.Mapper`, aliased selectable, and other information + using :func:`_sa.inspect`:: from sqlalchemy import inspect my_alias = aliased(MyClass) @@ -542,7 +542,7 @@ class AliasedInsp(sql_base.HasCacheKey, InspectionAttr): The :class:`.AliasedInsp` object is returned given an :class:`.AliasedClass` using the - :func:`.inspect` function:: + :func:`_sa.inspect` function:: from sqlalchemy import inspect from sqlalchemy.orm import aliased @@ -554,13 +554,16 @@ class AliasedInsp(sql_base.HasCacheKey, InspectionAttr): include: * ``entity`` - the :class:`.AliasedClass` represented. - * ``mapper`` - the :class:`.Mapper` mapping the underlying class. - * ``selectable`` - the :class:`.Alias` construct which ultimately - represents an aliased :class:`.Table` or :class:`.Select` + * ``mapper`` - the :class:`_orm.Mapper` mapping the underlying class. + * ``selectable`` - the :class:`_expression.Alias` + construct which ultimately + represents an aliased :class:`_schema.Table` or + :class:`_expression.Select` construct. * ``name`` - the name of the alias. Also is used as the attribute - name when returned in a result tuple from :class:`.Query`. - * ``with_polymorphic_mappers`` - collection of :class:`.Mapper` objects + name when returned in a result tuple from :class:`_query.Query`. + * ``with_polymorphic_mappers`` - collection of :class:`_orm.Mapper` + objects indicating all those mappers expressed in the select construct for the :class:`.AliasedClass`. * ``polymorphic_on`` - an alternate column or SQL expression which @@ -769,37 +772,45 @@ def aliased(element, alias=None, name=None, flat=False, adapt_on_names=False): The :func:`.aliased` function is used to create an ad-hoc mapping of a mapped class to a new selectable. By default, a selectable is generated - from the normally mapped selectable (typically a :class:`.Table`) using the - :meth:`.FromClause.alias` method. However, :func:`.aliased` can also be - used to link the class to a new :func:`~.sql.expression.select` statement. + from the normally mapped selectable (typically a :class:`_schema.Table` + ) using the + :meth:`_expression.FromClause.alias` method. However, :func:`.aliased` + can also be + used to link the class to a new :func:`_expression.select` statement. Also, the :func:`.with_polymorphic` function is a variant of :func:`.aliased` that is intended to specify a so-called "polymorphic selectable", that corresponds to the union of several joined-inheritance subclasses at once. For convenience, the :func:`.aliased` function also accepts plain - :class:`.FromClause` constructs, such as a :class:`.Table` or - :func:`~.sql.expression.select` construct. In those cases, the - :meth:`.FromClause.alias` method is called on the object and the new - :class:`.Alias` object returned. The returned :class:`.Alias` is not + :class:`_expression.FromClause` constructs, such as a + :class:`_schema.Table` or + :func:`_expression.select` construct. In those cases, the + :meth:`_expression.FromClause.alias` + method is called on the object and the new + :class:`_expression.Alias` object returned. The returned + :class:`_expression.Alias` is not ORM-mapped in this case. :param element: element to be aliased. Is normally a mapped class, - but for convenience can also be a :class:`.FromClause` element. + but for convenience can also be a :class:`_expression.FromClause` element + . :param alias: Optional selectable unit to map the element to. This should - normally be a :class:`.Alias` object corresponding to the :class:`.Table` - to which the class is mapped, or to a :func:`~.sql.expression.select` + normally be a :class:`_expression.Alias` object corresponding to the + :class:`_schema.Table` + to which the class is mapped, or to a :func:`_expression.select` construct that is compatible with the mapping. By default, a simple anonymous alias of the mapped table is generated. :param name: optional string name to use for the alias, if not specified by the ``alias`` parameter. The name, among other things, forms the attribute name that will be accessible via tuples returned by a - :class:`.Query` object. + :class:`_query.Query` object. :param flat: Boolean, will be passed through to the - :meth:`.FromClause.alias` call so that aliases of :class:`.Join` objects + :meth:`_expression.FromClause.alias` call so that aliases of + :class:`_expression.Join` objects don't include an enclosing SELECT. This can lead to more efficient queries in many circumstances. A JOIN against a nested JOIN will be rewritten as a JOIN against an aliased SELECT subquery on backends that @@ -807,7 +818,7 @@ def aliased(element, alias=None, name=None, flat=False, adapt_on_names=False): .. versionadded:: 0.9.0 - .. seealso:: :meth:`.Join.alias` + .. seealso:: :meth:`_expression.Join.alias` :param adapt_on_names: if True, more liberal "matching" will be used when mapping the mapped columns of the ORM entity to those of the @@ -879,7 +890,7 @@ def with_polymorphic( .. seealso:: :ref:`with_polymorphic` - full discussion of - :func:`.orm.with_polymorphic`. + :func:`_orm.with_polymorphic`. :param base: Base class to be aliased. @@ -895,11 +906,13 @@ def with_polymorphic( support parenthesized joins, such as SQLite and older versions of MySQL. However if the :paramref:`.with_polymorphic.selectable` parameter is in use - with an existing :class:`.Alias` construct, then you should not + with an existing :class:`_expression.Alias` construct, + then you should not set this flag. :param flat: Boolean, will be passed through to the - :meth:`.FromClause.alias` call so that aliases of :class:`.Join` + :meth:`_expression.FromClause.alias` call so that aliases of + :class:`_expression.Join` objects don't include an enclosing SELECT. This can lead to more efficient queries in many circumstances. A JOIN against a nested JOIN will be rewritten as a JOIN against an aliased SELECT subquery on @@ -910,7 +923,7 @@ def with_polymorphic( .. versionadded:: 0.9.0 - .. seealso:: :meth:`.Join.alias` + .. seealso:: :meth:`_expression.Join.alias` :param selectable: a table or subquery that will be used in place of the generated FROM clause. This argument is @@ -971,7 +984,7 @@ def _orm_deannotate(element): """Remove annotations that link a column to a particular mapping. Note this doesn't affect "remote" and "foreign" annotations - passed by the :func:`.orm.foreign` and :func:`.orm.remote` + passed by the :func:`_orm.foreign` and :func:`_orm.remote` annotators. """ @@ -1121,21 +1134,21 @@ def join( ): r"""Produce an inner join between left and right clauses. - :func:`.orm.join` is an extension to the core join interface - provided by :func:`.sql.expression.join()`, where the + :func:`_orm.join` is an extension to the core join interface + provided by :func:`_expression.join()`, where the left and right selectables may be not only core selectable - objects such as :class:`.Table`, but also mapped classes or + objects such as :class:`_schema.Table`, but also mapped classes or :class:`.AliasedClass` instances. The "on" clause can be a SQL expression, or an attribute or string name - referencing a configured :func:`.relationship`. + referencing a configured :func:`_orm.relationship`. - :func:`.orm.join` is not commonly needed in modern usage, + :func:`_orm.join` is not commonly needed in modern usage, as its functionality is encapsulated within that of the - :meth:`.Query.join` method, which features a - significant amount of automation beyond :func:`.orm.join` - by itself. Explicit usage of :func:`.orm.join` - with :class:`.Query` involves usage of the - :meth:`.Query.select_from` method, as in:: + :meth:`_query.Query.join` method, which features a + significant amount of automation beyond :func:`_orm.join` + by itself. Explicit usage of :func:`_orm.join` + with :class:`_query.Query` involves usage of the + :meth:`_query.Query.select_from` method, as in:: from sqlalchemy.orm import join session.query(User).\ @@ -1149,7 +1162,7 @@ def join( join(User.addresses).\ filter(Address.email_address=='foo@bar.com') - See :meth:`.Query.join` for information on modern usage + See :meth:`_query.Query.join` for information on modern usage of ORM level joins. .. deprecated:: 0.8 @@ -1164,7 +1177,7 @@ def join( def outerjoin(left, right, onclause=None, full=False, join_to_left=None): """Produce a left outer join between left and right clauses. - This is the "outer join" version of the :func:`.orm.join` function, + This is the "outer join" version of the :func:`_orm.join` function, featuring the same behavior except that an OUTER JOIN is generated. See that function's documentation for other usage details. @@ -1174,7 +1187,8 @@ def outerjoin(left, right, onclause=None, full=False, join_to_left=None): def with_parent(instance, prop, from_entity=None): """Create filtering criterion that relates this query's primary entity - to the given related instance, using established :func:`.relationship()` + to the given related instance, using established + :func:`_orm.relationship()` configuration. The SQL rendered is the same as that rendered when a lazy loader @@ -1184,7 +1198,7 @@ def with_parent(instance, prop, from_entity=None): in the rendered statement. :param instance: - An instance which has some :func:`.relationship`. + An instance which has some :func:`_orm.relationship`. :param property: String property name, or class-bound attribute, which indicates @@ -1193,7 +1207,7 @@ def with_parent(instance, prop, from_entity=None): :param from_entity: Entity in which to consider as the left side. This defaults to the - "zero" entity of the :class:`.Query` itself. + "zero" entity of the :class:`_query.Query` itself. .. versionadded:: 1.2 diff --git a/lib/sqlalchemy/pool/base.py b/lib/sqlalchemy/pool/base.py index 17d5ba15f..7da6e2c4a 100644 --- a/lib/sqlalchemy/pool/base.py +++ b/lib/sqlalchemy/pool/base.py @@ -31,8 +31,8 @@ class _ConnDialect(object): """partial implementation of :class:`.Dialect` which provides DBAPI connection methods. - When a :class:`.Pool` is combined with an :class:`.Engine`, - the :class:`.Engine` replaces this with its own + When a :class:`_pool.Pool` is combined with an :class:`_engine.Engine`, + the :class:`_engine.Engine` replaces this with its own :class:`.Dialect`. """ @@ -94,7 +94,7 @@ class Pool(log.Identified): which defaults to ``sys.stdout`` for output.. If set to the string ``"debug"``, the logging will include pool checkouts and checkins. - The :paramref:`.Pool.echo` parameter can also be set from the + The :paramref:`_pool.Pool.echo` parameter can also be set from the :func:`.create_engine` call by using the :paramref:`.create_engine.echo_pool` parameter. @@ -151,7 +151,7 @@ class Pool(log.Identified): as it is handled by the engine creation strategy. .. versionadded:: 1.1 - ``dialect`` is now a public parameter - to the :class:`.Pool`. + to the :class:`_pool.Pool`. :param pre_ping: if True, the pool will emit a "ping" (typically "SELECT 1", but is dialect-specific) on the connection @@ -264,11 +264,11 @@ class Pool(log.Identified): connection.invalidate(exception) def recreate(self): - """Return a new :class:`.Pool`, of the same class as this one + """Return a new :class:`_pool.Pool`, of the same class as this one and configured with identical creation arguments. This method is used in conjunction with :meth:`dispose` - to close out an entire :class:`.Pool` and create a new one in + to close out an entire :class:`_pool.Pool` and create a new one in its place. """ @@ -301,7 +301,7 @@ class Pool(log.Identified): return _ConnectionFairy._checkout(self) def _return_conn(self, record): - """Given a _ConnectionRecord, return it to the :class:`.Pool`. + """Given a _ConnectionRecord, return it to the :class:`_pool.Pool`. This method is called when an instrumented DBAPI connection has its ``close()`` method called. @@ -326,7 +326,7 @@ class Pool(log.Identified): class _ConnectionRecord(object): """Internal object which maintains an individual DBAPI connection - referenced by a :class:`.Pool`. + referenced by a :class:`_pool.Pool`. The :class:`._ConnectionRecord` object always exists for any particular DBAPI connection whether or not that DBAPI connection has been @@ -340,12 +340,14 @@ class _ConnectionRecord(object): method is called, the DBAPI connection associated with this :class:`._ConnectionRecord` will be discarded, but the :class:`._ConnectionRecord` may be used again, - in which case a new DBAPI connection is produced when the :class:`.Pool` + in which case a new DBAPI connection is produced when the + :class:`_pool.Pool` next uses this record. The :class:`._ConnectionRecord` is delivered along with connection - pool events, including :meth:`.PoolEvents.connect` and - :meth:`.PoolEvents.checkout`, however :class:`._ConnectionRecord` still + pool events, including :meth:`_events.PoolEvents.connect` and + :meth:`_events.PoolEvents.checkout`, however :class:`._ConnectionRecord` + still remains an internal object whose API and internals may change. .. seealso:: @@ -382,7 +384,7 @@ class _ConnectionRecord(object): """The ``.info`` dictionary associated with the DBAPI connection. This dictionary is shared among the :attr:`._ConnectionFairy.info` - and :attr:`.Connection.info` accessors. + and :attr:`_engine.Connection.info` accessors. .. note:: @@ -468,7 +470,8 @@ class _ConnectionRecord(object): This method is called for all connection invalidations, including when the :meth:`._ConnectionFairy.invalidate` or - :meth:`.Connection.invalidate` methods are called, as well as when any + :meth:`_engine.Connection.invalidate` methods are called, + as well as when any so-called "automatic invalidation" condition occurs. :param e: an exception object indicating a reason for the invalidation. @@ -639,9 +642,9 @@ class _ConnectionFairy(object): """Proxies a DBAPI connection and provides return-on-dereference support. - This is an internal object used by the :class:`.Pool` implementation + This is an internal object used by the :class:`_pool.Pool` implementation to provide context management to a DBAPI connection delivered by - that :class:`.Pool`. + that :class:`_pool.Pool`. The name "fairy" is inspired by the fact that the :class:`._ConnectionFairy` object's lifespan is transitory, as it lasts @@ -677,10 +680,11 @@ class _ConnectionFairy(object): rather than directly against the dialect-level do_rollback() and do_commit() methods. - In practice, a :class:`.Connection` assigns a :class:`.Transaction` object + In practice, a :class:`_engine.Connection` assigns a :class:`.Transaction` + object to this variable when one is in scope so that the :class:`.Transaction` takes the job of committing or rolling back on return if - :meth:`.Connection.close` is called while the :class:`.Transaction` + :meth:`_engine.Connection.close` is called while the :class:`.Transaction` still exists. This is essentially an "event handler" of sorts but is simplified as an @@ -838,7 +842,8 @@ class _ConnectionFairy(object): The data here will follow along with the DBAPI connection including after it is returned to the connection pool and used again in subsequent instances of :class:`._ConnectionFairy`. It is shared - with the :attr:`._ConnectionRecord.info` and :attr:`.Connection.info` + with the :attr:`._ConnectionRecord.info` and + :attr:`_engine.Connection.info` accessors. The dictionary associated with a particular DBAPI connection is @@ -869,7 +874,7 @@ class _ConnectionFairy(object): """Mark this connection as invalidated. This method can be called directly, and is also called as a result - of the :meth:`.Connection.invalidate` method. When invoked, + of the :meth:`_engine.Connection.invalidate` method. When invoked, the DBAPI connection is immediately closed and discarded from further use by the pool. The invalidation mechanism proceeds via the :meth:`._ConnectionRecord.invalidate` internal method. diff --git a/lib/sqlalchemy/pool/events.py b/lib/sqlalchemy/pool/events.py index 7a3a0910a..8adfa267c 100644 --- a/lib/sqlalchemy/pool/events.py +++ b/lib/sqlalchemy/pool/events.py @@ -11,7 +11,7 @@ from ..engine.base import Engine class PoolEvents(event.Events): - """Available events for :class:`.Pool`. + """Available events for :class:`_pool.Pool`. The methods here define the name of an event as well as the names of members that are passed to listener @@ -26,11 +26,11 @@ class PoolEvents(event.Events): event.listen(Pool, 'checkout', my_on_checkout) - In addition to accepting the :class:`.Pool` class and - :class:`.Pool` instances, :class:`.PoolEvents` also accepts - :class:`.Engine` objects and the :class:`.Engine` class as + In addition to accepting the :class:`_pool.Pool` class and + :class:`_pool.Pool` instances, :class:`_events.PoolEvents` also accepts + :class:`_engine.Engine` objects and the :class:`_engine.Engine` class as targets, which will be resolved to the ``.pool`` attribute of the - given engine or the :class:`.Pool` class:: + given engine or the :class:`_pool.Pool` class:: engine = create_engine("postgresql://scott:tiger@localhost/test") @@ -56,7 +56,7 @@ class PoolEvents(event.Events): def connect(self, dbapi_connection, connection_record): """Called at the moment a particular DBAPI connection is first - created for a given :class:`.Pool`. + created for a given :class:`_pool.Pool`. This event allows one to capture the point directly after which the DBAPI module-level ``.connect()`` method has been used in order @@ -71,13 +71,16 @@ class PoolEvents(event.Events): def first_connect(self, dbapi_connection, connection_record): """Called exactly once for the first time a DBAPI connection is - checked out from a particular :class:`.Pool`. + checked out from a particular :class:`_pool.Pool`. - The rationale for :meth:`.PoolEvents.first_connect` is to determine + The rationale for :meth:`_events.PoolEvents.first_connect` + is to determine information about a particular series of database connections based on the settings used for all connections. Since a particular - :class:`.Pool` refers to a single "creator" function (which in terms - of a :class:`.Engine` refers to the URL and connection options used), + :class:`_pool.Pool` + refers to a single "creator" function (which in terms + of a :class:`_engine.Engine` + refers to the URL and connection options used), it is typically valid to make observations about a single connection that can be safely assumed to be valid about all subsequent connections, such as the database version, the server and client @@ -108,7 +111,7 @@ class PoolEvents(event.Events): using the new connection. .. seealso:: :meth:`.ConnectionEvents.engine_connect` - a similar event - which occurs upon creation of a new :class:`.Connection`. + which occurs upon creation of a new :class:`_engine.Connection`. """ @@ -136,8 +139,8 @@ class PoolEvents(event.Events): pool argument. - The :meth:`.PoolEvents.reset` event is usually followed by the - :meth:`.PoolEvents.checkin` event is called, except in those + The :meth:`_events.PoolEvents.reset` event is usually followed by the + :meth:`_events.PoolEvents.checkin` event is called, except in those cases where the connection is discarded immediately after reset. :param dbapi_connection: a DBAPI connection. diff --git a/lib/sqlalchemy/pool/impl.py b/lib/sqlalchemy/pool/impl.py index fe87dbb8e..0fe7612b9 100644 --- a/lib/sqlalchemy/pool/impl.py +++ b/lib/sqlalchemy/pool/impl.py @@ -25,10 +25,11 @@ from ..util import threading class QueuePool(Pool): - """A :class:`.Pool` that imposes a limit on the number of open connections. + """A :class:`_pool.Pool` + that imposes a limit on the number of open connections. :class:`.QueuePool` is the default pooling implementation used for - all :class:`.Engine` objects, unless the SQLite dialect is in use. + all :class:`_engine.Engine` objects, unless the SQLite dialect is in use. """ @@ -45,7 +46,7 @@ class QueuePool(Pool): Construct a QueuePool. :param creator: a callable function that returns a DB-API - connection object, same as that of :paramref:`.Pool.creator`. + connection object, same as that of :paramref:`_pool.Pool.creator`. :param pool_size: The size of the pool to be maintained, defaults to 5. This is the largest number of connections that @@ -88,9 +89,9 @@ class QueuePool(Pool): :ref:`pool_disconnects` :param \**kw: Other keyword arguments including - :paramref:`.Pool.recycle`, :paramref:`.Pool.echo`, - :paramref:`.Pool.reset_on_return` and others are passed to the - :class:`.Pool` constructor. + :paramref:`_pool.Pool.recycle`, :paramref:`_pool.Pool.echo`, + :paramref:`_pool.Pool.reset_on_return` and others are passed to the + :class:`_pool.Pool` constructor. """ Pool.__init__(self, creator, **kw) @@ -273,7 +274,7 @@ class SingletonThreadPool(Pool): for production use. - Options are the same as those of :class:`.Pool`, as well as: + Options are the same as those of :class:`_pool.Pool`, as well as: :param pool_size: The number of threads in which to maintain connections at once. Defaults to five. @@ -417,7 +418,7 @@ class StaticPool(Pool): class AssertionPool(Pool): - """A :class:`.Pool` that allows at most one checked out connection at + """A :class:`_pool.Pool` that allows at most one checked out connection at any given time. This will raise an exception if more than one connection is checked out diff --git a/lib/sqlalchemy/sql/annotation.py b/lib/sqlalchemy/sql/annotation.py index d895e730c..891b8ae09 100644 --- a/lib/sqlalchemy/sql/annotation.py +++ b/lib/sqlalchemy/sql/annotation.py @@ -64,7 +64,8 @@ class SupportsCloneAnnotations(SupportsAnnotations): return new def _deannotate(self, values=None, clone=False): - """return a copy of this :class:`.ClauseElement` with annotations + """return a copy of this :class:`_expression.ClauseElement` + with annotations removed. :param values: optional tuple of individual values @@ -98,7 +99,8 @@ class SupportsWrappingAnnotations(SupportsAnnotations): return Annotated(self, values) def _deannotate(self, values=None, clone=False): - """return a copy of this :class:`.ClauseElement` with annotations + """return a copy of this :class:`_expression.ClauseElement` + with annotations removed. :param values: optional tuple of individual values diff --git a/lib/sqlalchemy/sql/base.py b/lib/sqlalchemy/sql/base.py index a02955c8c..1b9b20b32 100644 --- a/lib/sqlalchemy/sql/base.py +++ b/lib/sqlalchemy/sql/base.py @@ -519,8 +519,9 @@ class Executable(Generative): execution. Execution options can be set on a per-statement or - per :class:`.Connection` basis. Additionally, the - :class:`.Engine` and ORM :class:`~.orm.query.Query` objects provide + per :class:`_engine.Connection` basis. Additionally, the + :class:`_engine.Engine` and ORM :class:`~.orm.query.Query` + objects provide access to execution options which they in turn configure upon connections. @@ -533,14 +534,14 @@ class Executable(Generative): Note that only a subset of possible execution options can be applied to a statement - these include "autocommit" and "stream_results", but not "isolation_level" or "compiled_cache". - See :meth:`.Connection.execution_options` for a full list of + See :meth:`_engine.Connection.execution_options` for a full list of possible options. .. seealso:: - :meth:`.Connection.execution_options` + :meth:`_engine.Connection.execution_options` - :meth:`.Query.execution_options` + :meth:`_query.Query.execution_options` :meth:`.Executable.get_execution_options` @@ -573,7 +574,8 @@ class Executable(Generative): @util.deprecated_20( ":meth:`.Executable.execute`", alternative="All statement execution in SQLAlchemy 2.0 is performed " - "by the :meth:`.Connection.execute` method of :class:`.Connection`, " + "by the :meth:`_engine.Connection.execute` method of " + ":class:`_engine.Connection`, " "or in the ORM by the :meth:`.Session.execute` method of " ":class:`.Session`.", ) @@ -595,7 +597,8 @@ class Executable(Generative): @util.deprecated_20( ":meth:`.Executable.scalar`", alternative="All statement execution in SQLAlchemy 2.0 is performed " - "by the :meth:`.Connection.execute` method of :class:`.Connection`, " + "by the :meth:`_engine.Connection.execute` method of " + ":class:`_engine.Connection`, " "or in the ORM by the :meth:`.Session.execute` method of " ":class:`.Session`; the :meth:`.Result.scalar` method can then be " "used to return a scalar result.", @@ -609,7 +612,8 @@ class Executable(Generative): @property def bind(self): - """Returns the :class:`.Engine` or :class:`.Connection` to + """Returns the :class:`_engine.Engine` or :class:`_engine.Connection` + to which this :class:`.Executable` is bound, or None if none found. This is a traversal which checks locally, then @@ -675,14 +679,19 @@ class SchemaVisitor(ClauseVisitor): class ColumnCollection(object): - """Collection of :class:`.ColumnElement` instances, typically for + """Collection of :class:`_expression.ColumnElement` instances, + typically for selectables. - The :class:`.ColumnCollection` has both mapping- and sequence- like - behaviors. A :class:`.ColumnCollection` usually stores :class:`.Column` + The :class:`_expression.ColumnCollection` + has both mapping- and sequence- like + behaviors. A :class:`_expression.ColumnCollection` usually stores + :class:`_schema.Column` objects, which are then accessible both via mapping style access as well - as attribute access style. The name for which a :class:`.Column` would - be present is normally that of the :paramref:`.Column.key` parameter, + as attribute access style. The name for which a :class:`_schema.Column` + would + be present is normally that of the :paramref:`_schema.Column.key` + parameter, however depending on the context, it may be stored under a special label name:: @@ -706,7 +715,8 @@ class ColumnCollection(object): >>> cc[1] Column('y', Integer(), table=None) - .. versionadded:: 1.4 :class:`.ColumnCollection` allows integer-based + .. versionadded:: 1.4 :class:`_expression.ColumnCollection` + allows integer-based index access to the collection. Iterating the collection yields the column expressions in order:: @@ -715,7 +725,8 @@ class ColumnCollection(object): [Column('x', Integer(), table=None), Column('y', Integer(), table=None)] - The base :class:`.ColumnCollection` object can store duplicates, which can + The base :class:`_expression.ColumnCollection` object can store duplicates + , which can mean either two columns with the same key, in which case the column returned by key access is **arbitrary**:: @@ -730,18 +741,21 @@ class ColumnCollection(object): True Or it can also mean the same column multiple times. These cases are - supported as :class:`.ColumnCollection` is used to represent the columns in + supported as :class:`_expression.ColumnCollection` + is used to represent the columns in a SELECT statement which may include duplicates. A special subclass :class:`.DedupeColumnCollection` exists which instead maintains SQLAlchemy's older behavior of not allowing duplicates; this - collection is used for schema level objects like :class:`.Table` and + collection is used for schema level objects like :class:`_schema.Table` + and :class:`.PrimaryKeyConstraint` where this deduping is helpful. The :class:`.DedupeColumnCollection` class also has additional mutation methods as the schema constructs have more use cases that require removal and replacement of columns. - .. versionchanged:: 1.4 :class:`.ColumnCollection` now stores duplicate + .. versionchanged:: 1.4 :class:`_expression.ColumnCollection` + now stores duplicate column keys as well as the same column in multiple positions. The :class:`.DedupeColumnCollection` class is added to maintain the former behavior in those cases where deduplication as well as @@ -884,28 +898,34 @@ class ColumnCollection(object): return ImmutableColumnCollection(self) def corresponding_column(self, column, require_embedded=False): - """Given a :class:`.ColumnElement`, return the exported - :class:`.ColumnElement` object from this :class:`.ColumnCollection` - which corresponds to that original :class:`.ColumnElement` via a common + """Given a :class:`_expression.ColumnElement`, return the exported + :class:`_expression.ColumnElement` object from this + :class:`_expression.ColumnCollection` + which corresponds to that original :class:`_expression.ColumnElement` + via a common ancestor column. - :param column: the target :class:`.ColumnElement` to be matched + :param column: the target :class:`_expression.ColumnElement` + to be matched :param require_embedded: only return corresponding columns for - the given :class:`.ColumnElement`, if the given - :class:`.ColumnElement` is actually present within a sub-element - of this :class:`.Selectable`. Normally the column will match if + 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:`.Selectable`. + columns of this :class:`expression.Selectable`. .. seealso:: - :meth:`.Selectable.corresponding_column` - invokes this method + :meth:`expression.Selectable.corresponding_column` + - invokes this method against the collection returned by - :attr:`.Selectable.exported_columns`. + :attr:`expression.Selectable.exported_columns`. .. versionchanged:: 1.4 the implementation for ``corresponding_column`` - was moved onto the :class:`.ColumnCollection` itself. + was moved onto the :class:`_expression.ColumnCollection` itself. """ @@ -976,9 +996,10 @@ class ColumnCollection(object): class DedupeColumnCollection(ColumnCollection): - """A :class:`.ColumnCollection` that maintains deduplicating behavior. + """A :class:`_expression.ColumnCollection` + that maintains deduplicating behavior. - This is useful by schema level objects such as :class:`.Table` and + This is useful by schema level objects such as :class:`_schema.Table` and :class:`.PrimaryKeyConstraint`. The collection includes more sophisticated mutator methods as well to suit schema objects which require mutable column collections. diff --git a/lib/sqlalchemy/sql/compiler.py b/lib/sqlalchemy/sql/compiler.py index 23b15b158..7ef9f7e6d 100644 --- a/lib/sqlalchemy/sql/compiler.py +++ b/lib/sqlalchemy/sql/compiler.py @@ -393,7 +393,7 @@ class Compiled(object): :param dialect: :class:`.Dialect` to compile against. - :param statement: :class:`.ClauseElement` to be compiled. + :param statement: :class:`_expression.ClauseElement` to be compiled. :param bind: Optional Engine or Connection to compile this statement against. @@ -533,7 +533,7 @@ class _CompileLabel(elements.ColumnElement): class SQLCompiler(Compiled): """Default implementation of :class:`.Compiled`. - Compiles :class:`.ClauseElement` objects into SQL strings. + Compiles :class:`_expression.ClauseElement` objects into SQL strings. """ @@ -637,8 +637,9 @@ class SQLCompiler(Compiled): """Optional :class:`.CompileState` object that maintains additional state used by the compiler. - Major executable objects such as :class:`~.sql.expression.Insert`, - :class:`.Update`, :class:`.Delete`, :class:`.Select` will generate this + Major executable objects such as :class:`_expression.Insert`, + :class:`_expression.Update`, :class:`_expression.Delete`, + :class:`_expression.Select` will generate this state when compiled in order to calculate additional information about the object. For the top level object that is to be executed, the state can be stored here where it can also have applicability towards result set @@ -662,7 +663,7 @@ class SQLCompiler(Compiled): :param dialect: :class:`.Dialect` to be used - :param statement: :class:`.ClauseElement` to be compiled + :param statement: :class:`_expression.ClauseElement` to be compiled :param column_keys: a list of column names to be compiled into an INSERT or UPDATE statement. @@ -3351,10 +3352,12 @@ class StrSQLCompiler(SQLCompiler): The :class:`.StrSQLCompiler` is invoked whenever a Core expression element is directly stringified without calling upon the - :meth:`.ClauseElement.compile` method. It can render a limited set + :meth:`_expression.ClauseElement.compile` method. + It can render a limited set of non-standard SQL constructs to assist in basic stringification, however for more substantial custom or dialect-specific SQL constructs, - it will be necessary to make use of :meth:`.ClauseElement.compile` + it will be necessary to make use of + :meth:`_expression.ClauseElement.compile` directly. .. seealso:: diff --git a/lib/sqlalchemy/sql/crud.py b/lib/sqlalchemy/sql/crud.py index 114dbec9e..4d14497c1 100644 --- a/lib/sqlalchemy/sql/crud.py +++ b/lib/sqlalchemy/sql/crud.py @@ -24,10 +24,10 @@ REQUIRED = util.symbol( """ Placeholder for the value within a :class:`.BindParameter` which is required to be present when the statement is passed -to :meth:`.Connection.execute`. +to :meth:`_engine.Connection.execute`. -This symbol is typically used when a :func:`.expression.insert` -or :func:`.expression.update` statement is compiled without parameter +This symbol is typically used when a :func:`_expression.insert` +or :func:`_expression.update` statement is compiled without parameter values present. """, diff --git a/lib/sqlalchemy/sql/ddl.py b/lib/sqlalchemy/sql/ddl.py index 5a2095604..4c8250e98 100644 --- a/lib/sqlalchemy/sql/ddl.py +++ b/lib/sqlalchemy/sql/ddl.py @@ -138,12 +138,13 @@ class DDLElement(roles.DDLRole, Executable, _DDLCompiles): This DDL element. :target: - The :class:`.Table` or :class:`.MetaData` object which is the + The :class:`_schema.Table` or :class:`_schema.MetaData` + object which is the target of this event. May be None if the DDL is executed explicitly. :bind: - The :class:`.Connection` being used for DDL execution + The :class:`_engine.Connection` being used for DDL execution :tables: Optional keyword argument - a list of Table objects which are to @@ -216,8 +217,9 @@ class DDL(DDLElement): Specifies literal SQL DDL to be executed by the database. DDL objects function as DDL event listeners, and can be subscribed to those events - listed in :class:`.DDLEvents`, using either :class:`.Table` or - :class:`.MetaData` objects as targets. Basic templating support allows + listed in :class:`.DDLEvents`, using either :class:`_schema.Table` or + :class:`_schema.MetaData` objects as targets. + Basic templating support allows a single DDL instance to handle repetitive tasks for multiple tables. Examples:: @@ -371,12 +373,12 @@ class CreateTable(_CreateDropBase): ): """Create a :class:`.CreateTable` construct. - :param element: a :class:`.Table` that's the subject + :param element: a :class:`_schema.Table` that's the subject of the CREATE :param on: See the description for 'on' in :class:`.DDL`. :param bind: See the description for 'bind' in :class:`.DDL`. :param include_foreign_key_constraints: optional sequence of - :class:`.ForeignKeyConstraint` objects that will be included + :class:`_schema.ForeignKeyConstraint` objects that will be included inline within the CREATE construct; if omitted, all foreign key constraints that do not specify use_alter=True are included. @@ -400,7 +402,8 @@ class _DropView(_CreateDropBase): class CreateColumn(_DDLCompiles): - """Represent a :class:`.Column` as rendered in a CREATE TABLE statement, + """Represent a :class:`_schema.Column` + as rendered in a CREATE TABLE statement, via the :class:`.CreateTable` construct. This is provided to support custom column DDL within the generation @@ -408,7 +411,7 @@ class CreateColumn(_DDLCompiles): compiler extension documented in :ref:`sqlalchemy.ext.compiler_toplevel` to extend :class:`.CreateColumn`. - Typical integration is to examine the incoming :class:`.Column` + Typical integration is to examine the incoming :class:`_schema.Column` object, and to redirect compilation if a particular flag or condition is found:: @@ -439,7 +442,8 @@ class CreateColumn(_DDLCompiles): for const in column.constraints) return text - The above construct can be applied to a :class:`.Table` as follows:: + The above construct can be applied to a :class:`_schema.Table` + as follows:: from sqlalchemy import Table, Metadata, Column, Integer, String from sqlalchemy import schema @@ -454,7 +458,8 @@ class CreateColumn(_DDLCompiles): metadata.create_all(conn) - Above, the directives we've added to the :attr:`.Column.info` collection + Above, the directives we've added to the :attr:`_schema.Column.info` + collection will be detected by our custom compilation scheme:: CREATE TABLE mytable ( @@ -468,10 +473,11 @@ class CreateColumn(_DDLCompiles): columns when producing a ``CREATE TABLE``. This is accomplished by creating a compilation rule that conditionally returns ``None``. This is essentially how to produce the same effect as using the - ``system=True`` argument on :class:`.Column`, which marks a column + ``system=True`` argument on :class:`_schema.Column`, which marks a column as an implicitly-present "system" column. - For example, suppose we wish to produce a :class:`.Table` which skips + For example, suppose we wish to produce a :class:`_schema.Table` + which skips rendering of the PostgreSQL ``xmin`` column against the PostgreSQL backend, but on other backends does render it, in anticipation of a triggered rule. A conditional compilation rule could skip this name only @@ -940,13 +946,16 @@ class SchemaDropper(DDLBase): def sort_tables(tables, skip_fn=None, extra_dependencies=None): - """sort a collection of :class:`.Table` objects based on dependency. + """sort a collection of :class:`_schema.Table` objects based on dependency + . - This is a dependency-ordered sort which will emit :class:`.Table` - objects such that they will follow their dependent :class:`.Table` objects. + This is a dependency-ordered sort which will emit :class:`_schema.Table` + objects such that they will follow their dependent :class:`_schema.Table` + objects. Tables are dependent on another based on the presence of - :class:`.ForeignKeyConstraint` objects as well as explicit dependencies - added by :meth:`.Table.add_is_dependent_on`. + :class:`_schema.ForeignKeyConstraint` + objects as well as explicit dependencies + added by :meth:`_schema.Table.add_is_dependent_on`. .. warning:: @@ -954,19 +963,21 @@ def sort_tables(tables, skip_fn=None, extra_dependencies=None): automatic resolution of dependency cycles between tables, which are usually caused by mutually dependent foreign key constraints. To resolve these cycles, either the - :paramref:`.ForeignKeyConstraint.use_alter` parameter may be applied + :paramref:`_schema.ForeignKeyConstraint.use_alter` + parameter may be applied to those constraints, or use the - :func:`.sql.sort_tables_and_constraints` function which will break + :func:`_expression.sort_tables_and_constraints` + function which will break out foreign key constraints involved in cycles separately. - :param tables: a sequence of :class:`.Table` objects. + :param tables: a sequence of :class:`_schema.Table` objects. :param skip_fn: optional callable which will be passed a - :class:`.ForeignKey` object; if it returns True, this + :class:`_schema.ForeignKey` object; if it returns True, this constraint will not be considered as a dependency. Note this is **different** from the same parameter in :func:`.sort_tables_and_constraints`, which is - instead passed the owning :class:`.ForeignKeyConstraint` object. + instead passed the owning :class:`_schema.ForeignKeyConstraint` object. :param extra_dependencies: a sequence of 2-tuples of tables which will also be considered as dependent on each other. @@ -975,7 +986,7 @@ def sort_tables(tables, skip_fn=None, extra_dependencies=None): :func:`.sort_tables_and_constraints` - :meth:`.MetaData.sorted_tables` - uses this function to sort + :meth:`_schema.MetaData.sorted_tables` - uses this function to sort """ @@ -1004,27 +1015,32 @@ def sort_tables(tables, skip_fn=None, extra_dependencies=None): def sort_tables_and_constraints( tables, filter_fn=None, extra_dependencies=None ): - """sort a collection of :class:`.Table` / :class:`.ForeignKeyConstraint` + """sort a collection of :class:`_schema.Table` / + :class:`_schema.ForeignKeyConstraint` objects. This is a dependency-ordered sort which will emit tuples of ``(Table, [ForeignKeyConstraint, ...])`` such that each - :class:`.Table` follows its dependent :class:`.Table` objects. - Remaining :class:`.ForeignKeyConstraint` objects that are separate due to + :class:`_schema.Table` follows its dependent :class:`_schema.Table` + objects. + Remaining :class:`_schema.ForeignKeyConstraint` + objects that are separate due to dependency rules not satisfied by the sort are emitted afterwards as ``(None, [ForeignKeyConstraint ...])``. Tables are dependent on another based on the presence of - :class:`.ForeignKeyConstraint` objects, explicit dependencies - added by :meth:`.Table.add_is_dependent_on`, as well as dependencies + :class:`_schema.ForeignKeyConstraint` objects, explicit dependencies + added by :meth:`_schema.Table.add_is_dependent_on`, + as well as dependencies stated here using the :paramref:`~.sort_tables_and_constraints.skip_fn` and/or :paramref:`~.sort_tables_and_constraints.extra_dependencies` parameters. - :param tables: a sequence of :class:`.Table` objects. + :param tables: a sequence of :class:`_schema.Table` objects. :param filter_fn: optional callable which will be passed a - :class:`.ForeignKeyConstraint` object, and returns a value based on + :class:`_schema.ForeignKeyConstraint` object, + and returns a value based on whether this constraint should definitely be included or excluded as an inline constraint, or neither. If it returns False, the constraint will definitely be included as a dependency that cannot be subject diff --git a/lib/sqlalchemy/sql/dml.py b/lib/sqlalchemy/sql/dml.py index 1ac3acd8a..bc800de42 100644 --- a/lib/sqlalchemy/sql/dml.py +++ b/lib/sqlalchemy/sql/dml.py @@ -5,8 +5,8 @@ # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ -Provide :class:`~.sql.expression.Insert`, :class:`.Update` and -:class:`.Delete`. +Provide :class:`_expression.Insert`, :class:`_expression.Update` and +:class:`_expression.Delete`. """ from sqlalchemy.types import NullType @@ -303,7 +303,7 @@ class UpdateBase( def bind(self): """Return a 'bind' linked to this :class:`.UpdateBase` - or a :class:`.Table` associated with it. + or a :class:`_schema.Table` associated with it. """ return self._bind or self.table.bind @@ -330,7 +330,8 @@ class UpdateBase( The given collection of column expressions should be derived from the table that is - the target of the INSERT, UPDATE, or DELETE. While :class:`.Column` + the target of the INSERT, UPDATE, or DELETE. While + :class:`_schema.Column` objects are typical, the elements can also be expressions:: stmt = table.insert().returning( @@ -403,9 +404,9 @@ class UpdateBase( The text of the hint is rendered in the appropriate location for the database backend in use, relative - to the :class:`.Table` that is the subject of this + to the :class:`_schema.Table` that is the subject of this statement, or optionally to that of the given - :class:`.Table` passed as the ``selectable`` argument. + :class:`_schema.Table` passed as the ``selectable`` argument. The ``dialect_name`` option will limit the rendering of a particular hint to a particular backend. Such as, to add a hint @@ -414,7 +415,7 @@ class UpdateBase( mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql") :param text: Text of the hint. - :param selectable: optional :class:`.Table` that specifies + :param selectable: optional :class:`_schema.Table` that specifies an element of the FROM clause within an UPDATE or DELETE to be the subject of the hint - applies only to certain backends. :param dialect_name: defaults to ``*``, if specified as the name @@ -457,10 +458,11 @@ class ValuesBase(UpdateBase): r"""specify a fixed VALUES clause for an INSERT statement, or the SET clause for an UPDATE. - Note that the :class:`~.sql.expression.Insert` and :class:`.Update` + Note that the :class:`_expression.Insert` and + :class:`_expression.Update` constructs support per-execution time formatting of the VALUES and/or SET clauses, - based on the arguments passed to :meth:`.Connection.execute`. + based on the arguments passed to :meth:`_engine.Connection.execute`. However, the :meth:`.ValuesBase.values` method can be used to "fix" a particular set of parameters into the statement. @@ -473,7 +475,8 @@ class ValuesBase(UpdateBase): onto the existing list of values. :param \**kwargs: key value pairs representing the string key - of a :class:`.Column` mapped to the value to be rendered into the + of a :class:`_schema.Column` + mapped to the value to be rendered into the VALUES or SET clause:: users.insert().values(name="some name") @@ -484,10 +487,11 @@ class ValuesBase(UpdateBase): a dictionary, tuple, or list of dictionaries or tuples can be passed as a single positional argument in order to form the VALUES or SET clause of the statement. The forms that are accepted vary - based on whether this is an :class:`~.sql.expression.Insert` or an - :class:`.Update` construct. + based on whether this is an :class:`_expression.Insert` or an + :class:`_expression.Update` construct. - For either an :class:`~.sql.expression.Insert` or :class:`.Update` + For either an :class:`_expression.Insert` or + :class:`_expression.Update` construct, a single dictionary can be passed, which works the same as that of the kwargs form:: @@ -496,12 +500,12 @@ class ValuesBase(UpdateBase): users.update().values({"name": "some new name"}) Also for either form but more typically for the - :class:`~.sql.expression.Insert` construct, a tuple that contains an + :class:`_expression.Insert` construct, a tuple that contains an entry for every column in the table is also accepted:: users.insert().values((5, "some name")) - The :class:`~.sql.expression.Insert` construct also supports being + The :class:`_expression.Insert` construct also supports being passed a list of dictionaries or full-table-tuples, which on the server will render the less common SQL syntax of "multiple values" - this syntax is supported on backends such as SQLite, PostgreSQL, @@ -524,7 +528,8 @@ class ValuesBase(UpdateBase): NOT the same as using traditional executemany() form**. The above syntax is a **special** syntax not typically used. To emit an INSERT statement against multiple rows, the normal method is - to pass a multiple values list to the :meth:`.Connection.execute` + to pass a multiple values list to the + :meth:`_engine.Connection.execute` method, which is supported by all database backends and is generally more efficient for a very large number of parameters. @@ -536,7 +541,8 @@ class ValuesBase(UpdateBase): .. versionchanged:: 1.0.0 an INSERT that uses a multiple-VALUES clause, even a list of length one, - implies that the :paramref:`.Insert.inline` flag is set to + implies that the :paramref:`_expression.Insert.inline` + flag is set to True, indicating that the statement will not attempt to fetch the "last inserted primary key" or other defaults. The statement deals with an arbitrary number of rows, so the @@ -551,20 +557,20 @@ class ValuesBase(UpdateBase): The UPDATE construct also supports rendering the SET parameters in a specific order. For this feature refer to the - :meth:`.Update.ordered_values` method. + :meth:`_expression.Update.ordered_values` method. .. seealso:: - :meth:`.Update.ordered_values` + :meth:`_expression.Update.ordered_values` .. seealso:: :ref:`inserts_and_updates` - SQL Expression Language Tutorial - :func:`~.expression.insert` - produce an ``INSERT`` statement + :func:`_expression.insert` - produce an ``INSERT`` statement - :func:`~.expression.update` - produce an ``UPDATE`` statement + :func:`_expression.update` - produce an ``UPDATE`` statement """ if self._select_names: @@ -677,7 +683,8 @@ class ValuesBase(UpdateBase): :meth:`.UpdateBase.returning` is not used simultaneously. The column values will then be available on the result using the :attr:`.ResultProxy.returned_defaults` accessor as a dictionary, - referring to values keyed to the :class:`.Column` object as well as + referring to values keyed to the :class:`_schema.Column` + object as well as its ``.key``. This method differs from :meth:`.UpdateBase.returning` in these ways: @@ -711,7 +718,8 @@ class ValuesBase(UpdateBase): an efficient implementation for the ``eager_defaults`` feature of :func:`.mapper`. - :param cols: optional list of column key names or :class:`.Column` + :param cols: optional list of column key names or + :class:`_schema.Column` objects. If omitted, all column expressions evaluated on the server are added to the returning list. @@ -730,8 +738,8 @@ class ValuesBase(UpdateBase): class Insert(ValuesBase): """Represent an INSERT construct. - The :class:`~.sql.expression.Insert` object is created using the - :func:`~.expression.insert()` function. + The :class:`_expression.Insert` object is created using the + :func:`_expression.insert()` function. .. seealso:: @@ -787,20 +795,22 @@ class Insert(ValuesBase): return_defaults=False, **dialect_kw ): - """Construct an :class:`~.sql.expression.Insert` object. + """Construct an :class:`_expression.Insert` object. Similar functionality is available via the - :meth:`~.TableClause.insert` method on - :class:`~.schema.Table`. + :meth:`_expression.TableClause.insert` method on + :class:`_schema.Table`. - :param table: :class:`.TableClause` which is the subject of the + :param table: :class:`_expression.TableClause` + which is the subject of the insert. :param values: collection of values to be inserted; see - :meth:`.Insert.values` for a description of allowed formats here. - Can be omitted entirely; a :class:`~.sql.expression.Insert` construct + :meth:`_expression.Insert.values` + for a description of allowed formats here. + Can be omitted entirely; a :class:`_expression.Insert` construct will also dynamically render the VALUES clause at execution time - based on the parameters passed to :meth:`.Connection.execute`. + based on the parameters passed to :meth:`_engine.Connection.execute`. :param inline: if True, no attempt will be made to retrieve the SQL-generated default values to be provided within the statement; @@ -845,7 +855,7 @@ class Insert(ValuesBase): @_generative def inline(self): - """Make this :class:`~.sql.expression.Insert` construct "inline" . + """Make this :class:`_expression.Insert` construct "inline" . When set, no attempt will be made to retrieve the SQL-generated default values to be provided within the statement; @@ -856,15 +866,16 @@ class Insert(ValuesBase): returning" feature for the statement. - .. versionchanged:: 1.4 the :paramref:`.Insert.inline` parameter - is now superseded by the :meth:`.Insert.inline` method. + .. versionchanged:: 1.4 the :paramref:`_expression.Insert.inline` + parameter + is now superseded by the :meth:`_expression.Insert.inline` method. """ self._inline = True @_generative def from_select(self, names, select, include_defaults=True): - """Return a new :class:`~.sql.expression.Insert` construct which represents + """Return a new :class:`_expression.Insert` construct which represents an ``INSERT...FROM SELECT`` statement. e.g.:: @@ -872,19 +883,21 @@ class Insert(ValuesBase): sel = select([table1.c.a, table1.c.b]).where(table1.c.c > 5) ins = table2.insert().from_select(['a', 'b'], sel) - :param names: a sequence of string column names or :class:`.Column` + :param names: a sequence of string column names or + :class:`_schema.Column` objects representing the target columns. - :param select: a :func:`~.sql.expression.select` construct, - :class:`.FromClause` - or other construct which resolves into a :class:`.FromClause`, - such as an ORM :class:`.Query` object, etc. The order of + :param select: a :func:`_expression.select` construct, + :class:`_expression.FromClause` + or other construct which resolves into a + :class:`_expression.FromClause`, + such as an ORM :class:`_query.Query` object, etc. The order of columns returned from this FROM clause should correspond to the order of columns sent as the ``names`` parameter; while this is not checked before passing along to the database, the database would normally raise an exception if these column lists don't correspond. :param include_defaults: if True, non-server default values and - SQL expressions as specified on :class:`.Column` objects + SQL expressions as specified on :class:`_schema.Column` objects (as documented in :ref:`metadata_defaults_toplevel`) not otherwise specified in the list of names will be rendered into the INSERT and SELECT statements, so that these values are also @@ -894,13 +907,15 @@ class Insert(ValuesBase): will only be invoked **once** for the whole statement, and **not per row**. - .. versionadded:: 1.0.0 - :meth:`.Insert.from_select` now renders + .. versionadded:: 1.0.0 - :meth:`_expression.Insert.from_select` + now renders Python-side and SQL expression column defaults into the SELECT statement for columns otherwise not included in the list of column names. .. versionchanged:: 1.0.0 an INSERT that uses FROM SELECT - implies that the :paramref:`.insert.inline` flag is set to + implies that the :paramref:`_expression.insert.inline` + flag is set to True, indicating that the statement will not attempt to fetch the "last inserted primary key" or other defaults. The statement deals with an arbitrary number of rows, so the @@ -937,7 +952,8 @@ class DMLWhereBase(object): class Update(DMLWhereBase, ValuesBase): """Represent an Update construct. - The :class:`.Update` object is created using the :func:`update()` + The :class:`_expression.Update` + object is created using the :func:`update()` function. """ @@ -987,7 +1003,7 @@ class Update(DMLWhereBase, ValuesBase): preserve_parameter_order=False, **dialect_kw ): - r"""Construct an :class:`.Update` object. + r"""Construct an :class:`_expression.Update` object. E.g.:: @@ -997,14 +1013,15 @@ class Update(DMLWhereBase, ValuesBase): values(name='user #5') Similar functionality is available via the - :meth:`~.TableClause.update` method on - :class:`.Table`:: + :meth:`_expression.TableClause.update` method on + :class:`_schema.Table`:: stmt = users.update().\ where(users.c.id==5).\ values(name='user #5') - :param table: A :class:`.Table` object representing the database + :param table: A :class:`_schema.Table` + object representing the database table to be updated. :param whereclause: Optional SQL expression describing the ``WHERE`` @@ -1035,11 +1052,11 @@ class Update(DMLWhereBase, ValuesBase): the ``SET`` clause generates for all columns. Modern applications may prefer to use the generative - :meth:`.Update.values` method to set the values of the + :meth:`_expression.Update.values` method to set the values of the UPDATE statement. :param inline: - if True, SQL defaults present on :class:`.Column` objects via + if True, SQL defaults present on :class:`_schema.Column` objects via the ``default`` keyword will be compiled 'inline' into the statement and not pre-executed. This means that their values will not be available in the dictionary returned from @@ -1047,7 +1064,8 @@ class Update(DMLWhereBase, ValuesBase): :param preserve_parameter_order: if True, the update statement is expected to receive parameters **only** via the - :meth:`.Update.values` method, and they must be passed as a Python + :meth:`_expression.Update.values` method, + and they must be passed as a Python ``list`` of 2-tuples. The rendered UPDATE statement will emit the SET clause for each referenced column maintaining this order. @@ -1056,18 +1074,18 @@ class Update(DMLWhereBase, ValuesBase): .. seealso:: :ref:`updates_order_parameters` - illustrates the - :meth:`.Update.ordered_values` method. + :meth:`_expression.Update.ordered_values` method. If both ``values`` and compile-time bind parameters are present, the compile-time bind parameters override the information specified within ``values`` on a per-key basis. - The keys within ``values`` can be either :class:`.Column` + The keys within ``values`` can be either :class:`_schema.Column` objects or their string identifiers (specifically the "key" of the - :class:`.Column`, normally but not necessarily equivalent to + :class:`_schema.Column`, normally but not necessarily equivalent to its "name"). Normally, the - :class:`.Column` objects used here are expected to be - part of the target :class:`.Table` that is the table + :class:`_schema.Column` objects used here are expected to be + part of the target :class:`_schema.Table` that is the table to be updated. However when using MySQL, a multiple-table UPDATE statement can refer to columns from any of the tables referred to in the WHERE clause. @@ -1075,14 +1093,14 @@ class Update(DMLWhereBase, ValuesBase): The values referred to in ``values`` are typically: * a literal data value (i.e. string, number, etc.) - * a SQL expression, such as a related :class:`.Column`, - a scalar-returning :func:`~.sql.expression.select` construct, + * a SQL expression, such as a related :class:`_schema.Column`, + a scalar-returning :func:`_expression.select` construct, etc. - when combining :func:`~.sql.expression.select` constructs within the - values clause of an :func:`.update` + when combining :func:`_expression.select` constructs within the + values clause of an :func:`_expression.update` construct, the subquery represented - by the :func:`~.sql.expression.select` should be *correlated* to the + by the :func:`_expression.select` should be *correlated* to the parent table, that is, providing criterion which links the table inside the subquery to the outer table being updated:: @@ -1127,10 +1145,12 @@ class Update(DMLWhereBase, ValuesBase): .. seealso:: :ref:`updates_order_parameters` - full example of the - :meth:`.Update.ordered_values` method. + :meth:`_expression.Update.ordered_values` method. - .. versionchanged:: 1.4 The :meth:`.Update.ordered_values` method - supersedes the :paramref:`.update.preserve_parameter_order` + .. versionchanged:: 1.4 The :meth:`_expression.Update.ordered_values` + method + supersedes the + :paramref:`_expression.update.preserve_parameter_order` parameter, which will be removed in SQLAlchemy 2.0. """ @@ -1158,16 +1178,18 @@ class Update(DMLWhereBase, ValuesBase): @_generative def inline(self): - """Make this :class:`.Update` construct "inline" . + """Make this :class:`_expression.Update` construct "inline" . - When set, SQL defaults present on :class:`.Column` objects via the + When set, SQL defaults present on :class:`_schema.Column` + objects via the ``default`` keyword will be compiled 'inline' into the statement and not pre-executed. This means that their values will not be available in the dictionary returned from :meth:`.ResultProxy.last_updated_params`. - .. versionchanged:: 1.4 the :paramref:`.update.inline` parameter - is now superseded by the :meth:`.Update.inline` method. + .. versionchanged:: 1.4 the :paramref:`_expression.update.inline` + parameter + is now superseded by the :meth:`_expression.Update.inline` method. """ self._inline = True @@ -1176,7 +1198,8 @@ class Update(DMLWhereBase, ValuesBase): class Delete(DMLWhereBase, UpdateBase): """Represent a DELETE construct. - The :class:`.Delete` object is created using the :func:`delete()` + The :class:`_expression.Delete` + object is created using the :func:`delete()` function. """ @@ -1210,15 +1233,16 @@ class Delete(DMLWhereBase, UpdateBase): prefixes=None, **dialect_kw ): - r"""Construct :class:`.Delete` object. + r"""Construct :class:`_expression.Delete` object. Similar functionality is available via the - :meth:`~.TableClause.delete` method on - :class:`~.schema.Table`. + :meth:`_expression.TableClause.delete` method on + :class:`_schema.Table`. :param table: The table to delete rows from. - :param whereclause: A :class:`.ClauseElement` describing the ``WHERE`` + :param whereclause: A :class:`_expression.ClauseElement` + describing the ``WHERE`` condition of the ``DELETE`` statement. Note that the :meth:`~Delete.where()` generative method may be used instead. diff --git a/lib/sqlalchemy/sql/elements.py b/lib/sqlalchemy/sql/elements.py index 9689c7a8a..49bb08644 100644 --- a/lib/sqlalchemy/sql/elements.py +++ b/lib/sqlalchemy/sql/elements.py @@ -5,8 +5,8 @@ # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php -"""Core SQL expression elements, including :class:`.ClauseElement`, -:class:`.ColumnElement`, and derived classes. +"""Core SQL expression elements, including :class:`_expression.ClauseElement`, +:class:`_expression.ColumnElement`, and derived classes. """ @@ -88,14 +88,15 @@ def between(expr, lower_bound, upper_bound, symmetric=False): SELECT id, name FROM user WHERE id BETWEEN :id_1 AND :id_2 The :func:`.between` function is a standalone version of the - :meth:`.ColumnElement.between` method available on all + :meth:`_expression.ColumnElement.between` method available on all SQL expressions, as in:: stmt = select([users_table]).where(users_table.c.id.between(5, 7)) All arguments passed to :func:`.between`, including the left side column expression, are coerced from Python scalar values if a - the value is not a :class:`.ColumnElement` subclass. For example, + the value is not a :class:`_expression.ColumnElement` subclass. + For example, three fixed values can be compared as in:: print(between(5, 3, 7)) @@ -104,7 +105,8 @@ def between(expr, lower_bound, upper_bound, symmetric=False): :param_1 BETWEEN :param_2 AND :param_3 - :param expr: a column expression, typically a :class:`.ColumnElement` + :param expr: a column expression, typically a + :class:`_expression.ColumnElement` instance or alternatively a Python scalar expression to be coerced into a column expression, serving as the left side of the ``BETWEEN`` expression. @@ -122,7 +124,7 @@ def between(expr, lower_bound, upper_bound, symmetric=False): .. seealso:: - :meth:`.ColumnElement.between` + :meth:`_expression.ColumnElement.between` """ expr = coercions.expect(roles.ExpressionElementRole, expr) @@ -133,8 +135,10 @@ def literal(value, type_=None): r"""Return a literal clause, bound to a bind parameter. Literal clauses are created automatically when non- - :class:`.ClauseElement` objects (such as strings, ints, dates, etc.) are - used in a comparison operation with a :class:`.ColumnElement` subclass, + :class:`_expression.ClauseElement` objects (such as strings, ints, dates, + etc.) are + used in a comparison operation with a :class:`_expression.ColumnElement` + subclass, such as a :class:`~sqlalchemy.schema.Column` object. Use this function to force the generation of a literal clause, which will be created as a :class:`BindParameter` with a bound value. @@ -166,7 +170,7 @@ def not_(clause): """Return a negation of the given clause, i.e. ``NOT(clause)``. The ``~`` operator is also overloaded on all - :class:`.ColumnElement` subclasses to produce the + :class:`_expression.ColumnElement` subclasses to produce the same result. """ @@ -232,7 +236,7 @@ class ClauseElement( """in the context of binary expression, convert the type of this object to the one given. - applies only to :class:`.ColumnElement` classes. + applies only to :class:`_expression.ColumnElement` classes. """ return self @@ -334,7 +338,7 @@ class ClauseElement( \**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. - (see :class:`.ColumnElement`) + (see :class:`_expression.ColumnElement`) """ return traversals.compare(self, other, **kw) @@ -396,15 +400,16 @@ class ClauseElement( def self_group(self, against=None): # type: (Optional[Any]) -> ClauseElement - """Apply a 'grouping' to this :class:`.ClauseElement`. + """Apply a 'grouping' to this :class:`_expression.ClauseElement`. This method is overridden by subclasses to return a "grouping" construct, i.e. parenthesis. In particular it's used by "binary" expressions to provide a grouping around themselves when placed into a - larger expression, as well as by :func:`~.sql.expression.select` + larger expression, as well as by :func:`_expression.select` constructs when placed into the FROM clause of another - :func:`~.sql.expression.select`. (Note that subqueries should be - normally created using the :meth:`.Select.alias` method, as many + :func:`_expression.select`. (Note that subqueries should be + normally created using the :meth:`_expression.Select.alias` method, + as many platforms require nested SELECT statements to be named). As expressions are composed together, the application of @@ -415,13 +420,15 @@ class ClauseElement( an expression like ``x OR (y AND z)`` - AND takes precedence over OR. - The base :meth:`self_group` method of :class:`.ClauseElement` + The base :meth:`self_group` method of + :class:`_expression.ClauseElement` just returns self. """ return self def _ungroup(self): - """Return this :class:`.ClauseElement` without any groupings.""" + """Return this :class:`_expression.ClauseElement` """ + """without any groupings.""" return self @@ -438,7 +445,7 @@ class ClauseElement( :param bind: An ``Engine`` or ``Connection`` from which a ``Compiled`` will be acquired. This argument takes precedence over - this :class:`.ClauseElement`'s bound engine, if any. + this :class:`_expression.ClauseElement`'s bound engine, if any. :param column_keys: Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the @@ -447,7 +454,8 @@ class ClauseElement( :param dialect: A ``Dialect`` instance from which a ``Compiled`` will be acquired. This argument takes precedence over the `bind` - argument as well as this :class:`.ClauseElement`'s bound engine, + argument as well as this :class:`_expression.ClauseElement` + 's bound engine, if any. :param inline: Used for INSERT statements, for a dialect which does @@ -553,19 +561,23 @@ class ColumnElement( """Represent a column-oriented SQL expression suitable for usage in the "columns" clause, WHERE clause etc. of a statement. - While the most familiar kind of :class:`.ColumnElement` is the - :class:`.Column` object, :class:`.ColumnElement` serves as the basis + While the most familiar kind of :class:`_expression.ColumnElement` is the + :class:`_schema.Column` object, :class:`_expression.ColumnElement` + serves as the basis for any unit that may be present in a SQL expression, including the expressions themselves, SQL functions, bound parameters, literal expressions, keywords such as ``NULL``, etc. - :class:`.ColumnElement` is the ultimate base class for all such elements. + :class:`_expression.ColumnElement` + is the ultimate base class for all such elements. A wide variety of SQLAlchemy Core functions work at the SQL expression - level, and are intended to accept instances of :class:`.ColumnElement` as + level, and are intended to accept instances of + :class:`_expression.ColumnElement` as arguments. These functions will typically document that they accept a "SQL expression" as an argument. What this means in terms of SQLAlchemy usually refers to an input which is either already in the form of a - :class:`.ColumnElement` object, or a value which can be **coerced** into + :class:`_expression.ColumnElement` object, + or a value which can be **coerced** into one. The coercion rules followed by most, but not all, SQLAlchemy Core functions with regards to SQL expressions are as follows: @@ -575,7 +587,8 @@ class ColumnElement( value". This generally means that a :func:`.bindparam` will be produced featuring the given value embedded into the construct; the resulting :class:`.BindParameter` object is an instance of - :class:`.ColumnElement`. The Python value will ultimately be sent + :class:`_expression.ColumnElement`. + The Python value will ultimately be sent to the DBAPI at execution time as a parameterized argument to the ``execute()`` or ``executemany()`` methods, after SQLAlchemy type-specific converters (e.g. those provided by any associated @@ -585,25 +598,28 @@ class ColumnElement( feature an accessor called ``__clause_element__()``. The Core expression system looks for this method when an object of otherwise unknown type is passed to a function that is looking to coerce the - argument into a :class:`.ColumnElement` and sometimes a - :class:`.SelectBase` expression. It is used within the ORM to + argument into a :class:`_expression.ColumnElement` and sometimes a + :class:`_expression.SelectBase` expression. + It is used within the ORM to convert from ORM-specific objects like mapped classes and mapped attributes into Core expression objects. * The Python ``None`` value is typically interpreted as ``NULL``, which in SQLAlchemy Core produces an instance of :func:`.null`. - A :class:`.ColumnElement` provides the ability to generate new - :class:`.ColumnElement` + A :class:`_expression.ColumnElement` provides the ability to generate new + :class:`_expression.ColumnElement` objects using Python expressions. This means that Python operators such as ``==``, ``!=`` and ``<`` are overloaded to mimic SQL operations, - and allow the instantiation of further :class:`.ColumnElement` instances - which are composed from other, more fundamental :class:`.ColumnElement` + and allow the instantiation of further :class:`_expression.ColumnElement` + instances + which are composed from other, more fundamental + :class:`_expression.ColumnElement` objects. For example, two :class:`.ColumnClause` objects can be added together with the addition operator ``+`` to produce a :class:`.BinaryExpression`. Both :class:`.ColumnClause` and :class:`.BinaryExpression` are subclasses - of :class:`.ColumnElement`:: + of :class:`_expression.ColumnElement`:: >>> from sqlalchemy.sql import column >>> column('a') + column('b') @@ -613,9 +629,9 @@ class ColumnElement( .. seealso:: - :class:`.Column` + :class:`_schema.Column` - :func:`.expression.column` + :func:`_expression.column` """ @@ -801,8 +817,8 @@ class ColumnElement( return s def shares_lineage(self, othercolumn): - """Return True if the given :class:`.ColumnElement` - has a common ancestor to this :class:`.ColumnElement`.""" + """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)) @@ -829,8 +845,9 @@ class ColumnElement( def _make_proxy( self, selectable, name=None, name_is_truncatable=False, **kw ): - """Create a new :class:`.ColumnElement` representing this - :class:`.ColumnElement` as it appears in the select list of a + """Create a new :class:`_expression.ColumnElement` representing this + :class:`_expression.ColumnElement` + as it appears in the select list of a descending selectable. """ @@ -854,15 +871,15 @@ class ColumnElement( def cast(self, type_): """Produce a type cast, i.e. ``CAST(<expression> AS <type>)``. - This is a shortcut to the :func:`~.expression.cast` function. + This is a shortcut to the :func:`_expression.cast` function. .. seealso:: :ref:`coretutorial_casts` - :func:`~.expression.cast` + :func:`_expression.cast` - :func:`~.expression.type_coerce` + :func:`_expression.type_coerce` .. versionadded:: 1.0.7 @@ -872,7 +889,7 @@ class ColumnElement( def label(self, name): """Produce a column label, i.e. ``<columnname> AS <name>``. - This is a shortcut to the :func:`~.expression.label` function. + This is a shortcut to the :func:`_expression.label` function. if 'name' is None, an anonymous label name will be generated. @@ -923,7 +940,8 @@ class ColumnElement( class WrapsColumnExpression(object): - """Mixin that defines a :class:`.ColumnElement` as a wrapper with special + """Mixin that defines a :class:`_expression.ColumnElement` + as a wrapper with special labeling behavior for an expression that already has a name. .. versionadded:: 1.4 @@ -1011,7 +1029,8 @@ class BindParameter(roles.InElementRole, ColumnElement): r"""Produce a "bound expression". The return value is an instance of :class:`.BindParameter`; this - is a :class:`.ColumnElement` subclass which represents a so-called + is a :class:`_expression.ColumnElement` + subclass which represents a so-called "placeholder" value in a SQL expression, the value of which is supplied at the point at which the statement in executed against a database connection. @@ -1041,7 +1060,7 @@ class BindParameter(roles.InElementRole, ColumnElement): In order to populate the value of ``:username`` above, the value would typically be applied at execution time to a method - like :meth:`.Connection.execute`:: + like :meth:`_engine.Connection.execute`:: result = connection.execute(stmt, username='wendy') @@ -1070,7 +1089,7 @@ class BindParameter(roles.InElementRole, ColumnElement): expr = users_table.c.name == 'Wendy' The above expression will produce a :class:`.BinaryExpression` - construct, where the left side is the :class:`.Column` object + construct, where the left side is the :class:`_schema.Column` object representing the ``name`` column, and the right side is a :class:`.BindParameter` representing the literal value:: @@ -1102,7 +1121,7 @@ class BindParameter(roles.InElementRole, ColumnElement): Similarly, :func:`.bindparam` is invoked automatically when working with :term:`CRUD` statements as far as the "VALUES" portion is - concerned. The :func:`~.sql.expression.insert` construct produces an + concerned. The :func:`_expression.insert` construct produces an ``INSERT`` expression which will, at statement execution time, generate bound placeholders based on the arguments passed, as in:: @@ -1114,10 +1133,10 @@ class BindParameter(roles.InElementRole, ColumnElement): INSERT INTO "user" (name) VALUES (%(name)s) {'name': 'Wendy'} - The :class:`~.sql.expression.Insert` construct, at + The :class:`_expression.Insert` construct, at compilation/execution time, rendered a single :func:`.bindparam` mirroring the column name ``name`` as a result of the single ``name`` - parameter we passed to the :meth:`.Connection.execute` method. + parameter we passed to the :meth:`_engine.Connection.execute` method. :param key: the key (e.g. the name) for this bind param. @@ -1440,12 +1459,13 @@ class TextClause( result = connection.execute(t) - The :class:`.Text` construct is produced using the :func:`.text` + The :class:`_expression.TextClause` construct is produced using the + :func:`_expression.text` function; see that function for full documentation. .. seealso:: - :func:`.text` + :func:`_expression.text` """ @@ -1501,7 +1521,8 @@ class TextClause( @classmethod @_document_text_coercion("text", ":func:`.text`", ":paramref:`.text.text`") def _create_text(cls, text, bind=None): - r"""Construct a new :class:`.TextClause` clause, representing + r"""Construct a new :class:`_expression.TextClause` clause, + representing a textual SQL string directly. E.g.:: @@ -1511,7 +1532,8 @@ class TextClause( t = text("SELECT * FROM users") result = connection.execute(t) - The advantages :func:`.text` provides over a plain string are + The advantages :func:`_expression.text` + provides over a plain string are backend-neutral support for bind parameters, per-statement execution options, as well as bind parameter and result-column typing behavior, allowing @@ -1531,12 +1553,15 @@ class TextClause( t = text("SELECT * FROM users WHERE name='\:username'") - The :class:`.TextClause` construct includes methods which can + The :class:`_expression.TextClause` + construct includes methods which can provide information about the bound parameters as well as the column values which would be returned from the textual statement, assuming it's an executable SELECT type of statement. The - :meth:`.TextClause.bindparams` method is used to provide bound - parameter detail, and :meth:`.TextClause.columns` method allows + :meth:`_expression.TextClause.bindparams` + method is used to provide bound + parameter detail, and :meth:`_expression.TextClause.columns` + method allows specification of return columns including names and types:: t = text("SELECT * FROM users WHERE id=:user_id").\ @@ -1546,19 +1571,20 @@ class TextClause( for id, name in connection.execute(t): print(id, name) - The :func:`.text` construct is used in cases when + The :func:`_expression.text` construct is used in cases when a literal string SQL fragment is specified as part of a larger query, such as for the WHERE clause of a SELECT statement:: s = select([users.c.id, users.c.name]).where(text("id=:user_id")) result = connection.execute(s, user_id=12) - :func:`.text` is also used for the construction + :func:`_expression.text` is also used for the construction of a full, standalone statement using plain text. As such, SQLAlchemy refers to it as an :class:`.Executable` object, and it supports the :meth:`Executable.execution_options` method. For example, - a :func:`.text` construct that should be subject to "autocommit" + a :func:`_expression.text` + construct that should be subject to "autocommit" can be set explicitly so using the :paramref:`.Connection.execution_options.autocommit` option:: @@ -1566,7 +1592,8 @@ class TextClause( execution_options(autocommit=True) Note that SQLAlchemy's usual "autocommit" behavior applies to - :func:`.text` constructs implicitly - that is, statements which begin + :func:`_expression.text` constructs implicitly - that is, + statements which begin with a phrase such as ``INSERT``, ``UPDATE``, ``DELETE``, or a variety of other phrases specific to certain backends, will be eligible for autocommit if no transaction is in progress. @@ -1591,7 +1618,7 @@ class TextClause( @_generative def bindparams(self, *binds, **names_to_values): """Establish the values and/or types of bound parameters within - this :class:`.TextClause` construct. + this :class:`_expression.TextClause` construct. Given a text construct such as:: @@ -1599,7 +1626,8 @@ class TextClause( stmt = text("SELECT id, name FROM user WHERE name=:name " "AND timestamp=:timestamp") - the :meth:`.TextClause.bindparams` method can be used to establish + the :meth:`_expression.TextClause.bindparams` + method can be used to establish the initial value of ``:name`` and ``:timestamp``, using simple keyword arguments:: @@ -1635,10 +1663,12 @@ class TextClause( result = connection.execute(stmt, timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)) - The :meth:`.TextClause.bindparams` method can be called repeatedly, + The :meth:`_expression.TextClause.bindparams` + method can be called repeatedly, where it will re-use existing :class:`.BindParameter` objects to add new information. For example, we can call - :meth:`.TextClause.bindparams` first with typing information, and a + :meth:`_expression.TextClause.bindparams` + first with typing information, and a second time with value information, and it will be combined:: stmt = text("SELECT id, name FROM user WHERE name=:name " @@ -1652,10 +1682,12 @@ class TextClause( timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5) ) - The :meth:`.TextClause.bindparams` method also supports the concept of + The :meth:`_expression.TextClause.bindparams` + method also supports the concept of **unique** bound parameters. These are parameters that are "uniquified" on name at statement compilation time, so that multiple - :func:`.text` constructs may be combined together without the names + :func:`_expression.text` + constructs may be combined together without the names conflicting. To use this feature, specify the :paramref:`.BindParameter.unique` flag on each :func:`.bindparam` object:: @@ -1678,7 +1710,8 @@ class TextClause( UNION ALL select id from table where name=:name_2 .. versionadded:: 1.3.11 Added support for the - :paramref:`.BindParameter.unique` flag to work with :func:`.text` + :paramref:`.BindParameter.unique` flag to work with + :func:`_expression.text` constructs. """ @@ -1717,13 +1750,16 @@ class TextClause( @util.preload_module("sqlalchemy.sql.selectable") def columns(self, *cols, **types): - r"""Turn this :class:`.TextClause` object into a - :class:`.TextualSelect` object that serves the same role as a SELECT + r"""Turn this :class:`_expression.TextClause` object into a + :class:`_expression.TextualSelect` + object that serves the same role as a SELECT statement. - The :class:`.TextualSelect` is part of the :class:`.SelectBase` + The :class:`_expression.TextualSelect` is part of the + :class:`_expression.SelectBase` hierarchy and can be embedded into another statement by using the - :meth:`.TextualSelect.subquery` method to produce a :class:`.Subquery` + :meth:`_expression.TextualSelect.subquery` method to produce a + :class:`.Subquery` object, which can then be SELECTed from. This function essentially bridges the gap between an entirely @@ -1740,14 +1776,17 @@ class TextClause( mytable.join(stmt, mytable.c.name == stmt.c.name) ).where(stmt.c.id > 5) - Above, we pass a series of :func:`.column` elements to the - :meth:`.TextClause.columns` method positionally. These :func:`.column` + Above, we pass a series of :func:`_expression.column` elements to the + :meth:`_expression.TextClause.columns` method positionally. These + :func:`_expression.column` elements now become first class elements upon the - :attr:`.TextualSelect.selected_columns` column collection, which then + :attr:`_expression.TextualSelect.selected_columns` column collection, + which then become part of the :attr:`.Subquery.c` collection after - :meth:`.TextualSelect.subquery` is invoked. + :meth:`_expression.TextualSelect.subquery` is invoked. - The column expressions we pass to :meth:`.TextClause.columns` may + The column expressions we pass to + :meth:`_expression.TextClause.columns` may also be typed; when we do so, these :class:`.TypeEngine` objects become the effective return type of the column, so that SQLAlchemy's result-set-processing systems may be used on the return values. @@ -1777,10 +1816,12 @@ class TextClause( for id, name, timestamp in connection.execute(stmt): print(id, name, timestamp) - The positional form of :meth:`.TextClause.columns` also provides the + The positional form of :meth:`_expression.TextClause.columns` + also provides the unique feature of **positional column targeting**, which is particularly useful when using the ORM with complex textual queries. If - we specify the columns from our model to :meth:`.TextClause.columns`, + we specify the columns from our model to + :meth:`_expression.TextClause.columns`, the result set will match to those columns positionally, meaning the name or origin of the column in the textual SQL doesn't matter:: @@ -1798,20 +1839,24 @@ class TextClause( query = session.query(User).from_statement(stmt).options( contains_eager(User.addresses)) - .. versionadded:: 1.1 the :meth:`.TextClause.columns` method now + .. versionadded:: 1.1 the :meth:`_expression.TextClause.columns` + method now offers positional column targeting in the result set when the column expressions are passed purely positionally. - The :meth:`.TextClause.columns` method provides a direct - route to calling :meth:`.FromClause.subquery` as well as - :meth:`.SelectBase.cte` against a textual SELECT statement:: + The :meth:`_expression.TextClause.columns` method provides a direct + route to calling :meth:`_expression.FromClause.subquery` as well as + :meth:`_expression.SelectBase.cte` + against a textual SELECT statement:: stmt = stmt.columns(id=Integer, name=String).cte('st') stmt = select([sometable]).where(sometable.c.id == stmt.c.id) - :param \*cols: A series of :class:`.ColumnElement` objects, typically - :class:`.Column` objects from a :class:`.Table` or ORM level + :param \*cols: A series of :class:`_expression.ColumnElement` objects, + typically + :class:`_schema.Column` objects from a :class:`_schema.Table` + or ORM level column-mapped attributes, representing a set of columns that this textual string will SELECT from. @@ -2212,7 +2257,8 @@ class BooleanClauseList(ClauseList, ColumnElement): ) The :func:`.and_` operation is also implicit in some cases; - the :meth:`.Select.where` method for example can be invoked multiple + the :meth:`_expression.Select.where` + method for example can be invoked multiple times against a statement, which will have the effect of each clause being combined using :func:`.and_`:: @@ -2477,9 +2523,11 @@ class Case(ColumnElement): The values which are accepted as result values in :paramref:`.case.whens` as well as with :paramref:`.case.else_` are coerced from Python literals into :func:`.bindparam` constructs. - SQL expressions, e.g. :class:`.ColumnElement` constructs, are accepted + SQL expressions, e.g. :class:`_expression.ColumnElement` constructs, + are accepted as well. To coerce a literal string expression into a constant - expression rendered inline, use the :func:`.literal_column` construct, + expression rendered inline, use the :func:`_expression.literal_column` + construct, as in:: from sqlalchemy import case, literal_column @@ -2595,13 +2643,16 @@ class Case(ColumnElement): def literal_column(text, type_=None): r"""Produce a :class:`.ColumnClause` object that has the - :paramref:`.column.is_literal` flag set to True. + :paramref:`_expression.column.is_literal` flag set to True. - :func:`.literal_column` is similar to :func:`.column`, except that + :func:`_expression.literal_column` is similar to + :func:`_expression.column`, except that it is more often used as a "standalone" column expression that renders - exactly as stated; while :func:`.column` stores a string name that + exactly as stated; while :func:`_expression.column` + stores a string name that will be assumed to be part of a table and may be quoted as such, - :func:`.literal_column` can be that, or any other arbitrary column-oriented + :func:`_expression.literal_column` can be that, + or any other arbitrary column-oriented expression. :param text: the text of the expression; can be any SQL expression. @@ -2616,9 +2667,9 @@ def literal_column(text, type_=None): .. seealso:: - :func:`.column` + :func:`_expression.column` - :func:`.text` + :func:`_expression.text` :ref:`sqlexpression_literal_column` @@ -2695,7 +2746,8 @@ class Cast(WrapsColumnExpression, ColumnElement): with a specific type, but does not render the ``CAST`` expression in SQL. - :param expression: A SQL expression, such as a :class:`.ColumnElement` + :param expression: A SQL expression, such as a + :class:`_expression.ColumnElement` expression or a Python string which will be coerced into a bound literal value. @@ -2730,7 +2782,7 @@ class Cast(WrapsColumnExpression, ColumnElement): class TypeCoerce(WrapsColumnExpression, ColumnElement): """Represent a Python-side type-coercion wrapper. - :class:`.TypeCoerce` supplies the :func:`.expression.type_coerce` + :class:`.TypeCoerce` supplies the :func:`_expression.type_coerce` function; see that function for usage details. .. versionchanged:: 1.1 The :func:`.type_coerce` function now produces @@ -2739,7 +2791,7 @@ class TypeCoerce(WrapsColumnExpression, ColumnElement): .. seealso:: - :func:`.expression.type_coerce` + :func:`_expression.type_coerce` :func:`.cast` @@ -2776,7 +2828,7 @@ class TypeCoerce(WrapsColumnExpression, ColumnElement): column remains separate in the list of result columns vs. other type-coerced or direct values of the target column. In order to provide a named label for the expression, use - :meth:`.ColumnElement.label`:: + :meth:`_expression.ColumnElement.label`:: stmt = select([ type_coerce( @@ -2801,7 +2853,8 @@ class TypeCoerce(WrapsColumnExpression, ColumnElement): except that it does not render the ``CAST`` expression in the resulting statement. - :param expression: A SQL expression, such as a :class:`.ColumnElement` + :param expression: A SQL expression, such as a + :class:`_expression.ColumnElement` expression or a Python string which will be coerced into a bound literal value. @@ -2961,7 +3014,8 @@ class UnaryExpression(ColumnElement): Like :func:`.asc` and :func:`.desc`, :func:`.nullsfirst` is typically invoked from the column expression itself using - :meth:`.ColumnElement.nullsfirst`, rather than as its standalone + :meth:`_expression.ColumnElement.nullsfirst`, + rather than as its standalone function version, as in:: stmt = (select([users_table]). @@ -2976,7 +3030,7 @@ class UnaryExpression(ColumnElement): :func:`.nullslast` - :meth:`.Select.order_by` + :meth:`_expression.Select.order_by` """ return UnaryExpression( @@ -3005,7 +3059,8 @@ class UnaryExpression(ColumnElement): Like :func:`.asc` and :func:`.desc`, :func:`.nullslast` is typically invoked from the column expression itself using - :meth:`.ColumnElement.nullslast`, rather than as its standalone + :meth:`_expression.ColumnElement.nullslast`, + rather than as its standalone function version, as in:: stmt = select([users_table]).\ @@ -3019,7 +3074,7 @@ class UnaryExpression(ColumnElement): :func:`.nullsfirst` - :meth:`.Select.order_by` + :meth:`_expression.Select.order_by` """ return UnaryExpression( @@ -3043,13 +3098,15 @@ class UnaryExpression(ColumnElement): SELECT id, name FROM user ORDER BY name DESC The :func:`.desc` function is a standalone version of the - :meth:`.ColumnElement.desc` method available on all SQL expressions, + :meth:`_expression.ColumnElement.desc` + method available on all SQL expressions, e.g.:: stmt = select([users_table]).order_by(users_table.c.name.desc()) - :param column: A :class:`.ColumnElement` (e.g. scalar SQL expression) + :param column: A :class:`_expression.ColumnElement` (e.g. + scalar SQL expression) with which to apply the :func:`.desc` operation. .. seealso:: @@ -3060,7 +3117,7 @@ class UnaryExpression(ColumnElement): :func:`.nullslast` - :meth:`.Select.order_by` + :meth:`_expression.Select.order_by` """ return UnaryExpression( @@ -3083,13 +3140,15 @@ class UnaryExpression(ColumnElement): SELECT id, name FROM user ORDER BY name ASC The :func:`.asc` function is a standalone version of the - :meth:`.ColumnElement.asc` method available on all SQL expressions, + :meth:`_expression.ColumnElement.asc` + method available on all SQL expressions, e.g.:: stmt = select([users_table]).order_by(users_table.c.name.asc()) - :param column: A :class:`.ColumnElement` (e.g. scalar SQL expression) + :param column: A :class:`_expression.ColumnElement` (e.g. + scalar SQL expression) with which to apply the :func:`.asc` operation. .. seealso:: @@ -3100,7 +3159,7 @@ class UnaryExpression(ColumnElement): :func:`.nullslast` - :meth:`.Select.order_by` + :meth:`_expression.Select.order_by` """ return UnaryExpression( @@ -3125,12 +3184,13 @@ class UnaryExpression(ColumnElement): SELECT COUNT(DISTINCT name) FROM user The :func:`.distinct` function is also available as a column-level - method, e.g. :meth:`.ColumnElement.distinct`, as in:: + method, e.g. :meth:`_expression.ColumnElement.distinct`, as in:: stmt = select([func.count(users_table.c.name.distinct())]) The :func:`.distinct` operator is different from the - :meth:`.Select.distinct` method of :class:`.Select`, + :meth:`_expression.Select.distinct` method of + :class:`_expression.Select`, which produces a ``SELECT`` statement with ``DISTINCT`` applied to the result set as a whole, e.g. a ``SELECT DISTINCT`` expression. See that method for further @@ -3138,9 +3198,9 @@ class UnaryExpression(ColumnElement): .. seealso:: - :meth:`.ColumnElement.distinct` + :meth:`_expression.ColumnElement.distinct` - :meth:`.Select.distinct` + :meth:`_expression.Select.distinct` :data:`.func` @@ -3210,7 +3270,7 @@ class CollectionAggregate(UnaryExpression): .. seealso:: - :func:`.expression.all_` + :func:`_expression.all_` """ @@ -3241,7 +3301,7 @@ class CollectionAggregate(UnaryExpression): .. seealso:: - :func:`.expression.any_` + :func:`_expression.any_` """ @@ -3551,7 +3611,7 @@ class Over(ColumnElement): Used against aggregate or so-called "window" functions, for database backends that support window functions. - :func:`~.expression.over` is usually called using + :func:`_expression.over` is usually called using the :meth:`.FunctionElement.over` method, e.g.:: func.row_number().over(order_by=mytable.c.some_column) @@ -3623,7 +3683,7 @@ class Over(ColumnElement): :data:`.expression.func` - :func:`.expression.within_group` + :func:`_expression.within_group` """ self.element = element @@ -3739,7 +3799,7 @@ class WithinGroup(ColumnElement): set aggregate" functions, including :class:`.percentile_cont`, :class:`.rank`, :class:`.dense_rank`, etc. - :func:`~.expression.within_group` is usually called using + :func:`_expression.within_group` is usually called using the :meth:`.FunctionElement.within_group` method, e.g.:: from sqlalchemy import within_group @@ -3765,7 +3825,7 @@ class WithinGroup(ColumnElement): :data:`.expression.func` - :func:`.expression.over` + :func:`_expression.over` """ self.element = element @@ -3904,7 +3964,7 @@ class FunctionFilter(ColumnElement): from sqlalchemy import over, funcfilter over(funcfilter(func.rank(), MyClass.y > 5), order_by='x') - See :func:`~.expression.over` for a full description. + See :func:`_expression.over` for a full description. """ return Over( @@ -3956,17 +4016,18 @@ class Label(roles.LabeledColumnExprRole, ColumnElement): def __init__(self, name, element, type_=None): """Return a :class:`Label` object for the - given :class:`.ColumnElement`. + given :class:`_expression.ColumnElement`. A label changes the name of an element in the columns clause of a ``SELECT`` statement, typically via the ``AS`` SQL keyword. This functionality is more conveniently available via the - :meth:`.ColumnElement.label` method on :class:`.ColumnElement`. + :meth:`_expression.ColumnElement.label` method on + :class:`_expression.ColumnElement`. :param name: label name - :param obj: a :class:`.ColumnElement`. + :param obj: a :class:`_expression.ColumnElement`. """ @@ -4070,8 +4131,8 @@ class ColumnClause( """Represents a column expression from any textual string. The :class:`.ColumnClause`, a lightweight analogue to the - :class:`.Column` class, is typically invoked using the - :func:`.column` function, as in:: + :class:`_schema.Column` class, is typically invoked using the + :func:`_expression.column` function, as in:: from sqlalchemy import column @@ -4083,21 +4144,24 @@ class ColumnClause( SELECT id, name FROM user :class:`.ColumnClause` is the immediate superclass of the schema-specific - :class:`.Column` object. While the :class:`.Column` class has all the + :class:`_schema.Column` object. While the :class:`_schema.Column` + class has all the same capabilities as :class:`.ColumnClause`, the :class:`.ColumnClause` class is usable by itself in those cases where behavioral requirements are limited to simple SQL expression generation. The object has none of the associations with schema-level metadata or with execution-time - behavior that :class:`.Column` does, so in that sense is a "lightweight" - version of :class:`.Column`. + behavior that :class:`_schema.Column` does, + so in that sense is a "lightweight" + version of :class:`_schema.Column`. - Full details on :class:`.ColumnClause` usage is at :func:`.column`. + Full details on :class:`.ColumnClause` usage is at + :func:`_expression.column`. .. seealso:: - :func:`.column` + :func:`_expression.column` - :class:`.Column` + :class:`_schema.Column` """ @@ -4118,7 +4182,8 @@ class ColumnClause( """Produce a :class:`.ColumnClause` object. The :class:`.ColumnClause` is a lightweight analogue to the - :class:`.Column` class. The :func:`.column` function can + :class:`_schema.Column` class. The :func:`_expression.column` + function can be invoked with just a name alone, as in:: from sqlalchemy import column @@ -4130,8 +4195,9 @@ class ColumnClause( SELECT id, name FROM user - Once constructed, :func:`.column` may be used like any other SQL - expression element such as within :func:`~.sql.expression.select` + Once constructed, :func:`_expression.column` + may be used like any other SQL + expression element such as within :func:`_expression.select` constructs:: from sqlalchemy.sql import column @@ -4139,19 +4205,24 @@ class ColumnClause( id, name = column("id"), column("name") stmt = select([id, name]).select_from("user") - The text handled by :func:`.column` is assumed to be handled + The text handled by :func:`_expression.column` + is assumed to be handled like the name of a database column; if the string contains mixed case, special characters, or matches a known reserved word on the target backend, the column expression will render using the quoting behavior determined by the backend. To produce a textual SQL expression that is rendered exactly without any quoting, - use :func:`.literal_column` instead, or pass ``True`` as the - value of :paramref:`.column.is_literal`. Additionally, full SQL - statements are best handled using the :func:`.text` construct. + use :func:`_expression.literal_column` instead, + or pass ``True`` as the + value of :paramref:`_expression.column.is_literal`. Additionally, + full SQL + statements are best handled using the :func:`_expression.text` + construct. - :func:`.column` can be used in a table-like + :func:`_expression.column` can be used in a table-like fashion by combining it with the :func:`.table` function - (which is the lightweight analogue to :class:`.Table`) to produce + (which is the lightweight analogue to :class:`_schema.Table` + ) to produce a working table construct with minimal boilerplate:: from sqlalchemy import table, column, select @@ -4164,36 +4235,37 @@ class ColumnClause( stmt = select([user.c.description]).where(user.c.name == 'wendy') - A :func:`.column` / :func:`.table` construct like that illustrated + A :func:`_expression.column` / :func:`.table` + construct like that illustrated above can be created in an ad-hoc fashion and is not associated with any - :class:`.schema.MetaData`, DDL, or events, unlike its - :class:`.Table` counterpart. + :class:`_schema.MetaData`, DDL, or events, unlike its + :class:`_schema.Table` counterpart. - .. versionchanged:: 1.0.0 :func:`.expression.column` can now + .. versionchanged:: 1.0.0 :func:`_expression.column` can now be imported from the plain ``sqlalchemy`` namespace like any other SQL element. :param text: the text of the element. - :param type: :class:`.types.TypeEngine` object which can associate + :param type: :class:`_types.TypeEngine` object which can associate this :class:`.ColumnClause` with a type. :param is_literal: if True, the :class:`.ColumnClause` is assumed to be an exact expression that will be delivered to the output with no quoting rules applied regardless of case sensitive settings. the - :func:`.literal_column()` function essentially invokes - :func:`.column` while passing ``is_literal=True``. + :func:`_expression.literal_column()` function essentially invokes + :func:`_expression.column` while passing ``is_literal=True``. .. seealso:: - :class:`.Column` + :class:`_schema.Column` - :func:`.literal_column` + :func:`_expression.literal_column` :func:`.table` - :func:`.text` + :func:`_expression.text` :ref:`sqlexpression_literal_column` @@ -4418,9 +4490,11 @@ class quoted_name(util.MemoizedSlots, util.text_type): The :class:`.quoted_name` object is normally created automatically when specifying the name for key schema constructs such as - :class:`.Table`, :class:`.Column`, and others. The class can also be + :class:`_schema.Table`, :class:`_schema.Column`, and others. + The class can also be passed explicitly as the name to any function that receives a name which - can be quoted. Such as to use the :meth:`.Engine.has_table` method with + can be quoted. Such as to use the :meth:`_engine.Engine.has_table` + method with an unconditionally quoted name:: from sqlalchemy import create_engine @@ -4592,7 +4666,7 @@ class conv(_truncated_label): In some situations, such as in migration scripts, we may be rendering the above :class:`.CheckConstraint` with a name that's already been converted. In order to make sure the name isn't double-modified, the - new name is applied using the :func:`.schema.conv` marker. We can + new name is applied using the :func:`_schema.conv` marker. We can use this explicitly as follows:: @@ -4602,7 +4676,7 @@ class conv(_truncated_label): t = Table('t', m, Column('x', Integer), CheckConstraint('x > 5', name=conv('ck_t_x5'))) - Where above, the :func:`.schema.conv` marker indicates that the constraint + Where above, the :func:`_schema.conv` marker indicates that the constraint name here is final, and the name will render as ``"ck_t_x5"`` and not ``"ck_t_ck_t_x5"`` diff --git a/lib/sqlalchemy/sql/events.py b/lib/sqlalchemy/sql/events.py index cd0ba2640..51556d929 100644 --- a/lib/sqlalchemy/sql/events.py +++ b/lib/sqlalchemy/sql/events.py @@ -13,18 +13,19 @@ class DDLEvents(event.Events): """ Define event listeners for schema objects, that is, :class:`.SchemaItem` and other :class:`.SchemaEventTarget` - subclasses, including :class:`.MetaData`, :class:`.Table`, - :class:`.Column`. + subclasses, including :class:`_schema.MetaData`, :class:`_schema.Table`, + :class:`_schema.Column`. - :class:`.MetaData` and :class:`.Table` support events + :class:`_schema.MetaData` and :class:`_schema.Table` support events specifically regarding when CREATE and DROP DDL is emitted to the database. Attachment events are also provided to customize behavior whenever a child schema element is associated - with a parent, such as, when a :class:`.Column` is associated - with its :class:`.Table`, when a :class:`.ForeignKeyConstraint` - is associated with a :class:`.Table`, etc. + with a parent, such as, when a :class:`_schema.Column` is associated + with its :class:`_schema.Table`, when a + :class:`_schema.ForeignKeyConstraint` + is associated with a :class:`_schema.Table`, etc. Example using the ``after_create`` event:: @@ -59,7 +60,8 @@ class DDLEvents(event.Events): For all :class:`.DDLEvent` events, the ``propagate=True`` keyword argument will ensure that a given event handler is propagated to copies of the - object, which are made when using the :meth:`.Table.tometadata` method:: + object, which are made when using the :meth:`_schema.Table.tometadata` + method:: from sqlalchemy import DDL event.listen( @@ -72,7 +74,7 @@ class DDLEvents(event.Events): new_table = some_table.tometadata(new_metadata) The above :class:`.DDL` object will also be associated with the - :class:`.Table` object represented by ``new_table``. + :class:`_schema.Table` object represented by ``new_table``. .. seealso:: @@ -92,9 +94,9 @@ class DDLEvents(event.Events): def before_create(self, target, connection, **kw): r"""Called before CREATE statements are emitted. - :param target: the :class:`.MetaData` or :class:`.Table` + :param target: the :class:`_schema.MetaData` or :class:`_schema.Table` object which is the target of the event. - :param connection: the :class:`.Connection` where the + :param connection: the :class:`_engine.Connection` where the CREATE statement or statements will be emitted. :param \**kw: additional keyword arguments relevant to the event. The contents of this dictionary @@ -107,16 +109,16 @@ class DDLEvents(event.Events): modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when - :meth:`.Table.tometadata` is used. + :meth:`_schema.Table.tometadata` is used. """ def after_create(self, target, connection, **kw): r"""Called after CREATE statements are emitted. - :param target: the :class:`.MetaData` or :class:`.Table` + :param target: the :class:`_schema.MetaData` or :class:`_schema.Table` object which is the target of the event. - :param connection: the :class:`.Connection` where the + :param connection: the :class:`_engine.Connection` where the CREATE statement or statements have been emitted. :param \**kw: additional keyword arguments relevant to the event. The contents of this dictionary @@ -129,16 +131,16 @@ class DDLEvents(event.Events): modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when - :meth:`.Table.tometadata` is used. + :meth:`_schema.Table.tometadata` is used. """ def before_drop(self, target, connection, **kw): r"""Called before DROP statements are emitted. - :param target: the :class:`.MetaData` or :class:`.Table` + :param target: the :class:`_schema.MetaData` or :class:`_schema.Table` object which is the target of the event. - :param connection: the :class:`.Connection` where the + :param connection: the :class:`_engine.Connection` where the DROP statement or statements will be emitted. :param \**kw: additional keyword arguments relevant to the event. The contents of this dictionary @@ -151,16 +153,16 @@ class DDLEvents(event.Events): modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when - :meth:`.Table.tometadata` is used. + :meth:`_schema.Table.tometadata` is used. """ def after_drop(self, target, connection, **kw): r"""Called after DROP statements are emitted. - :param target: the :class:`.MetaData` or :class:`.Table` + :param target: the :class:`_schema.MetaData` or :class:`_schema.Table` object which is the target of the event. - :param connection: the :class:`.Connection` where the + :param connection: the :class:`_engine.Connection` where the DROP statement or statements have been emitted. :param \**kw: additional keyword arguments relevant to the event. The contents of this dictionary @@ -173,7 +175,7 @@ class DDLEvents(event.Events): modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when - :meth:`.Table.tometadata` is used. + :meth:`_schema.Table.tometadata` is used. """ @@ -188,7 +190,7 @@ class DDLEvents(event.Events): modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when - :meth:`.Table.tometadata` is used. + :meth:`_schema.Table.tometadata` is used. """ @@ -203,13 +205,13 @@ class DDLEvents(event.Events): modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when - :meth:`.Table.tometadata` is used. + :meth:`_schema.Table.tometadata` is used. """ def column_reflect(self, inspector, table, column_info): """Called for each unit of 'column info' retrieved when - a :class:`.Table` is being reflected. + a :class:`_schema.Table` is being reflected. The dictionary of column information as returned by the dialect is passed, and can be modified. The dictionary @@ -226,13 +228,13 @@ class DDLEvents(event.Events): * ``default`` - the column's server default value. This is normally specified as a plain string SQL expression, however the event can pass a :class:`.FetchedValue`, :class:`.DefaultClause`, - or :func:`.sql.expression.text` object as well. + or :func:`_expression.text` object as well. .. versionchanged:: 1.1.6 The :meth:`.DDLEvents.column_reflect` event allows a non string :class:`.FetchedValue`, - :func:`.sql.expression.text`, or derived object to be + :func:`_expression.text`, or derived object to be specified as the value of ``default`` in the column dictionary. @@ -240,12 +242,12 @@ class DDLEvents(event.Events): The event is called before any action is taken against this dictionary, and the contents can be modified. - The :class:`.Column` specific arguments ``info``, ``key``, + The :class:`_schema.Column` specific arguments ``info``, ``key``, and ``quote`` can also be added to the dictionary and - will be passed to the constructor of :class:`.Column`. + will be passed to the constructor of :class:`_schema.Column`. Note that this event is only meaningful if either - associated with the :class:`.Table` class across the + associated with the :class:`_schema.Table` class across the board, e.g.:: from sqlalchemy.schema import Table @@ -260,7 +262,7 @@ class DDLEvents(event.Events): 'column_reflect', listen_for_reflect) - ...or with a specific :class:`.Table` instance using + ...or with a specific :class:`_schema.Table` instance using the ``listeners`` argument:: def listen_for_reflect(inspector, table, column_info): @@ -275,12 +277,13 @@ class DDLEvents(event.Events): ]) This because the reflection process initiated by ``autoload=True`` - completes within the scope of the constructor for :class:`.Table`. + completes within the scope of the constructor for + :class:`_schema.Table`. :func:`.event.listen` also accepts the ``propagate=True`` modifier for this event; when True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when - :meth:`.Table.tometadata` is used. + :meth:`_schema.Table.tometadata` is used. """ diff --git a/lib/sqlalchemy/sql/functions.py b/lib/sqlalchemy/sql/functions.py index 7973871f3..1b10df954 100644 --- a/lib/sqlalchemy/sql/functions.py +++ b/lib/sqlalchemy/sql/functions.py @@ -127,7 +127,7 @@ class FunctionElement(Executable, ColumnElement, FromClause): an anonymously named column. An interim approach to providing named columns for a function - as a FROM clause is to build a :func:`~.sql.expression.select` with the + as a FROM clause is to build a :func:`_expression.select` with the desired columns:: from sqlalchemy.sql import column @@ -163,7 +163,7 @@ class FunctionElement(Executable, ColumnElement, FromClause): from sqlalchemy import over over(func.row_number(), order_by='x') - See :func:`~.expression.over` for a full description. + See :func:`_expression.over` for a full description. """ return Over( @@ -181,7 +181,7 @@ class FunctionElement(Executable, ColumnElement, FromClause): set aggregate" functions, including :class:`.percentile_cont`, :class:`.rank`, :class:`.dense_rank`, etc. - See :func:`~.expression.within_group` for a full description. + See :func:`_expression.within_group` for a full description. .. versionadded:: 1.1 @@ -245,7 +245,8 @@ class FunctionElement(Executable, ColumnElement, FromClause): to manipulate the "left" and "right" sides of the ON clause of a JOIN expression. The purpose of this method is to provide a SQL function construct that can also supply this information to the ORM, when used - with the :paramref:`.relationship.primaryjoin` parameter. The return + with the :paramref:`_orm.relationship.primaryjoin` parameter. + The return value is a containment object called :class:`.FunctionAsBinary`. An ORM example is as follows:: @@ -300,7 +301,7 @@ class FunctionElement(Executable, ColumnElement, FromClause): return None def alias(self, name=None, flat=False): - r"""Produce a :class:`.Alias` construct against this + r"""Produce a :class:`_expression.Alias` construct against this :class:`.FunctionElement`. This construct wraps the function in a named alias which @@ -332,7 +333,7 @@ class FunctionElement(Executable, ColumnElement, FromClause): return Alias._construct(self, name) def select(self): - """Produce a :func:`~.expression.select` construct + """Produce a :func:`_expression.select` construct against this :class:`.FunctionElement`. This is shorthand for:: @@ -353,8 +354,8 @@ class FunctionElement(Executable, ColumnElement, FromClause): produce a SELECT construct. Note that :class:`.FunctionElement` can be passed to - the :meth:`.Connectable.scalar` method of :class:`.Connection` - or :class:`.Engine`. + the :meth:`.Connectable.scalar` method of :class:`_engine.Connection` + or :class:`_engine.Engine`. """ return self.select().execute().scalar() @@ -367,8 +368,8 @@ class FunctionElement(Executable, ColumnElement, FromClause): produce a SELECT construct. Note that :class:`.FunctionElement` can be passed to - the :meth:`.Connectable.execute` method of :class:`.Connection` - or :class:`.Engine`. + the :meth:`.Connectable.execute` method of :class:`_engine.Connection` + or :class:`_engine.Engine`. """ return self.select().execute() @@ -478,7 +479,8 @@ class _FunctionGenerator(object): :class:`.Function`. This object meets the "column" interface, including comparison and labeling functions. The object can also be passed the :meth:`~.Connectable.execute` - method of a :class:`.Connection` or :class:`.Engine`, where it will be + method of a :class:`_engine.Connection` or :class:`_engine.Engine`, + where it will be wrapped inside of a SELECT statement first:: print(connection.execute(func.current_timestamp()).scalar()) @@ -919,7 +921,7 @@ class array_agg(GenericFunction): """support for the ARRAY_AGG function. The ``func.array_agg(expr)`` construct returns an expression of - type :class:`.types.ARRAY`. + type :class:`_types.ARRAY`. e.g.:: @@ -929,8 +931,8 @@ class array_agg(GenericFunction): .. seealso:: - :func:`.postgresql.array_agg` - PostgreSQL-specific version that - returns :class:`.postgresql.ARRAY`, which has PG-specific operators + :func:`_postgresql.array_agg` - PostgreSQL-specific version that + returns :class:`_postgresql.ARRAY`, which has PG-specific operators added. """ @@ -988,7 +990,7 @@ class percentile_cont(OrderedSetAgg): modifier to supply a sort expression to operate upon. The return type of this function is the same as the sort expression, - or if the arguments are an array, an :class:`.types.ARRAY` of the sort + or if the arguments are an array, an :class:`_types.ARRAY` of the sort expression's type. .. versionadded:: 1.1 @@ -1005,7 +1007,7 @@ class percentile_disc(OrderedSetAgg): modifier to supply a sort expression to operate upon. The return type of this function is the same as the sort expression, - or if the arguments are an array, an :class:`.types.ARRAY` of the sort + or if the arguments are an array, an :class:`_types.ARRAY` of the sort expression's type. .. versionadded:: 1.1 @@ -1079,7 +1081,7 @@ class cube(GenericFunction): r"""Implement the ``CUBE`` grouping operation. This function is used as part of the GROUP BY of a statement, - e.g. :meth:`.Select.group_by`:: + e.g. :meth:`_expression.Select.group_by`:: stmt = select( [func.sum(table.c.value), table.c.col_1, table.c.col_2] @@ -1095,7 +1097,7 @@ class rollup(GenericFunction): r"""Implement the ``ROLLUP`` grouping operation. This function is used as part of the GROUP BY of a statement, - e.g. :meth:`.Select.group_by`:: + e.g. :meth:`_expression.Select.group_by`:: stmt = select( [func.sum(table.c.value), table.c.col_1, table.c.col_2] @@ -1111,7 +1113,7 @@ class grouping_sets(GenericFunction): r"""Implement the ``GROUPING SETS`` grouping operation. This function is used as part of the GROUP BY of a statement, - e.g. :meth:`.Select.group_by`:: + e.g. :meth:`_expression.Select.group_by`:: stmt = select( [func.sum(table.c.value), table.c.col_1, table.c.col_2] diff --git a/lib/sqlalchemy/sql/operators.py b/lib/sqlalchemy/sql/operators.py index ae56822c2..c0699c2ad 100644 --- a/lib/sqlalchemy/sql/operators.py +++ b/lib/sqlalchemy/sql/operators.py @@ -61,7 +61,7 @@ class Operators(object): When used with SQL expressions, results in an AND operation, equivalent to - :func:`~.expression.and_`, that is:: + :func:`_expression.and_`, that is:: a & b @@ -85,7 +85,7 @@ class Operators(object): When used with SQL expressions, results in an OR operation, equivalent to - :func:`~.expression.or_`, that is:: + :func:`_expression.or_`, that is:: a | b @@ -109,7 +109,7 @@ class Operators(object): When used with SQL expressions, results in a NOT operation, equivalent to - :func:`~.expression.not_`, that is:: + :func:`_expression.not_`, that is:: ~a @@ -296,7 +296,7 @@ class custom_op(object): class ColumnOperators(Operators): """Defines boolean, comparison, and other operators for - :class:`.ColumnElement` expressions. + :class:`_expression.ColumnElement` expressions. By default, all methods call down to :meth:`.operate` or :meth:`.reverse_operate`, @@ -314,9 +314,9 @@ class ColumnOperators(Operators): def eq(a, b): return a == b - The core column expression unit :class:`.ColumnElement` + The core column expression unit :class:`_expression.ColumnElement` overrides :meth:`.Operators.operate` and others - to return further :class:`.ColumnElement` constructs, + to return further :class:`_expression.ColumnElement` constructs, so that the ``==`` operation above is replaced by a clause construct. @@ -579,7 +579,7 @@ class ColumnOperators(Operators): .. versionadded:: 1.3 "expanding" bound parameters now support empty lists - * a :func:`~.sql.expression.select` construct, which is usually a + * a :func:`_expression.select` construct, which is usually a correlated scalar select:: stmt.where( @@ -594,7 +594,7 @@ class ColumnOperators(Operators): WHERE COL IN (SELECT othertable.y FROM othertable WHERE othertable.x = table.x) - :param other: a list of literals, a :func:`~.sql.expression.select` + :param other: a list of literals, a :func:`_expression.select` construct, or a :func:`.bindparam` construct that includes the :paramref:`.bindparam.expanding` flag set to True. @@ -961,32 +961,32 @@ class ColumnOperators(Operators): return self.operate(match_op, other, **kwargs) def desc(self): - """Produce a :func:`~.expression.desc` clause against the + """Produce a :func:`_expression.desc` clause against the parent object.""" return self.operate(desc_op) def asc(self): - """Produce a :func:`~.expression.asc` clause against the + """Produce a :func:`_expression.asc` clause against the parent object.""" return self.operate(asc_op) def nullsfirst(self): - """Produce a :func:`~.expression.nullsfirst` clause against the + """Produce a :func:`_expression.nullsfirst` clause against the parent object.""" return self.operate(nullsfirst_op) def nullslast(self): - """Produce a :func:`~.expression.nullslast` clause against the + """Produce a :func:`_expression.nullslast` clause against the parent object.""" return self.operate(nullslast_op) def collate(self, collation): - """Produce a :func:`~.expression.collate` clause against + """Produce a :func:`_expression.collate` clause against the parent object, given the collation string. .. seealso:: - :func:`~.expression.collate` + :func:`_expression.collate` """ return self.operate(collate, collation) @@ -1032,21 +1032,21 @@ class ColumnOperators(Operators): return self.reverse_operate(mod, other) def between(self, cleft, cright, symmetric=False): - """Produce a :func:`~.expression.between` clause against + """Produce a :func:`_expression.between` clause against the parent object, given the lower and upper range. """ return self.operate(between_op, cleft, cright, symmetric=symmetric) def distinct(self): - """Produce a :func:`~.expression.distinct` clause against the + """Produce a :func:`_expression.distinct` clause against the parent object. """ return self.operate(distinct_op) def any_(self): - """Produce a :func:`~.expression.any_` clause against the + """Produce a :func:`_expression.any_` clause against the parent object. This operator is only appropriate against a scalar subquery @@ -1061,9 +1061,9 @@ class ColumnOperators(Operators): .. seealso:: - :func:`~.expression.any_` - standalone version + :func:`_expression.any_` - standalone version - :func:`~.expression.all_` - ALL operator + :func:`_expression.all_` - ALL operator .. versionadded:: 1.1 @@ -1071,7 +1071,7 @@ class ColumnOperators(Operators): return self.operate(any_op) def all_(self): - """Produce a :func:`~.expression.all_` clause against the + """Produce a :func:`_expression.all_` clause against the parent object. This operator is only appropriate against a scalar subquery @@ -1086,9 +1086,9 @@ class ColumnOperators(Operators): .. seealso:: - :func:`~.expression.all_` - standalone version + :func:`_expression.all_` - standalone version - :func:`~.expression.any_` - ANY operator + :func:`_expression.any_` - ANY operator .. versionadded:: 1.1 diff --git a/lib/sqlalchemy/sql/schema.py b/lib/sqlalchemy/sql/schema.py index ac3fb9607..ec8d5a458 100644 --- a/lib/sqlalchemy/sql/schema.py +++ b/lib/sqlalchemy/sql/schema.py @@ -60,9 +60,9 @@ RETAIN_SCHEMA = util.symbol("retain_schema") BLANK_SCHEMA = util.symbol( "blank_schema", - """Symbol indicating that a :class:`.Table` or :class:`.Sequence` + """Symbol indicating that a :class:`_schema.Table` or :class:`.Sequence` should have 'None' for its schema, even if the parent - :class:`.MetaData` has specified a schema. + :class:`_schema.MetaData` has specified a schema. .. versionadded:: 1.0.14 @@ -131,7 +131,7 @@ class SchemaItem(SchemaEventTarget, visitors.Visitable): The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, - such as :class:`.Table` and :class:`.Column`. + such as :class:`_schema.Table` and :class:`_schema.Column`. """ return {} @@ -155,12 +155,14 @@ class Table(DialectKWArgs, SchemaItem, TableClause): Column('value', String(50)) ) - The :class:`.Table` object constructs a unique instance of itself based + The :class:`_schema.Table` + object constructs a unique instance of itself based on its name and optional schema name within the given - :class:`.MetaData` object. Calling the :class:`.Table` - constructor with the same name and same :class:`.MetaData` argument - a second time will return the *same* :class:`.Table` object - in this way - the :class:`.Table` constructor acts as a registry function. + :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:: @@ -171,10 +173,12 @@ class Table(DialectKWArgs, SchemaItem, TableClause): :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:`.Table` within - the owning :class:`.MetaData` collection. - Additional calls to :class:`.Table` with the same name, metadata, - and schema name will return the same :class:`.Table` object. + 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 @@ -186,26 +190,34 @@ class Table(DialectKWArgs, SchemaItem, TableClause): ``quote=True`` to the constructor, or use the :class:`.quoted_name` construct to specify the name. - :param metadata: a :class:`.MetaData` object which will contain this + :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:`.Connectable`. :param \*args: Additional positional arguments are used primarily - to add the list of :class:`.Column` objects contained within this + 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:`.ForeignKeyConstraint`. + :class:`.PrimaryKeyConstraint`, and + :class:`_schema.ForeignKeyConstraint`. - :param autoload: Defaults to False, unless :paramref:`.Table.autoload_with` - is set in which case it defaults to True; :class:`.Column` objects + :param autoload: Defaults to False, unless + :paramref:`_schema.Table.autoload_with` + is set in which case it defaults to True; :class:`_schema.Column` + objects for this table should be reflected from the database, possibly - augmenting or replacing existing :class:`.Column` objects that were + augmenting or replacing existing :class:`_schema.Column` + objects that were explicitly specified. - .. versionchanged:: 1.0.0 setting the :paramref:`.Table.autoload_with` - parameter implies that :paramref:`.Table.autoload` will default + .. versionchanged:: 1.0.0 setting the + :paramref:`_schema.Table.autoload_with` + parameter implies that :paramref:`_schema.Table.autoload` + will default to True. .. seealso:: @@ -213,69 +225,90 @@ class Table(DialectKWArgs, SchemaItem, TableClause): :ref:`metadata_reflection_toplevel` :param autoload_replace: Defaults to ``True``; when using - :paramref:`.Table.autoload` - in conjunction with :paramref:`.Table.extend_existing`, indicates - that :class:`.Column` objects present in the already-existing - :class:`.Table` object should be replaced with columns of the same + :paramref:`_schema.Table.autoload` + 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:`.Column` objects - specified programmatically within the call to :class:`.Table` that - also is autoloading; those :class:`.Column` objects will always + 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:`.Table.extend_existing` is ``True``. + :paramref:`_schema.Table.extend_existing` is ``True``. .. seealso:: - :paramref:`.Table.autoload` + :paramref:`_schema.Table.autoload` - :paramref:`.Table.extend_existing` + :paramref:`_schema.Table.extend_existing` - :param autoload_with: An :class:`.Engine` or :class:`.Connection` object, - or a :class:`.Inspector` object as returned by :func:`.inspect` - against one, with which this :class:`.Table` object will be reflected. + :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, it implies that - :paramref:`.Table.autoload` is ``True``. If left unset, but - :paramref:`.Table.autoload` is explicitly set to ``True``, an autoload - operation will attempt to proceed by locating an :class:`.Engine` or - :class:`.Connection` bound to the underlying :class:`.MetaData` object. + :paramref:`_schema.Table.autoload` is ``True``. If left unset, but + :paramref:`_schema.Table.autoload` is explicitly set to ``True``, + an autoload + operation will attempt to proceed by locating an + :class:`_engine.Engine` or + :class:`_engine.Connection` bound to the underlying + :class:`_schema.MetaData` object. .. seealso:: - :paramref:`.Table.autoload` + :paramref:`_schema.Table.autoload` :param extend_existing: When ``True``, indicates that if this - :class:`.Table` is already present in the given :class:`.MetaData`, + :class:`_schema.Table` is already present in the given + :class:`_schema.MetaData`, apply further arguments within the constructor to the existing - :class:`.Table`. - - If :paramref:`.Table.extend_existing` or - :paramref:`.Table.keep_existing` are not set, and the given name - of the new :class:`.Table` refers to a :class:`.Table` that is - already present in the target :class:`.MetaData` collection, and - this :class:`.Table` specifies additional columns or other constructs + :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:`.Table` - is specified that matches an existing :class:`.Table`, yet specifies + 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:`.Table.extend_existing` will also work in conjunction - with :paramref:`.Table.autoload` to run a new reflection - operation against the database, even if a :class:`.Table` + :paramref:`_schema.Table.extend_existing` + will also work in conjunction + with :paramref:`_schema.Table.autoload` 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:`.MetaData`; newly reflected :class:`.Column` objects + :class:`_schema.MetaData`; newly reflected :class:`_schema.Column` + objects and other options will be added into the state of the - :class:`.Table`, potentially overwriting existing columns + :class:`_schema.Table`, potentially overwriting existing columns and options of the same name. - As is always the case with :paramref:`.Table.autoload`, - :class:`.Column` objects can be specified in the same :class:`.Table` + As is always the case with :paramref:`_schema.Table.autoload`, + :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:`.Column` objects - both reflected from the database, as well as the given :class:`.Column` + 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, @@ -287,11 +320,11 @@ class Table(DialectKWArgs, SchemaItem, TableClause): .. seealso:: - :paramref:`.Table.autoload` + :paramref:`_schema.Table.autoload` - :paramref:`.Table.autoload_replace` + :paramref:`_schema.Table.autoload_replace` - :paramref:`.Table.keep_existing` + :paramref:`_schema.Table.keep_existing` :param implicit_returning: True by default - indicates that @@ -305,15 +338,20 @@ class Table(DialectKWArgs, SchemaItem, TableClause): ``Table`` object. Defaults to ``None`` which indicates all columns should be reflected. - :param resolve_fks: Whether or not to reflect :class:`.Table` objects - related to this one via :class:`.ForeignKey` objects, when - :paramref:`.Table.autoload` or :paramref:`.Table.autoload_with` is + :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` or + :paramref:`_schema.Table.autoload_with` is specified. Defaults to True. Set to False to disable reflection of - related tables as :class:`.ForeignKey` objects are encountered; may be + 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:`.MetaData` collection, or becomes present later, a - :class:`.ForeignKey` object associated with this :class:`.Table` will + 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 @@ -327,34 +365,41 @@ class Table(DialectKWArgs, SchemaItem, TableClause): :attr:`.SchemaItem.info` attribute of this object. :param keep_existing: When ``True``, indicates that if this Table - is already present in the given :class:`.MetaData`, ignore + is already present in the given :class:`_schema.MetaData`, ignore further arguments within the constructor to the existing - :class:`.Table`, and return the :class:`.Table` object as + :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:`.Table` on first call, but on - subsequent calls will return the same :class:`.Table`, + 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:`.Table.extend_existing` or - :paramref:`.Table.keep_existing` are not set, and the given name - of the new :class:`.Table` refers to a :class:`.Table` that is - already present in the target :class:`.MetaData` collection, and - this :class:`.Table` specifies additional columns or other constructs + 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:`.Table` - is specified that matches an existing :class:`.Table`, yet specifies + 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:`.Table.extend_existing` + :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:`.Table` before + of a listener function specific to this :class:`_schema.Table` before the "autoload" process begins. Particularly useful for the :meth:`.DDLEvents.column_reflect` event:: @@ -370,7 +415,7 @@ class Table(DialectKWArgs, SchemaItem, TableClause): ]) :param mustexist: When ``True``, indicates that this Table must already - be present in the given :class:`.MetaData` collection, else + be present in the given :class:`_schema.MetaData` collection, else an exception is raised. :param prefixes: @@ -391,16 +436,23 @@ class Table(DialectKWArgs, SchemaItem, TableClause): 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:`.MetaData` of this :class:`.Table` specifies its - own :paramref:`.MetaData.schema` parameter, then that schema name will - be applied to this :class:`.Table` if the schema parameter here is set - to ``None``. To set a blank schema name on a :class:`.Table` that - would otherwise use the schema set on the owning :class:`.MetaData`, + 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`. .. versionadded:: 1.0.14 Added the :attr:`.BLANK_SCHEMA` symbol to - allow a :class:`.Table` to have a blank schema name even when the - parent :class:`.MetaData` specifies :paramref:`.MetaData.schema`. + allow a :class:`_schema.Table` + to have a blank schema name even when the + parent :class:`_schema.MetaData` specifies + :paramref:`_schema.MetaData.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 @@ -411,8 +463,9 @@ class Table(DialectKWArgs, SchemaItem, TableClause): :param comment: Optional string that will render an SQL comment on table creation. - .. versionadded:: 1.2 Added the :paramref:`.Table.comment` parameter - to :class:`.Table`. + .. 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>``. @@ -482,10 +535,10 @@ class Table(DialectKWArgs, SchemaItem, TableClause): metadata._remove_table(name, schema) def __init__(self, *args, **kw): - """Constructor for :class:`~.schema.Table`. + """Constructor for :class:`_schema.Table`. This method is a no-op. See the top-level - documentation for :class:`~.schema.Table` + documentation for :class:`_schema.Table` for constructor arguments. """ @@ -596,10 +649,11 @@ class Table(DialectKWArgs, SchemaItem, TableClause): @property def foreign_key_constraints(self): - """:class:`.ForeignKeyConstraint` objects referred to by this - :class:`.Table`. + """:class:`_schema.ForeignKeyConstraint` objects referred to by this + :class:`_schema.Table`. - This list is produced from the collection of :class:`.ForeignKey` + This list is produced from the collection of + :class:`_schema.ForeignKey` objects currently associated. .. versionadded:: 1.0.0 @@ -676,12 +730,13 @@ class Table(DialectKWArgs, SchemaItem, TableClause): @property def key(self): - """Return the 'key' for this :class:`.Table`. + """Return the 'key' for this :class:`_schema.Table`. This value is used as the dictionary key within the - :attr:`.MetaData.tables` collection. It is typically the same - as that of :attr:`.Table.name` for a table with no - :attr:`.Table.schema` set; otherwise it is typically of the form + :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``. """ @@ -719,13 +774,13 @@ class Table(DialectKWArgs, SchemaItem, TableClause): self._extra_dependencies.add(table) def append_column(self, column): - """Append a :class:`~.schema.Column` to this :class:`~.schema.Table`. + """Append a :class:`_schema.Column` to this :class:`_schema.Table`. - The "key" of the newly added :class:`~.schema.Column`, i.e. the + 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 + 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` + UPDATE, etc. statements generated from this :class:`_schema.Table` construct. Note that this does **not** change the definition of the table @@ -741,13 +796,13 @@ class Table(DialectKWArgs, SchemaItem, TableClause): column._set_parent_with_dispatch(self) def append_constraint(self, constraint): - """Append a :class:`~.schema.Constraint` to this - :class:`~.schema.Table`. + """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. + :class:`_schema.Constraint` object. Note that this does **not** produce the constraint within the relational database automatically, for a table that already exists @@ -782,9 +837,9 @@ class Table(DialectKWArgs, SchemaItem, TableClause): @util.deprecated( "1.4", - "The :meth:`.Table.exists` method is deprecated and will be " + "The :meth:`_schema.Table.exists` method is deprecated and will be " "removed in a future release. Please refer to " - ":meth:`.Inspector.has_table`.", + ":meth:`_reflection.Inspector.has_table`.", ) def exists(self, bind=None): """Return True if this table exists. @@ -799,12 +854,12 @@ class Table(DialectKWArgs, SchemaItem, TableClause): def create(self, bind=None, checkfirst=False): """Issue a ``CREATE`` statement for this - :class:`.Table`, using the given :class:`.Connectable` + :class:`_schema.Table`, using the given :class:`.Connectable` for connectivity. .. seealso:: - :meth:`.MetaData.create_all`. + :meth:`_schema.MetaData.create_all`. """ @@ -814,12 +869,12 @@ class Table(DialectKWArgs, SchemaItem, TableClause): def drop(self, bind=None, checkfirst=False): """Issue a ``DROP`` statement for this - :class:`.Table`, using the given :class:`.Connectable` + :class:`_schema.Table`, using the given :class:`.Connectable` for connectivity. .. seealso:: - :meth:`.MetaData.drop_all`. + :meth:`_schema.MetaData.drop_all`. """ if bind is None: @@ -833,8 +888,9 @@ class Table(DialectKWArgs, SchemaItem, TableClause): referred_schema_fn=None, name=None, ): - """Return a copy of this :class:`.Table` associated with a different - :class:`.MetaData`. + """Return a copy of this :class:`_schema.Table` + associated with a different + :class:`_schema.MetaData`. E.g.:: @@ -845,16 +901,19 @@ class Table(DialectKWArgs, SchemaItem, TableClause): m2 = MetaData() user_copy = user.tometadata(m2) - :param metadata: Target :class:`.MetaData` object, into which the - new :class:`.Table` object will be created. + :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:`.Table`. If set to a string name, the new :class:`.Table` + :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:`.MetaData`, which is typically ``None`` as well, unless + :class:`_schema.MetaData`, which is typically ``None`` as well, + unless set explicitly:: m2 = MetaData(schema='newschema') @@ -869,10 +928,10 @@ class Table(DialectKWArgs, SchemaItem, TableClause): :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:`.ForeignKeyConstraint`. - The callable accepts this parent :class:`.Table`, the + 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:`.ForeignKeyConstraint` object, and the existing + :class:`_schema.ForeignKeyConstraint` object, and the existing "target schema" of that constraint. The function should return the string schema name that should be applied. E.g.:: @@ -891,7 +950,8 @@ class Table(DialectKWArgs, SchemaItem, TableClause): :param name: optional string name indicating the target table name. If not specified or None, the table name is retained. This allows - a :class:`.Table` to be copied to the same :class:`.MetaData` target + a :class:`_schema.Table` to be copied to the same + :class:`_schema.MetaData` target with a new name. .. versionadded:: 1.0.0 @@ -985,7 +1045,7 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause): The name field may be omitted at construction time and applied later, at any time before the Column is associated with a - :class:`.Table`. This is to support convenient + :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 @@ -1004,21 +1064,24 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause): If the ``type`` is ``None`` or is omitted, it will first default to the special type :class:`.NullType`. If and when this - :class:`.Column` is made to refer to another column using - :class:`.ForeignKey` and/or :class:`.ForeignKeyConstraint`, the type + :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:`.Column` object. + remote :class:`_schema.Column` object. .. versionchanged:: 0.9.0 - Support for propagation of type to a :class:`.Column` from its - :class:`.ForeignKey` object has been improved and should be + Support for propagation of type to a :class:`_schema.Column` + from its + :class:`_schema.ForeignKey` object has been improved and should be more reliable and timely. :param \*args: Additional positional arguments include various :class:`.SchemaItem` derived constructs which will be applied as options to the column. These include instances of - :class:`.Constraint`, :class:`.ForeignKey`, :class:`.ColumnDefault`, + :class:`.Constraint`, :class:`_schema.ForeignKey`, + :class:`.ColumnDefault`, :class:`.Sequence`, :class:`.Computed`. In some cases an equivalent keyword argument is available such as ``server_default``, ``default`` and ``unique``. @@ -1053,7 +1116,8 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause): (multi-column) primary keys, autoincrement is never implicitly enabled; as always, ``autoincrement=True`` will allow for at most one of those columns to be an "autoincrement" column. - ``autoincrement=True`` may also be set on a :class:`.Column` + ``autoincrement=True`` may also be set on a + :class:`_schema.Column` that has an explicit client-side or server-side default, subject to limitations of the backend database and dialect. @@ -1064,7 +1128,8 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause): * Part of the primary key - * Not referring to another column via :class:`.ForeignKey`, unless + * Not referring to another column via :class:`_schema.ForeignKey`, + unless the value is specified as ``'ignore_fk'``:: # turn on autoincrement for this column despite @@ -1102,14 +1167,15 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause): :param default: A scalar, Python callable, or - :class:`.ColumnElement` expression representing the + :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:`.Column.server_default` + Contrast this argument to + :paramref:`_schema.Column.server_default` which creates a default generator on the database side. .. seealso:: @@ -1118,11 +1184,13 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause): :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:`.Column.comment` + **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:`.Table`. When a key is provided, + ``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. @@ -1141,7 +1209,8 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause): ``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:`~.Column.primary_key` is also ``True``, in which case it + :paramref:`_schema.Column.primary_key` is also ``True``, + in which case it defaults to ``False``. This parameter is only used when issuing CREATE TABLE statements. @@ -1160,7 +1229,7 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause): :param primary_key: If ``True``, marks this column as a primary key column. Multiple columns can have this flag set to specify composite primary keys. As an alternative, the primary key of a - :class:`.Table` can be specified via an explicit + :class:`_schema.Table` can be specified via an explicit :class:`.PrimaryKeyConstraint` object. :param server_default: A :class:`.FetchedValue` instance, str, Unicode @@ -1233,8 +1302,9 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause): :param comment: Optional string that will render an SQL comment on table creation. - .. versionadded:: 1.2 Added the :paramref:`.Column.comment` - parameter to :class:`.Column`. + .. versionadded:: 1.2 Added the + :paramref:`_schema.Column.comment` + parameter to :class:`_schema.Column`. """ @@ -1600,7 +1670,8 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause): class ForeignKey(DialectKWArgs, SchemaItem): """Defines a dependency between two columns. - ``ForeignKey`` is specified as an argument to a :class:`.Column` object, + ``ForeignKey`` is specified as an argument to a :class:`_schema.Column` + object, e.g.:: t = Table("remote_table", metadata, @@ -1609,24 +1680,26 @@ class ForeignKey(DialectKWArgs, SchemaItem): 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:`.ForeignKeyConstraint` + 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:`.Column` which - in turn is associated with a :class:`.Table`. Conversely, - when :class:`.ForeignKeyConstraint` is applied to a :class:`.Table`, + 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:`.Column`, which are also + 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:`.ForeignKeyConstraint` object must be used, and applied - to the :class:`.Table`. The associated ``ForeignKey`` objects + 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:`.Column` object are available in the `foreign_keys` collection + :class:`_schema.Column` + object are available in the `foreign_keys` collection of that column. Further examples of foreign key configuration are in @@ -1654,12 +1727,13 @@ class ForeignKey(DialectKWArgs, SchemaItem): r""" Construct a column-level FOREIGN KEY. - The :class:`.ForeignKey` object when constructed generates a - :class:`.ForeignKeyConstraint` which is associated with the parent - :class:`.Table` object's collection of constraints. + 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:`.Column` object or a column name as a string: + :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 @@ -1687,14 +1761,15 @@ class ForeignKey(DialectKWArgs, SchemaItem): assigned ``key``. :param use_alter: passed to the underlying - :class:`.ForeignKeyConstraint` to indicate the constraint should + :class:`_schema.ForeignKeyConstraint` + to indicate the constraint should be generated/dropped externally from the CREATE TABLE/ DROP TABLE - statement. See :paramref:`.ForeignKeyConstraint.use_alter` + statement. See :paramref:`_schema.ForeignKeyConstraint.use_alter` for further description. .. seealso:: - :paramref:`.ForeignKeyConstraint.use_alter` + :paramref:`_schema.ForeignKeyConstraint.use_alter` :ref:`use_alter` @@ -1710,7 +1785,8 @@ class ForeignKey(DialectKWArgs, SchemaItem): :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:`.ForeignKeyConstraint`. See the documentation regarding + :class:`_schema.ForeignKeyConstraint`. + See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. @@ -1756,16 +1832,16 @@ class ForeignKey(DialectKWArgs, SchemaItem): return "ForeignKey(%r)" % self._get_colspec() def copy(self, schema=None): - """Produce a copy of this :class:`.ForeignKey` object. + """Produce a copy of this :class:`_schema.ForeignKey` object. - The new :class:`.ForeignKey` will not be bound - to any :class:`.Column`. + The new :class:`_schema.ForeignKey` will not be bound + to any :class:`_schema.Column`. This method is usually used by the internal - copy procedures of :class:`.Column`, :class:`.Table`, - and :class:`.MetaData`. + copy procedures of :class:`_schema.Column`, :class:`_schema.Table`, + and :class:`_schema.MetaData`. - :param schema: The returned :class:`.ForeignKey` will + :param schema: The returned :class:`_schema.ForeignKey` will reference the original table and column name, qualified by the given string schema name. @@ -1787,7 +1863,7 @@ class ForeignKey(DialectKWArgs, SchemaItem): def _get_colspec(self, schema=None, table_name=None): """Return a string based 'column specification' for this - :class:`.ForeignKey`. + :class:`_schema.ForeignKey`. This is usually the equivalent of the string-based "tablename.colname" argument first passed to the object's constructor. @@ -1829,17 +1905,20 @@ class ForeignKey(DialectKWArgs, SchemaItem): target_fullname = property(_get_colspec) def references(self, table): - """Return True if the given :class:`.Table` is referenced by this - :class:`.ForeignKey`.""" + """Return True if the given :class:`_schema.Table` + is referenced by this + :class:`_schema.ForeignKey`.""" return table.corresponding_column(self.column) is not None def get_referent(self, table): - """Return the :class:`.Column` in the given :class:`.Table` - referenced by this :class:`.ForeignKey`. + """Return the :class:`_schema.Column` in the given + :class:`_schema.Table` + referenced by this :class:`_schema.ForeignKey`. - Returns None if this :class:`.ForeignKey` does not reference the given - :class:`.Table`. + Returns None if this :class:`_schema.ForeignKey` + does not reference the given + :class:`_schema.Table`. """ @@ -1966,8 +2045,8 @@ class ForeignKey(DialectKWArgs, SchemaItem): @util.memoized_property def column(self): - """Return the target :class:`.Column` referenced by this - :class:`.ForeignKey`. + """Return the target :class:`_schema.Column` referenced by this + :class:`_schema.ForeignKey`. If no target column has been established, an exception is raised. @@ -2097,7 +2176,8 @@ class DefaultGenerator(SchemaItem): @util.deprecated_20( ":meth:`.DefaultGenerator.execute`", alternative="All statement execution in SQLAlchemy 2.0 is performed " - "by the :meth:`.Connection.execute` method of :class:`.Connection`, " + "by the :meth:`_engine.Connection.execute` method of " + ":class:`_engine.Connection`, " "or in the ORM by the :meth:`.Session.execute` method of " ":class:`.Session`.", ) @@ -2126,7 +2206,7 @@ class ColumnDefault(DefaultGenerator): :class:`.ColumnDefault` is generated automatically whenever the ``default``, ``onupdate`` arguments of - :class:`.Column` are used. A :class:`.ColumnDefault` + :class:`_schema.Column` are used. A :class:`.ColumnDefault` can be passed positionally as well. For example, the following:: @@ -2151,7 +2231,7 @@ class ColumnDefault(DefaultGenerator): string, integer, boolean, or other simple type. The default value will be used as is each time. * a SQL expression, that is one which derives from - :class:`.ColumnElement`. The SQL expression will + :class:`_expression.ColumnElement`. The SQL expression will be rendered into the INSERT or UPDATE statement, or in the case of a primary key column when RETURNING is not used may be @@ -2162,7 +2242,7 @@ class ColumnDefault(DefaultGenerator): zero or one positional arguments. The one-argument form will receive an instance of the :class:`.ExecutionContext`, which provides contextual information as to the current - :class:`.Connection` in use as well as the current + :class:`_engine.Connection` in use as well as the current statement and parameters. """ @@ -2236,8 +2316,9 @@ class Sequence(roles.StatementRole, DefaultGenerator): The :class:`.Sequence` object represents the name and configurational parameters of a database sequence. It also represents - a construct that can be "executed" by a SQLAlchemy :class:`.Engine` - or :class:`.Connection`, rendering the appropriate "next value" function + a construct that can be "executed" by a SQLAlchemy :class:`_engine.Engine` + or :class:`_engine.Connection`, + rendering the appropriate "next value" function for the target database and returning a result. The :class:`.Sequence` is typically associated with a primary key column:: @@ -2248,7 +2329,7 @@ class Sequence(roles.StatementRole, DefaultGenerator): primary_key=True) ) - When CREATE TABLE is emitted for the above :class:`.Table`, if the + When CREATE TABLE is emitted for the above :class:`_schema.Table`, if the target platform supports sequences, a CREATE SEQUENCE statement will be emitted as well. For platforms that don't support sequences, the :class:`.Sequence` construct is ignored. @@ -2348,8 +2429,9 @@ class Sequence(roles.StatementRole, DefaultGenerator): :param schema: Optional schema name for the sequence, if located in a schema other than the default. The rules for selecting the - schema name when a :class:`.MetaData` is also present are the same - as that of :paramref:`.Table.schema`. + schema name when a :class:`_schema.MetaData` + is also present are the same + as that of :paramref:`_schema.Table.schema`. :param cache: optional integer value; number of future values in the sequence which are calculated in advance. Renders the CACHE keyword @@ -2377,27 +2459,32 @@ class Sequence(roles.StatementRole, DefaultGenerator): :param quote_schema: set the quoting preferences for the ``schema`` name. - :param metadata: optional :class:`.MetaData` object which this + :param metadata: optional :class:`_schema.MetaData` object which this :class:`.Sequence` will be associated with. A :class:`.Sequence` - that is associated with a :class:`.MetaData` gains the following + that is associated with a :class:`_schema.MetaData` + gains the following capabilities: - * The :class:`.Sequence` will inherit the :paramref:`.MetaData.schema` - parameter specified to the target :class:`.MetaData`, which + * The :class:`.Sequence` will inherit the + :paramref:`_schema.MetaData.schema` + parameter specified to the target :class:`_schema.MetaData`, which affects the production of CREATE / DROP DDL, if any. * The :meth:`.Sequence.create` and :meth:`.Sequence.drop` methods - automatically use the engine bound to the :class:`.MetaData` + automatically use the engine bound to the :class:`_schema.MetaData` object, if any. - * The :meth:`.MetaData.create_all` and :meth:`.MetaData.drop_all` + * The :meth:`_schema.MetaData.create_all` and + :meth:`_schema.MetaData.drop_all` methods will emit CREATE / DROP for this :class:`.Sequence`, even if the :class:`.Sequence` is not associated with any - :class:`.Table` / :class:`.Column` that's a member of this - :class:`.MetaData`. + :class:`_schema.Table` / :class:`_schema.Column` + that's a member of this + :class:`_schema.MetaData`. The above behaviors can only occur if the :class:`.Sequence` is - explicitly associated with the :class:`.MetaData` via this parameter. + explicitly associated with the :class:`_schema.MetaData` + via this parameter. .. seealso:: @@ -2405,7 +2492,8 @@ class Sequence(roles.StatementRole, DefaultGenerator): :paramref:`.Sequence.metadata` parameter. :param for_update: Indicates this :class:`.Sequence`, when associated - with a :class:`.Column`, should be invoked for UPDATE statements + with a :class:`_schema.Column`, + should be invoked for UPDATE statements on that column's table, rather than for INSERT statements, when no value is otherwise present for that column in the statement. @@ -2555,7 +2643,7 @@ class DefaultClause(FetchedValue): :class:`.DefaultClause` is generated automatically whenever the ``server_default``, ``server_onupdate`` arguments of - :class:`.Column` are used. A :class:`.DefaultClause` + :class:`_schema.Column` are used. A :class:`.DefaultClause` can be passed positionally as well. For example, the following:: @@ -2672,7 +2760,8 @@ class Constraint(DialectKWArgs, SchemaItem): class ColumnCollectionMixin(object): columns = None - """A :class:`.ColumnCollection` of :class:`.Column` objects. + """A :class:`_expression.ColumnCollection` of :class:`_schema.Column` + objects. This collection represents the columns which are referred to by this object. @@ -2799,7 +2888,7 @@ class ColumnCollectionConstraint(ColumnCollectionMixin, Constraint): ) columns = None - """A :class:`.ColumnCollection` representing the set of columns + """A :class:`_expression.ColumnCollection` representing the set of columns for this constraint. """ @@ -2824,7 +2913,8 @@ class ColumnCollectionConstraint(ColumnCollectionMixin, Constraint): """Return True if this constraint contains the given column. Note that this object also contains an attribute ``.columns`` - which is a :class:`.ColumnCollection` of :class:`.Column` objects. + which is a :class:`_expression.ColumnCollection` of + :class:`_schema.Column` objects. """ @@ -2870,7 +2960,8 @@ class CheckConstraint(ColumnCollectionConstraint): :param sqltext: A string containing the constraint definition, which will be used verbatim, or a SQL expression construct. If given as a string, - the object is converted to a :func:`.text` object. If the textual + the object is converted to a :func:`_expression.text` object. + If the textual string includes a colon character, escape this using a backslash:: CheckConstraint(r"foo ~ E'a(?\:b|c)d") @@ -2938,9 +3029,10 @@ class ForeignKeyConstraint(ColumnCollectionConstraint): Defines a single column or composite FOREIGN KEY ... REFERENCES constraint. For a no-frills, single column foreign key, adding a - :class:`.ForeignKey` to the definition of a :class:`.Column` is a + :class:`_schema.ForeignKey` to the definition of a :class:`_schema.Column` + is a shorthand equivalent for an unnamed, single column - :class:`.ForeignKeyConstraint`. + :class:`_schema.ForeignKeyConstraint`. Examples of foreign key configuration are in :ref:`metadata_foreignkeys`. @@ -3000,16 +3092,17 @@ class ForeignKeyConstraint(ColumnCollectionConstraint): have been created, and drop it via an ALTER TABLE statement before the full collection of tables are dropped. - The use of :paramref:`.ForeignKeyConstraint.use_alter` is + The use of :paramref:`_schema.ForeignKeyConstraint.use_alter` is particularly geared towards the case where two or more tables are established within a mutually-dependent foreign key constraint - relationship; however, the :meth:`.MetaData.create_all` and - :meth:`.MetaData.drop_all` methods will perform this resolution + relationship; however, the :meth:`_schema.MetaData.create_all` and + :meth:`_schema.MetaData.drop_all` + methods will perform this resolution automatically, so the flag is normally not needed. .. versionchanged:: 1.0.0 Automatic resolution of foreign key cycles has been added, removing the need to use the - :paramref:`.ForeignKeyConstraint.use_alter` in typical use + :paramref:`_schema.ForeignKeyConstraint.use_alter` in typical use cases. .. seealso:: @@ -3097,15 +3190,16 @@ class ForeignKeyConstraint(ColumnCollectionConstraint): self.elements.append(fk) columns = None - """A :class:`.ColumnCollection` representing the set of columns + """A :class:`_expression.ColumnCollection` representing the set of columns for this constraint. """ elements = None - """A sequence of :class:`.ForeignKey` objects. + """A sequence of :class:`_schema.ForeignKey` objects. - Each :class:`.ForeignKey` represents a single referring column/referred + Each :class:`_schema.ForeignKey` + represents a single referring column/referred column pair. This collection is intended to be read-only. @@ -3126,8 +3220,8 @@ class ForeignKeyConstraint(ColumnCollectionConstraint): @property def referred_table(self): - """The :class:`.Table` object to which this - :class:`.ForeignKeyConstraint` references. + """The :class:`_schema.Table` object to which this + :class:`_schema.ForeignKeyConstraint` references. This is a dynamically calculated attribute which may not be available if the constraint and/or parent table is not yet associated with @@ -3151,11 +3245,11 @@ class ForeignKeyConstraint(ColumnCollectionConstraint): @property def column_keys(self): """Return a list of string keys representing the local - columns in this :class:`.ForeignKeyConstraint`. + columns in this :class:`_schema.ForeignKeyConstraint`. This list is either the original string arguments sent - to the constructor of the :class:`.ForeignKeyConstraint`, - or if the constraint has been initialized with :class:`.Column` + to the constructor of the :class:`_schema.ForeignKeyConstraint`, + or if the constraint has been initialized with :class:`_schema.Column` objects, is the string .key of each element. .. versionadded:: 1.0.0 @@ -3225,9 +3319,9 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint): """A table-level PRIMARY KEY constraint. The :class:`.PrimaryKeyConstraint` object is present automatically - on any :class:`.Table` object; it is assigned a set of - :class:`.Column` objects corresponding to those marked with - the :paramref:`.Column.primary_key` flag:: + on any :class:`_schema.Table` object; it is assigned a set of + :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), @@ -3242,7 +3336,7 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint): primary_key=True, nullable=False) ) - The primary key of a :class:`.Table` can also be specified by using + The primary key of a :class:`_schema.Table` can also be specified by using a :class:`.PrimaryKeyConstraint` object explicitly; in this mode of usage, the "name" of the constraint can also be specified, as well as other options which may be recognized by dialects:: @@ -3275,7 +3369,7 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint): :class:`.PrimaryKeyConstraint`, but the usual style of using ``primary_key=True`` flags is still desirable, an empty :class:`.PrimaryKeyConstraint` may be specified, which will take on the - primary key column collection from the :class:`.Table` based on the + primary key column collection from the :class:`_schema.Table` based on the flags:: my_table = Table('mytable', metadata, @@ -3289,7 +3383,7 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint): .. versionadded:: 0.9.2 an empty :class:`.PrimaryKeyConstraint` may now be specified for the purposes of establishing keyword arguments with the constraint, independently of the specification of "primary key" - columns within the :class:`.Table` itself; columns marked as + columns within the :class:`_schema.Table` itself; columns marked as ``primary_key=True`` will be gathered into the empty constraint's column collection. @@ -3342,7 +3436,7 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint): This is basically like putting a whole new :class:`.PrimaryKeyConstraint` object on the parent - :class:`.Table` object without actually replacing the object. + :class:`_schema.Table` object without actually replacing the object. The ordering of the given list of columns is also maintained; these columns will be appended to the list of columns after any which @@ -3457,7 +3551,7 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem): Index("some_index", sometable.c.name) For a no-frills, single column index, adding - :class:`.Column` also supports ``index=True``:: + :class:`_schema.Column` also supports ``index=True``:: sometable = Table("sometable", metadata, Column("name", String(50), index=True) @@ -3469,13 +3563,15 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem): Functional indexes are supported as well, typically by using the :data:`.func` construct in conjunction with table-bound - :class:`.Column` objects:: + :class:`_schema.Column` objects:: Index("some_index", func.lower(sometable.c.name)) - An :class:`.Index` can also be manually associated with a :class:`.Table`, + An :class:`.Index` can also be manually associated with a + :class:`_schema.Table`, either through inline declaration or using - :meth:`.Table.append_constraint`. When this approach is used, the names + :meth:`_schema.Table.append_constraint`. When this approach is used, + the names of the indexed columns can be specified as strings:: Table("sometable", metadata, @@ -3485,7 +3581,7 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem): ) To support functional or expression-based indexes in this form, the - :func:`.text` construct may be used:: + :func:`_expression.text` construct may be used:: from sqlalchemy import text @@ -3495,9 +3591,10 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem): Index("some_index", text("lower(name)")) ) - .. versionadded:: 0.9.5 the :func:`.text` construct may be used to + .. versionadded:: 0.9.5 the :func:`_expression.text` + construct may be used to specify :class:`.Index` expressions, provided the :class:`.Index` - is explicitly associated with the :class:`.Table`. + is explicitly associated with the :class:`_schema.Table`. .. seealso:: @@ -3525,9 +3622,9 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem): :param \*expressions: Column expressions to include in the index. The expressions - are normally instances of :class:`.Column`, but may also + are normally instances of :class:`_schema.Column`, but may also be arbitrary SQL expressions which ultimately refer to a - :class:`.Column`. + :class:`_schema.Column`. :param unique=False: Keyword only argument; if True, create a unique index. @@ -3535,7 +3632,7 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem): :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:`.Column.quote`. + :paramref:`_schema.Column.quote`. :param info=None: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. @@ -3610,7 +3707,7 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem): .. seealso:: - :meth:`.MetaData.create_all`. + :meth:`_schema.MetaData.create_all`. """ if bind is None: @@ -3625,7 +3722,7 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem): .. seealso:: - :meth:`.MetaData.drop_all`. + :meth:`_schema.MetaData.drop_all`. """ if bind is None: @@ -3646,20 +3743,22 @@ DEFAULT_NAMING_CONVENTION = util.immutabledict({"ix": "ix_%(column_0_label)s"}) class MetaData(SchemaItem): - """A collection of :class:`.Table` objects and their associated schema + """A collection of :class:`_schema.Table` + objects and their associated schema constructs. - Holds a collection of :class:`.Table` objects as well as - an optional binding to an :class:`.Engine` or - :class:`.Connection`. If bound, the :class:`.Table` objects + Holds a collection of :class:`_schema.Table` objects as well as + an optional binding to an :class:`_engine.Engine` or + :class:`_engine.Connection`. If bound, the :class:`_schema.Table` objects in the collection and their columns may participate in implicit SQL execution. - The :class:`.Table` objects themselves are stored in the - :attr:`.MetaData.tables` dictionary. + The :class:`_schema.Table` objects themselves are stored in the + :attr:`_schema.MetaData.tables` dictionary. - :class:`.MetaData` is a thread-safe object for read operations. - Construction of new tables within a single :class:`.MetaData` object, + :class:`_schema.MetaData` is a thread-safe object for read operations. + Construction of new tables within a single :class:`_schema.MetaData` + object, either explicitly or via reflection, may not be completely thread-safe. .. seealso:: @@ -3690,37 +3789,46 @@ class MetaData(SchemaItem): Defaults to False. ``bind`` is required when this option is set. :param schema: - The default schema to use for the :class:`.Table`, + The default schema to use for the :class:`_schema.Table`, :class:`.Sequence`, and potentially other objects associated with - this :class:`.MetaData`. Defaults to ``None``. + this :class:`_schema.MetaData`. Defaults to ``None``. - When this value is set, any :class:`.Table` or :class:`.Sequence` + When this value is set, any :class:`_schema.Table` or + :class:`.Sequence` which specifies ``None`` for the schema parameter will instead - have this schema name defined. To build a :class:`.Table` + have this schema name defined. To build a :class:`_schema.Table` or :class:`.Sequence` that still has ``None`` for the schema even when this parameter is present, use the :attr:`.BLANK_SCHEMA` symbol. .. note:: - As referred above, the :paramref:`.MetaData.schema` parameter + As referred above, the :paramref:`_schema.MetaData.schema` + parameter only refers to the **default value** that will be applied to - the :paramref:`.Table.schema` parameter of an incoming - :class:`.Table` object. It does not refer to how the - :class:`.Table` is catalogued within the :class:`.MetaData`, - which remains consistent vs. a :class:`.MetaData` collection - that does not define this parameter. The :class:`.Table` - within the :class:`.MetaData` will still be keyed based on its + the :paramref:`_schema.Table.schema` parameter of an incoming + :class:`_schema.Table` object. It does not refer to how the + :class:`_schema.Table` is catalogued within the + :class:`_schema.MetaData`, + which remains consistent vs. a :class:`_schema.MetaData` + collection + that does not define this parameter. The + :class:`_schema.Table` + within the :class:`_schema.MetaData` + will still be keyed based on its schema-qualified name, e.g. ``my_metadata.tables["some_schema.my_table"]``. - The current behavior of the :class:`.ForeignKey` object is to + The current behavior of the :class:`_schema.ForeignKey` + object is to circumvent this restriction, where it can locate a table given the table name alone, where the schema will be assumed to be present from this value as specified on the owning - :class:`.MetaData` collection. However, this implies that a + :class:`_schema.MetaData` collection. However, + this implies that a table qualified with BLANK_SCHEMA cannot currently be referred - to by string name from :class:`.ForeignKey`. Other parts of + to by string name from :class:`_schema.ForeignKey`. + Other parts of SQLAlchemy such as Declarative may not have similar behaviors built in, however may do so in a future release, along with a consistent method of referring to a table in BLANK_SCHEMA. @@ -3728,12 +3836,12 @@ class MetaData(SchemaItem): .. seealso:: - :paramref:`.Table.schema` + :paramref:`_schema.Table.schema` :paramref:`.Sequence.schema` :param quote_schema: - Sets the ``quote_schema`` flag for those :class:`.Table`, + Sets the ``quote_schema`` flag for those :class:`_schema.Table`, :class:`.Sequence`, and other objects which make usage of the local ``schema`` name. @@ -3750,7 +3858,8 @@ class MetaData(SchemaItem): The keys of this dictionary may be: * a constraint or Index class, e.g. the :class:`.UniqueConstraint`, - :class:`.ForeignKeyConstraint` class, the :class:`.Index` class + :class:`_schema.ForeignKeyConstraint` class, the :class:`.Index` + class * a string mnemonic for one of the known constraint classes; ``"fk"``, ``"pk"``, ``"ix"``, ``"ck"``, ``"uq"`` for foreign key, @@ -3765,45 +3874,49 @@ class MetaData(SchemaItem): which describe how the name should be composed. The values associated with user-defined "token" keys should be callables of the form ``fn(constraint, table)``, which accepts the constraint/index - object and :class:`.Table` as arguments, returning a string + object and :class:`_schema.Table` as arguments, returning a string result. The built-in names are as follows, some of which may only be available for certain types of constraint: - * ``%(table_name)s`` - the name of the :class:`.Table` object + * ``%(table_name)s`` - the name of the :class:`_schema.Table` + object associated with the constraint. - * ``%(referred_table_name)s`` - the name of the :class:`.Table` + * ``%(referred_table_name)s`` - the name of the + :class:`_schema.Table` object associated with the referencing target of a - :class:`.ForeignKeyConstraint`. + :class:`_schema.ForeignKeyConstraint`. - * ``%(column_0_name)s`` - the name of the :class:`.Column` at + * ``%(column_0_name)s`` - the name of the :class:`_schema.Column` + at index position "0" within the constraint. - * ``%(column_0N_name)s`` - the name of all :class:`.Column` + * ``%(column_0N_name)s`` - the name of all :class:`_schema.Column` objects in order within the constraint, joined without a separator. - * ``%(column_0_N_name)s`` - the name of all :class:`.Column` + * ``%(column_0_N_name)s`` - the name of all + :class:`_schema.Column` objects in order within the constraint, joined with an underscore as a separator. * ``%(column_0_label)s``, ``%(column_0N_label)s``, ``%(column_0_N_label)s`` - the label of either the zeroth - :class:`.Column` or all :class:`.Columns`, separated with + :class:`_schema.Column` or all :class:`.Columns`, separated with or without an underscore * ``%(column_0_key)s``, ``%(column_0N_key)s``, ``%(column_0_N_key)s`` - the key of either the zeroth - :class:`.Column` or all :class:`.Columns`, separated with + :class:`_schema.Column` or all :class:`.Columns`, separated with or without an underscore * ``%(referred_column_0_name)s``, ``%(referred_column_0N_name)s`` ``%(referred_column_0_N_name)s``, ``%(referred_column_0_key)s``, ``%(referred_column_0N_key)s``, ... column tokens which render the names/keys/labels of columns that are referenced - by a :class:`.ForeignKeyConstraint`. + by a :class:`_schema.ForeignKeyConstraint`. * ``%(constraint_name)s`` - a special key that refers to the existing name given to the constraint. When this key is @@ -3843,16 +3956,20 @@ class MetaData(SchemaItem): self.bind = bind tables = None - """A dictionary of :class:`.Table` objects keyed to their name or "table key". - - The exact key is that determined by the :attr:`.Table.key` attribute; - for a table with no :attr:`.Table.schema` attribute, this is the same - as :attr:`.Table.name`. For a table with a schema, it is typically of the + """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:`.MetaData.sorted_tables` + :attr:`_schema.MetaData.sorted_tables` """ @@ -3910,10 +4027,11 @@ class MetaData(SchemaItem): return self._bind is not None def bind(self): - """An :class:`.Engine` or :class:`.Connection` to which this - :class:`.MetaData` is bound. + """An :class:`_engine.Engine` or :class:`_engine.Connection` + to which this + :class:`_schema.MetaData` is bound. - Typically, a :class:`.Engine` is assigned to this attribute + Typically, a :class:`_engine.Engine` is assigned to this attribute so that "implicit execution" may be used, or alternatively as a means of providing engine binding information to an ORM :class:`.Session` object:: @@ -3953,10 +4071,11 @@ class MetaData(SchemaItem): @property def sorted_tables(self): - """Returns a list of :class:`.Table` objects sorted in order of + """Returns a list of :class:`_schema.Table` objects sorted in order of foreign key dependency. - The sorting will place :class:`.Table` objects that have dependencies + 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. @@ -3967,22 +4086,23 @@ class MetaData(SchemaItem): automatic resolution of dependency cycles between tables, which are usually caused by mutually dependent foreign key constraints. To resolve these cycles, either the - :paramref:`.ForeignKeyConstraint.use_alter` parameter may be + :paramref:`_schema.ForeignKeyConstraint.use_alter` + parameter may be applied to those constraints, or use the - :func:`.schema.sort_tables_and_constraints` function which will + :func:`_schema.sort_tables_and_constraints` function which will break out foreign key constraints involved in cycles separately. .. seealso:: - :func:`.schema.sort_tables` + :func:`_schema.sort_tables` - :func:`.schema.sort_tables_and_constraints` + :func:`_schema.sort_tables_and_constraints` - :attr:`.MetaData.tables` + :attr:`_schema.MetaData.tables` - :meth:`.Inspector.get_table_names` + :meth:`_reflection.Inspector.get_table_names` - :meth:`.Inspector.get_sorted_table_and_fkc_names` + :meth:`_reflection.Inspector.get_sorted_table_and_fkc_names` """ @@ -4015,7 +4135,7 @@ class MetaData(SchemaItem): :param schema: Optional, query and reflect tables from an alternate schema. - If None, the schema associated with this :class:`.MetaData` + If None, the schema associated with this :class:`_schema.MetaData` is used, if any. :param views: @@ -4035,35 +4155,41 @@ class MetaData(SchemaItem): 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:`.Table` as - :paramref:`.Table.extend_existing`. + :param extend_existing: Passed along to each :class:`_schema.Table` as + :paramref:`_schema.Table.extend_existing`. .. versionadded:: 0.9.1 - :param autoload_replace: Passed along to each :class:`.Table` as - :paramref:`.Table.autoload_replace`. + :param autoload_replace: Passed along to each :class:`_schema.Table` + as + :paramref:`_schema.Table.autoload_replace`. .. versionadded:: 0.9.1 - :param resolve_fks: if True, reflect :class:`.Table` objects linked - to :class:`.ForeignKey` objects located in each :class:`.Table`. - For :meth:`.MetaData.reflect`, this has the effect of reflecting + :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:`.ForeignKey` objects are not followed to the :class:`.Table` + :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:`.ForeignKey` object will still resolve to its related - :class:`.Table` after the :meth:`.MetaData.reflect` operation is + :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:`.Table.resolve_fks` + :paramref:`_schema.Table.resolve_fks` :param \**dialect_kwargs: Additional keyword arguments not mentioned above are dialect specific, and passed in the form @@ -4073,7 +4199,7 @@ class MetaData(SchemaItem): .. versionadded:: 0.9.2 - Added :paramref:`.MetaData.reflect.**dialect_kwargs` to support - dialect-level reflection options for all :class:`.Table` + dialect-level reflection options for all :class:`_schema.Table` objects reflected. """ @@ -4273,7 +4399,7 @@ class Computed(FetchedValue, SchemaItem): """Defines a generated column, i.e. "GENERATED ALWAYS AS" syntax. The :class:`.Computed` construct is an inline construct added to the - argument list of a :class:`.Column` object:: + argument list of a :class:`_schema.Column` object:: from sqlalchemy import Computed @@ -4299,13 +4425,14 @@ class Computed(FetchedValue, SchemaItem): ) def __init__(self, sqltext, persisted=None): """Construct a GENERATED ALWAYS AS DDL construct to accompany a - :class:`.Column`. + :class:`_schema.Column`. :param sqltext: A string containing the column generation expression, which will be - used verbatim, or a SQL expression construct, such as a :func:`.text` + used verbatim, or a SQL expression construct, such as a + :func:`_expression.text` object. If given as a string, the object is converted to a - :func:`.text` object. + :func:`_expression.text` object. :param persisted: Optional, controls how this column should be persisted by the diff --git a/lib/sqlalchemy/sql/selectable.py b/lib/sqlalchemy/sql/selectable.py index 08a237636..bfe5d80ad 100644 --- a/lib/sqlalchemy/sql/selectable.py +++ b/lib/sqlalchemy/sql/selectable.py @@ -5,7 +5,8 @@ # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php -"""The :class:`.FromClause` class of SQL expression elements, representing +"""The :class:`_expression.FromClause` class of SQL expression elements, +representing SQL tables and derived rowsets. """ @@ -70,12 +71,12 @@ class _OffsetLimitParam(BindParameter): ) def subquery(alias, *args, **kwargs): r"""Return an :class:`.Subquery` object derived - from a :class:`.Select`. + from a :class:`_expression.Select`. :param name: the alias name for the subquery :param \*args, \**kwargs: all other arguments are passed through to the - :func:`~.sql.expression.select` function. + :func:`_expression.select` function. """ return Select(*args, **kwargs).subquery(alias) @@ -107,26 +108,29 @@ class ReturnsRows(roles.ReturnsRowsRole, ClauseElement): def _exported_columns_iterator(self): """An iterator of column objects that represents the "exported" - columns of this :class:`.ReturnsRows`. + columns of this :class:`_expression.ReturnsRows`. This is the same set of columns as are returned by - :meth:`.ReturnsRows.exported_columns` except they are returned + :meth:`_expression.ReturnsRows.exported_columns` + except they are returned as a simple iterator or sequence, rather than as a - :class:`.ColumnCollection` namespace. + :class:`_expression.ColumnCollection` namespace. Subclasses should re-implement this method to bypass the interim - creation of the :class:`.ColumnCollection` if appropriate. + creation of the :class:`_expression.ColumnCollection` if appropriate. """ return iter(self.exported_columns) @property def exported_columns(self): - """A :class:`.ColumnCollection` that represents the "exported" - columns of this :class:`.ReturnsRows`. + """A :class:`_expression.ColumnCollection` + that represents the "exported" + columns of this :class:`_expression.ReturnsRows`. The "exported" columns represent the collection of - :class:`.ColumnElement` expressions that are rendered by this SQL + :class:`_expression.ColumnElement` + expressions that are rendered by this SQL construct. There are primary varieties which are the "FROM clause columns" of a FROM clause, such as a table, join, or subquery, the "SELECTed columns", which are the columns in @@ -137,9 +141,9 @@ class ReturnsRows(roles.ReturnsRowsRole, ClauseElement): .. seealso: - :attr:`.FromClause.exported_columns` + :attr:`_expression.FromClause.exported_columns` - :attr:`.SelectBase.exported_columns` + :attr:`_expression.SelectBase.exported_columns` """ raise NotImplementedError() @@ -162,10 +166,10 @@ class Selectable(ReturnsRows): raise NotImplementedError() def lateral(self, name=None): - """Return a LATERAL alias of this :class:`.Selectable`. + """Return a LATERAL alias of this :class:`expression.Selectable`. - The return value is the :class:`.Lateral` construct also - provided by the top-level :func:`~.expression.lateral` function. + The return value is the :class:`_expression.Lateral` construct also + provided by the top-level :func:`_expression.lateral` function. .. versionadded:: 1.1 @@ -185,34 +189,40 @@ class Selectable(ReturnsRows): @util.preload_module("sqlalchemy.sql.util") def replace_selectable(self, old, alias): """replace all occurrences of FromClause 'old' with the given Alias - object, returning a copy of this :class:`.FromClause`. + object, returning a copy of this :class:`_expression.FromClause`. """ return util.preloaded.sql_util.ClauseAdapter(alias).traverse(self) def corresponding_column(self, column, require_embedded=False): - """Given a :class:`.ColumnElement`, return the exported - :class:`.ColumnElement` object from the - :attr:`.Selectable.exported_columns` - collection of this :class:`.Selectable` which corresponds to that - original :class:`.ColumnElement` via a common ancestor + """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:`.ColumnElement` to be matched + :param column: the target :class:`_expression.ColumnElement` + to be matched :param require_embedded: only return corresponding columns for - the given :class:`.ColumnElement`, if the given - :class:`.ColumnElement` is actually present within a sub-element - of this :class:`.Selectable`. Normally the column will match if + 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:`.Selectable`. + columns of this :class:`expression.Selectable`. .. seealso:: - :attr:`.Selectable.exported_columns` - the - :class:`.ColumnCollection` that is used for the operation + :attr:`expression.Selectable.exported_columns` - the + :class:`_expression.ColumnCollection` + that is used for the operation - :meth:`.ColumnCollection.corresponding_column` - implementation + :meth:`_expression.ColumnCollection.corresponding_column` + - implementation method. """ @@ -232,7 +242,7 @@ class HasPrefixes(object): @_generative @_document_text_coercion( "expr", - ":meth:`.HasPrefixes.prefix_with`", + ":meth:`_expression.HasPrefixes.prefix_with`", ":paramref:`.HasPrefixes.prefix_with.*expr`", ) def prefix_with(self, *expr, **kw): @@ -251,9 +261,10 @@ class HasPrefixes(object): "/*+ BKA(t1) */", dialect="mysql") Multiple prefixes can be specified by multiple calls - to :meth:`.prefix_with`. + to :meth:`_expression.HasPrefixes.prefix_with`. - :param \*expr: textual or :class:`.ClauseElement` construct which + :param \*expr: textual or :class:`_expression.ClauseElement` + construct which will be rendered following the INSERT, UPDATE, or DELETE keyword. :param \**kw: A single keyword 'dialect' is accepted. This is an @@ -287,7 +298,7 @@ class HasSuffixes(object): @_generative @_document_text_coercion( "expr", - ":meth:`.HasSuffixes.suffix_with`", + ":meth:`_expression.HasSuffixes.suffix_with`", ":paramref:`.HasSuffixes.suffix_with.*expr`", ) def suffix_with(self, *expr, **kw): @@ -302,9 +313,10 @@ class HasSuffixes(object): "cycle empno set y_cycle to 1 default 0", dialect="oracle") Multiple suffixes can be specified by multiple calls - to :meth:`.suffix_with`. + to :meth:`_expression.HasSuffixes.suffix_with`. - :param \*expr: textual or :class:`.ClauseElement` construct which + :param \*expr: textual or :class:`_expression.ClauseElement` + construct which will be rendered following the target clause. :param \**kw: A single keyword 'dialect' is accepted. This is an optional string dialect name which will @@ -331,17 +343,19 @@ class FromClause(roles.AnonymizedFromClauseRole, Selectable): """Represent an element that can be used within the ``FROM`` clause of a ``SELECT`` statement. - The most common forms of :class:`.FromClause` are the - :class:`.Table` and the :func:`~.sql.expression.select` constructs. Key - features common to all :class:`.FromClause` objects include: + The most common forms of :class:`_expression.FromClause` are the + :class:`_schema.Table` and the :func:`_expression.select` constructs. Key + features common to all :class:`_expression.FromClause` objects include: * a :attr:`.c` collection, which provides per-name access to a collection - of :class:`.ColumnElement` objects. + of :class:`_expression.ColumnElement` objects. * a :attr:`.primary_key` attribute, which is a collection of all those - :class:`.ColumnElement` objects that indicate the ``primary_key`` flag. + :class:`_expression.ColumnElement` + objects that indicate the ``primary_key`` flag. * Methods to generate various derivations of a "from" clause, including - :meth:`.FromClause.alias`, :meth:`.FromClause.join`, - :meth:`.FromClause.select`. + :meth:`_expression.FromClause.alias`, + :meth:`_expression.FromClause.join`, + :meth:`_expression.FromClause.select`. """ @@ -351,11 +365,11 @@ class FromClause(roles.AnonymizedFromClauseRole, Selectable): _hide_froms = [] schema = None - """Define the 'schema' attribute for this :class:`.FromClause`. + """Define the 'schema' attribute for this :class:`_expression.FromClause`. This is typically ``None`` for most objects except that of - :class:`.Table`, where it is taken as the value of the - :paramref:`.Table.schema` argument. + :class:`_schema.Table`, where it is taken as the value of the + :paramref:`_schema.Table.schema` argument. """ @@ -366,11 +380,11 @@ class FromClause(roles.AnonymizedFromClauseRole, Selectable): _use_schema_map = False def select(self, whereclause=None, **params): - """return a SELECT of this :class:`.FromClause`. + """return a SELECT of this :class:`_expression.FromClause`. .. seealso:: - :func:`~.sql.expression.select` - general purpose + :func:`_expression.select` - general purpose method which allows for arbitrary column lists. """ @@ -378,7 +392,8 @@ class FromClause(roles.AnonymizedFromClauseRole, Selectable): return Select([self], whereclause, **params) def join(self, right, onclause=None, isouter=False, full=False): - """Return a :class:`.Join` from this :class:`.FromClause` + """Return a :class:`_expression.Join` from this + :class:`_expression.FromClause` to another :class:`FromClause`. E.g.:: @@ -395,12 +410,14 @@ class FromClause(roles.AnonymizedFromClauseRole, Selectable): JOIN address ON user.id = address.user_id :param right: the right side of the join; this is any - :class:`.FromClause` object such as a :class:`.Table` object, and + :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:`.FromClause.join` will attempt to + 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. @@ -412,16 +429,17 @@ class FromClause(roles.AnonymizedFromClauseRole, Selectable): .. seealso:: - :func:`.join` - standalone function + :func:`_expression.join` - standalone function - :class:`.Join` - the type of object produced + :class:`_expression.Join` - the type of object produced """ return Join(self, right, onclause, isouter, full) def outerjoin(self, right, onclause=None, full=False): - """Return a :class:`.Join` from this :class:`.FromClause` + """Return a :class:`_expression.Join` from this + :class:`_expression.FromClause` to another :class:`FromClause`, with the "isouter" flag set to True. @@ -440,12 +458,14 @@ class FromClause(roles.AnonymizedFromClauseRole, Selectable): isouter=True) :param right: the right side of the join; this is any - :class:`.FromClause` object such as a :class:`.Table` object, and + :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:`.FromClause.join` will attempt to + 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 @@ -455,45 +475,47 @@ class FromClause(roles.AnonymizedFromClauseRole, Selectable): .. seealso:: - :meth:`.FromClause.join` + :meth:`_expression.FromClause.join` - :class:`.Join` + :class:`_expression.Join` """ return Join(self, right, onclause, True, full) def alias(self, name=None, flat=False): - """return an alias of this :class:`.FromClause`. + """return an alias of this :class:`_expression.FromClause`. E.g.:: a2 = some_table.alias('a2') - The above code creates an :class:`.Alias` object which can be used + The above code creates an :class:`_expression.Alias` + object which can be used as a FROM clause in any SELECT statement. .. seealso:: :ref:`core_tutorial_aliases` - :func:`~.expression.alias` + :func:`_expression.alias` """ return Alias._construct(self, name) def tablesample(self, sampling, name=None, seed=None): - """Return a TABLESAMPLE alias of this :class:`.FromClause`. + """Return a TABLESAMPLE alias of this :class:`_expression.FromClause`. - The return value is the :class:`.TableSample` construct also - provided by the top-level :func:`~.expression.tablesample` function. + The return value is the :class:`_expression.TableSample` + construct also + provided by the top-level :func:`_expression.tablesample` function. .. versionadded:: 1.1 .. seealso:: - :func:`~.expression.tablesample` - usage guidelines and parameters + :func:`_expression.tablesample` - usage guidelines and parameters """ return TableSample._construct(self, sampling, name, seed) @@ -536,19 +558,21 @@ class FromClause(roles.AnonymizedFromClauseRole, Selectable): @property def exported_columns(self): - """A :class:`.ColumnCollection` that represents the "exported" - columns of this :class:`.Selectable`. + """A :class:`_expression.ColumnCollection` + that represents the "exported" + columns of this :class:`expression.Selectable`. - The "exported" columns for a :class:`.FromClause` object are synonymous - with the :attr:`.FromClause.columns` collection. + The "exported" columns for a :class:`_expression.FromClause` + object are synonymous + with the :attr:`_expression.FromClause.columns` collection. .. versionadded:: 1.4 .. seealso: - :attr:`.Selectable.exported_columns` + :attr:`expression.Selectable.exported_columns` - :attr:`.SelectBase.exported_columns` + :attr:`_expression.SelectBase.exported_columns` """ @@ -556,8 +580,9 @@ class FromClause(roles.AnonymizedFromClauseRole, Selectable): @util.memoized_property def columns(self): - """A named-based collection of :class:`.ColumnElement` objects - maintained by this :class:`.FromClause`. + """A named-based collection of :class:`_expression.ColumnElement` + objects + maintained by this :class:`_expression.FromClause`. The :attr:`.columns`, or :attr:`.c` collection, is the gateway to the construction of SQL expressions using table-bound or @@ -663,18 +688,22 @@ class FromClause(roles.AnonymizedFromClauseRole, Selectable): class Join(FromClause): - """represent a ``JOIN`` construct between two :class:`.FromClause` + """represent a ``JOIN`` construct between two + :class:`_expression.FromClause` elements. - The public constructor function for :class:`.Join` is the module-level - :func:`.join()` function, as well as the :meth:`.FromClause.join` method - of any :class:`.FromClause` (e.g. such as :class:`.Table`). + The public constructor function for :class:`_expression.Join` + is the module-level + :func:`_expression.join()` function, as well as the + :meth:`_expression.FromClause.join` method + of any :class:`_expression.FromClause` (e.g. such as + :class:`_schema.Table`). .. seealso:: - :func:`.join` + :func:`_expression.join` - :meth:`.FromClause.join` + :meth:`_expression.FromClause.join` """ @@ -691,11 +720,11 @@ class Join(FromClause): _is_join = True def __init__(self, left, right, onclause=None, isouter=False, full=False): - """Construct a new :class:`.Join`. + """Construct a new :class:`_expression.Join`. - The usual entrypoint here is the :func:`~.expression.join` - function or the :meth:`.FromClause.join` method of any - :class:`.FromClause` object. + The usual entrypoint here is the :func:`_expression.join` + function or the :meth:`_expression.FromClause.join` method of any + :class:`_expression.FromClause` object. """ self.left = coercions.expect(roles.FromClauseRole, left) @@ -713,11 +742,11 @@ class Join(FromClause): def _create_outerjoin(cls, left, right, onclause=None, full=False): """Return an ``OUTER JOIN`` clause element. - The returned object is an instance of :class:`.Join`. + The returned object is an instance of :class:`_expression.Join`. Similar functionality is also available via the - :meth:`~.FromClause.outerjoin()` method on any - :class:`.FromClause`. + :meth:`_expression.FromClause.outerjoin()` method on any + :class:`_expression.FromClause`. :param left: The left side of the join. @@ -727,9 +756,10 @@ class Join(FromClause): derived from foreign key relationships established between left and right otherwise. - To chain joins together, use the :meth:`.FromClause.join` or - :meth:`.FromClause.outerjoin` methods on the resulting - :class:`.Join` object. + To chain joins together, use the :meth:`_expression.FromClause.join` + or + :meth:`_expression.FromClause.outerjoin` methods on the resulting + :class:`_expression.Join` object. """ return cls(left, right, onclause, isouter=True, full=full) @@ -738,7 +768,8 @@ class Join(FromClause): def _create_join( cls, left, right, onclause=None, isouter=False, full=False ): - """Produce a :class:`.Join` object, given two :class:`.FromClause` + """Produce a :class:`_expression.Join` object, given two + :class:`_expression.FromClause` expressions. E.g.:: @@ -753,18 +784,21 @@ class Join(FromClause): JOIN address ON user.id = address.user_id Similar functionality is available given any - :class:`.FromClause` object (e.g. such as a :class:`.Table`) using - the :meth:`.FromClause.join` method. + :class:`_expression.FromClause` object (e.g. such as a + :class:`_schema.Table`) using + the :meth:`_expression.FromClause.join` method. :param left: The left side of the join. :param right: the right side of the join; this is any - :class:`.FromClause` object such as a :class:`.Table` object, and + :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:`.FromClause.join` will attempt to + 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. @@ -775,9 +809,10 @@ class Join(FromClause): .. seealso:: - :meth:`.FromClause.join` - method form, based on a given left side + :meth:`_expression.FromClause.join` - method form, + based on a given left side - :class:`.Join` - the type of object produced + :class:`_expression.Join` - the type of object produced """ @@ -989,9 +1024,11 @@ class Join(FromClause): ) def select(self, whereclause=None, **kwargs): - r"""Create a :class:`.Select` from this :class:`.Join`. + r"""Create a :class:`_expression.Select` from this + :class:`_expression.Join`. - The equivalent long-hand form, given a :class:`.Join` object + The equivalent long-hand form, given a :class:`_expression.Join` + object ``j``, is:: from sqlalchemy import select @@ -1020,11 +1057,11 @@ class Join(FromClause): @util.preload_module("sqlalchemy.sql.util") def alias(self, name=None, flat=False): - r"""return an alias of this :class:`.Join`. + r"""return an alias of this :class:`_expression.Join`. The default behavior here is to first produce a SELECT - construct from this :class:`.Join`, then to produce an - :class:`.Alias` from that. So given a join of the form:: + construct from this :class:`_expression.Join`, then to produce an + :class:`_expression.Alias` from that. So given a join of the form:: j = table_a.join(table_b, table_a.c.id == table_b.c.a_id) @@ -1040,7 +1077,8 @@ class Join(FromClause): FROM table_a JOIN table_b ON table_a.id = table_b.a_id) AS anon_1 - The equivalent long-hand form, given a :class:`.Join` object + The equivalent long-hand form, given a :class:`_expression.Join` + object ``j``, is:: from sqlalchemy import select, alias @@ -1052,20 +1090,22 @@ class Join(FromClause): name=name ) - The selectable produced by :meth:`.Join.alias` features the same + The selectable produced by :meth:`_expression.Join.alias` + features the same columns as that of the two individual selectables presented under a single name - the individual columns are "auto-labeled", meaning - the ``.c.`` collection of the resulting :class:`.Alias` represents + the ``.c.`` collection of the resulting :class:`_expression.Alias` + represents the names of the individual columns using a ``<tablename>_<columname>`` scheme:: j.c.table_a_id j.c.table_b_a_id - :meth:`.Join.alias` also features an alternate + :meth:`_expression.Join.alias` also features an alternate option for aliasing joins which produces no enclosing SELECT and does not normally apply labels to the column names. The - ``flat=True`` option will call :meth:`.FromClause.alias` + ``flat=True`` option will call :meth:`_expression.FromClause.alias` against the left and right sides individually. Using this option, no new ``SELECT`` is produced; we instead, from a construct as below:: @@ -1094,15 +1134,16 @@ class Join(FromClause): ON table_b_1.id = table_c_1.b_id ) ON table_a_1.id = table_b_1.a_id - The standalone :func:`~.expression.alias` function as well as the - base :meth:`.FromClause.alias` method also support the ``flat=True`` + The standalone :func:`_expression.alias` function as well as the + base :meth:`_expression.FromClause.alias` + method also support the ``flat=True`` argument as a no-op, so that the argument can be passed to the ``alias()`` method of any selectable. :param name: name given to the alias. :param flat: if True, produce an alias of the left and right - sides of this :class:`.Join` and return the join of those + sides of this :class:`_expression.Join` and return the join of those two selectables. This produces join expression that does not include an enclosing SELECT. @@ -1110,7 +1151,7 @@ class Join(FromClause): :ref:`core_tutorial_aliases` - :func:`~.expression.alias` + :func:`_expression.alias` """ sqlutil = util.preloaded.sql_util @@ -1260,13 +1301,14 @@ class Alias(AliasedReturnsRows): sub-select within a SQL statement using the ``AS`` keyword (or without the keyword on certain databases such as Oracle). - This object is constructed from the :func:`~.expression.alias` module - level function as well as the :meth:`.FromClause.alias` method available - on all :class:`.FromClause` subclasses. + This object is constructed from the :func:`_expression.alias` module + level function as well as the :meth:`_expression.FromClause.alias` + method available + on all :class:`_expression.FromClause` subclasses. .. seealso:: - :meth:`.FromClause.alias` + :meth:`_expression.FromClause.alias` """ @@ -1274,24 +1316,28 @@ class Alias(AliasedReturnsRows): @classmethod def _factory(cls, selectable, name=None, flat=False): - """Return an :class:`.Alias` object. + """Return an :class:`_expression.Alias` object. - An :class:`.Alias` represents any :class:`.FromClause` + An :class:`_expression.Alias` represents any + :class:`_expression.FromClause` with an alternate name assigned within SQL, typically using the ``AS`` clause when generated, e.g. ``SELECT * FROM table AS aliasname``. - Similar functionality is available via the :meth:`~.FromClause.alias` - method available on all :class:`.FromClause` subclasses. In terms of - a SELECT object as generated from the :func:`~.sql.expression.select` - function, the :meth:`.SelectBase.alias` method returns an - :class:`.Alias` or similar object which represents a named, + Similar functionality is available via the + :meth:`_expression.FromClause.alias` + method available on all :class:`_expression.FromClause` subclasses. + In terms of + a SELECT object as generated from the :func:`_expression.select` + function, the :meth:`_expression.SelectBase.alias` method returns an + :class:`_expression.Alias` or similar object which represents a named, parenthesized subquery. - When an :class:`.Alias` is created from a :class:`.Table` object, + When an :class:`_expression.Alias` is created from a + :class:`_schema.Table` object, this has the effect of the table being rendered as ``tablename AS aliasname`` in a SELECT statement. - For :func:`~.sql.expression.select` objects, the effect is that of + For :func:`_expression.select` objects, the effect is that of creating a named subquery, i.e. ``(select ...) AS aliasname``. The ``name`` parameter is optional, and provides the name @@ -1302,7 +1348,7 @@ class Alias(AliasedReturnsRows): same name for each successive compilation of the same statement object. - :param selectable: any :class:`.FromClause` subclass, + :param selectable: any :class:`_expression.FromClause` subclass, such as a table, select statement, etc. :param name: string name to be assigned as the alias. @@ -1310,7 +1356,8 @@ class Alias(AliasedReturnsRows): at compile time. :param flat: Will be passed through to if the given selectable - is an instance of :class:`.Join` - see :meth:`.Join.alias` + is an instance of :class:`_expression.Join` - see + :meth:`_expression.Join.alias` for details. """ @@ -1322,9 +1369,10 @@ class Alias(AliasedReturnsRows): class Lateral(AliasedReturnsRows): """Represent a LATERAL subquery. - This object is constructed from the :func:`~.expression.lateral` module - level function as well as the :meth:`.FromClause.lateral` method available - on all :class:`.FromClause` subclasses. + This object is constructed from the :func:`_expression.lateral` module + level function as well as the :meth:`_expression.FromClause.lateral` + method available + on all :class:`_expression.FromClause` subclasses. While LATERAL is part of the SQL standard, currently only more recent PostgreSQL versions provide support for this keyword. @@ -1342,9 +1390,10 @@ class Lateral(AliasedReturnsRows): @classmethod def _factory(cls, selectable, name=None): - """Return a :class:`.Lateral` object. + """Return a :class:`_expression.Lateral` object. - :class:`.Lateral` is an :class:`.Alias` subclass that represents + :class:`_expression.Lateral` is an :class:`_expression.Alias` + subclass that represents a subquery with the LATERAL keyword applied to it. The special behavior of a LATERAL subquery is that it appears in the @@ -1368,15 +1417,16 @@ class Lateral(AliasedReturnsRows): class TableSample(AliasedReturnsRows): """Represent a TABLESAMPLE clause. - This object is constructed from the :func:`~.expression.tablesample` module - level function as well as the :meth:`.FromClause.tablesample` method - available on all :class:`.FromClause` subclasses. + This object is constructed from the :func:`_expression.tablesample` module + level function as well as the :meth:`_expression.FromClause.tablesample` + method + available on all :class:`_expression.FromClause` subclasses. .. versionadded:: 1.1 .. seealso:: - :func:`~.expression.tablesample` + :func:`_expression.tablesample` """ @@ -1389,13 +1439,15 @@ class TableSample(AliasedReturnsRows): @classmethod def _factory(cls, selectable, sampling, name=None, seed=None): - """Return a :class:`.TableSample` object. + """Return a :class:`_expression.TableSample` object. - :class:`.TableSample` is an :class:`.Alias` subclass that represents + :class:`_expression.TableSample` is an :class:`_expression.Alias` + subclass that represents a table with the TABLESAMPLE clause applied to it. - :func:`~.expression.tablesample` - is also available from the :class:`.FromClause` class via the - :meth:`.FromClause.tablesample` method. + :func:`_expression.tablesample` + is also available from the :class:`_expression.FromClause` + class via the + :meth:`_expression.FromClause.tablesample` method. The TABLESAMPLE clause allows selecting a randomly selected approximate percentage of rows from a table. It supports multiple sampling methods, @@ -1421,7 +1473,7 @@ class TableSample(AliasedReturnsRows): .. versionadded:: 1.1 :param sampling: a ``float`` percentage between 0 and 100 or - :class:`.functions.Function`. + :class:`_functions.Function`. :param name: optional alias name @@ -1450,8 +1502,8 @@ class TableSample(AliasedReturnsRows): class CTE(Generative, HasPrefixes, HasSuffixes, AliasedReturnsRows): """Represent a Common Table Expression. - The :class:`.CTE` object is obtained using the - :meth:`.SelectBase.cte` method from any selectable. + The :class:`_expression.CTE` object is obtained using the + :meth:`_expression.SelectBase.cte` method from any selectable. See that method for complete examples. """ @@ -1471,9 +1523,10 @@ class CTE(Generative, HasPrefixes, HasSuffixes, AliasedReturnsRows): @classmethod def _factory(cls, selectable, name=None, recursive=False): - r"""Return a new :class:`.CTE`, or Common Table Expression instance. + r"""Return a new :class:`_expression.CTE`, + or Common Table Expression instance. - Please see :meth:`.HasCte.cte` for detail on CTE usage. + Please see :meth:`_expression.HasCTE.cte` for detail on CTE usage. """ return coercions.expect(roles.HasCTERole, selectable).cte( @@ -1500,16 +1553,17 @@ class CTE(Generative, HasPrefixes, HasSuffixes, AliasedReturnsRows): super(CTE, self)._init(selectable, name=name) def alias(self, name=None, flat=False): - """Return an :class:`.Alias` of this :class:`.CTE`. + """Return an :class:`_expression.Alias` of this + :class:`_expression.CTE`. This method is a CTE-specific specialization of the - :class:`.FromClause.alias` method. + :class:`_expression.FromClause.alias` method. .. seealso:: :ref:`core_tutorial_aliases` - :func:`~.expression.alias` + :func:`_expression.alias` """ return CTE._construct( @@ -1550,7 +1604,8 @@ class HasCTE(roles.HasCTERole): """ def cte(self, name=None, recursive=False): - r"""Return a new :class:`.CTE`, or Common Table Expression instance. + r"""Return a new :class:`_expression.CTE`, + or Common Table Expression instance. Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along @@ -1567,13 +1622,14 @@ class HasCTE(roles.HasCTERole): .. versionchanged:: 1.1 Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE. - SQLAlchemy detects :class:`.CTE` objects, which are treated - similarly to :class:`.Alias` objects, as special elements + SQLAlchemy detects :class:`_expression.CTE` objects, which are treated + similarly to :class:`_expression.Alias` objects, as special elements to be delivered to the FROM clause of the statement as well as to a WITH clause at the top of the statement. For special prefixes such as PostgreSQL "MATERIALIZED" and - "NOT MATERIALIZED", the :meth:`.CTE.prefix_with` method may be + "NOT MATERIALIZED", the :meth:`_expression.CTE.prefix_with` + method may be used to establish these. .. versionchanged:: 1.3.13 Added support for prefixes. @@ -1711,7 +1767,7 @@ class HasCTE(roles.HasCTERole): .. seealso:: :meth:`.orm.query.Query.cte` - ORM version of - :meth:`.HasCTE.cte`. + :meth:`_expression.HasCTE.cte`. """ return CTE._construct(self, name=name, recursive=recursive) @@ -1721,18 +1777,24 @@ class Subquery(AliasedReturnsRows): """Represent a subquery of a SELECT. A :class:`.Subquery` is created by invoking the - :meth:`.SelectBase.subquery` method, or for convenience the - :class:`.SelectBase.alias` method, on any :class:`.SelectBase` subclass - which includes :class:`.Select`, :class:`.CompoundSelect`, and - :class:`.TextualSelect`. As rendered in a FROM clause, it represents the + :meth:`_expression.SelectBase.subquery` method, or for convenience the + :class:`_expression.SelectBase.alias` method, on any + :class:`_expression.SelectBase` subclass + which includes :class:`_expression.Select`, + :class:`_expression.CompoundSelect`, and + :class:`_expression.TextualSelect`. As rendered in a FROM clause, + it represents the body of the SELECT statement inside of parenthesis, followed by the usual "AS <somename>" that defines all "alias" objects. - The :class:`.Subquery` object is very similar to the :class:`.Alias` + The :class:`.Subquery` object is very similar to the + :class:`_expression.Alias` object and can be used in an equivalent way. The difference between - :class:`.Alias` and :class:`.Subquery` is that :class:`.Alias` always - contains a :class:`.FromClause` object whereas :class:`.Subquery` - always contains a :class:`.SelectBase` object. + :class:`_expression.Alias` and :class:`.Subquery` is that + :class:`_expression.Alias` always + contains a :class:`_expression.FromClause` object whereas + :class:`.Subquery` + always contains a :class:`_expression.SelectBase` object. .. versionadded:: 1.4 The :class:`.Subquery` class was added which now serves the purpose of providing an aliased version of a SELECT @@ -1758,10 +1820,10 @@ class Subquery(AliasedReturnsRows): "The :meth:`.Subquery.as_scalar` method, which was previously " "``Alias.as_scalar()`` prior to version 1.4, is deprecated and " "will be removed in a future release; Please use the " - ":meth:`.Select.scalar_subquery` method of the " - ":func:`~.sql.expression.select` " + ":meth:`_expression.Select.scalar_subquery` method of the " + ":func:`_expression.select` " "construct before constructing a subquery object, or with the ORM " - "use the :meth:`.Query.scalar_subquery` method.", + "use the :meth:`_query.Query.scalar_subquery` method.", ) def as_scalar(self): return self.element._set_label_style( @@ -1818,7 +1880,7 @@ class TableClause(Immutable, FromClause): This is a lightweight table object that has only a name and a collection of columns, which are typically produced - by the :func:`.expression.column` function:: + by the :func:`_expression.column` function:: from sqlalchemy import table, column @@ -1828,16 +1890,17 @@ class TableClause(Immutable, FromClause): column("description"), ) - The :class:`.TableClause` construct serves as the base for - the more commonly used :class:`~.schema.Table` object, providing - the usual set of :class:`~.expression.FromClause` services including + The :class:`_expression.TableClause` construct serves as the base for + the more commonly used :class:`_schema.Table` object, providing + the usual set of :class:`_expression.FromClause` services including the ``.c.`` collection and statement generation methods. It does **not** provide all the additional schema-level services - of :class:`~.schema.Table`, including constraints, references to other - tables, or support for :class:`.MetaData`-level services. It's useful + of :class:`_schema.Table`, including constraints, references to other + tables, or support for :class:`_schema.MetaData`-level services. + It's useful on its own as an ad-hoc construct used to generate quick SQL - statements when a more fully fledged :class:`~.schema.Table` + statements when a more fully fledged :class:`_schema.Table` is not on hand. """ @@ -1855,27 +1918,29 @@ class TableClause(Immutable, FromClause): named_with_column = True implicit_returning = False - """:class:`.TableClause` doesn't support having a primary key or column + """:class:`_expression.TableClause` + doesn't support having a primary key or column -level defaults, so implicit returning doesn't apply.""" _autoincrement_column = None """No PK or default support so no autoincrement column.""" def __init__(self, name, *columns): - """Produce a new :class:`.TableClause`. + """Produce a new :class:`_expression.TableClause`. - The object returned is an instance of :class:`.TableClause`, which + The object returned is an instance of :class:`_expression.TableClause` + , which represents the "syntactical" portion of the schema-level - :class:`~.schema.Table` object. + :class:`_schema.Table` object. It may be used to construct lightweight table constructs. - .. versionchanged:: 1.0.0 :func:`.expression.table` can now + .. versionchanged:: 1.0.0 :func:`_expression.table` can now be imported from the plain ``sqlalchemy`` namespace like any other SQL element. :param name: Name of the table. - :param columns: A collection of :func:`.expression.column` constructs. + :param columns: A collection of :func:`_expression.column` constructs. """ @@ -1906,14 +1971,14 @@ class TableClause(Immutable, FromClause): @util.preload_module("sqlalchemy.sql.dml") def insert(self, values=None, inline=False, **kwargs): - """Generate an :func:`~.sql.expression.insert` construct against this - :class:`.TableClause`. + """Generate an :func:`_expression.insert` construct against this + :class:`_expression.TableClause`. E.g.:: table.insert().values(name='foo') - See :func:`~.sql.expression.insert` for argument and usage information. + See :func:`_expression.insert` for argument and usage information. """ return util.preloaded.sql_dml.Insert( @@ -1922,14 +1987,14 @@ class TableClause(Immutable, FromClause): @util.preload_module("sqlalchemy.sql.dml") def update(self, whereclause=None, values=None, inline=False, **kwargs): - """Generate an :func:`.update` construct against this - :class:`.TableClause`. + """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:`.update` for argument and usage information. + See :func:`_expression.update` for argument and usage information. """ return util.preloaded.sql_dml.Update( @@ -1942,14 +2007,14 @@ class TableClause(Immutable, FromClause): @util.preload_module("sqlalchemy.sql.dml") def delete(self, whereclause=None, **kwargs): - """Generate a :func:`.delete` construct against this - :class:`.TableClause`. + """Generate a :func:`_expression.delete` construct against this + :class:`_expression.TableClause`. E.g.:: table.delete().where(table.c.id==7) - See :func:`.delete` for argument and usage information. + See :func:`_expression.delete` for argument and usage information. """ return util.preloaded.sql_dml.Delete(self, whereclause, **kwargs) @@ -1991,7 +2056,8 @@ class ForUpdateArg(ClauseElement): skip_locked=False, key_share=False, ): - """Represents arguments specified to :meth:`.Select.for_update`. + """Represents arguments specified to + :meth:`_expression.Select.for_update`. """ @@ -2012,8 +2078,8 @@ class Values(Generative, FromClause): """represent a ``VALUES`` construct that can be used as a FROM element in a statement. - The :class:`.Values` object is created from the - :func:`~.sql.expression.values` function. + The :class:`_expression.Values` object is created from the + :func:`_expression.values` function. .. versionadded:: 1.4 @@ -2032,13 +2098,15 @@ class Values(Generative, FromClause): ] def __init__(self, *columns, **kw): - r"""Construct a :class:`.Values` construct. + r"""Construct a :class:`_expression.Values` construct. The column expressions and the actual data for - :class:`.Values` are given in two separate steps. The + :class:`_expression.Values` are given in two separate steps. The constructor receives the column expressions typically as - :func:`.column` constructs, and the data is then passed via the - :meth:`.Values.data` method as a list, which can be called multiple + :func:`_expression.column` constructs, + and the data is then passed via the + :meth:`_expression.Values.data` method as a list, + which can be called multiple times to add more data, e.g.:: from sqlalchemy import column @@ -2053,7 +2121,7 @@ class Values(Generative, FromClause): ) :param \*columns: column expressions, typically composed using - :func:`.column` objects. + :func:`_expression.column` objects. :param name: the name for this VALUES construct. If omitted, the VALUES construct will be unnamed in a SQL expression. Different @@ -2073,17 +2141,18 @@ class Values(Generative, FromClause): @_generative def alias(self, name, **kw): - """Return a new :class:`.Values` construct that is a copy of this + """Return a new :class:`_expression.Values` + construct that is a copy of this one with the given name. This method is a VALUES-specific specialization of the - :class:`.FromClause.alias` method. + :class:`_expression.FromClause.alias` method. .. seealso:: :ref:`core_tutorial_aliases` - :func:`~.expression.alias` + :func:`_expression.alias` """ self.name = name @@ -2091,12 +2160,13 @@ class Values(Generative, FromClause): @_generative def lateral(self, name=None): - """Return a new :class:`.Values` with the lateral flag set, so that + """Return a new :class:`_expression.Values` with the lateral flag set, + so that it renders as LATERAL. .. seealso:: - :func:`~.expression.lateral` + :func:`_expression.lateral` """ self._is_lateral = True @@ -2105,7 +2175,8 @@ class Values(Generative, FromClause): @_generative def data(self, values): - """Return a new :class:`.Values` construct, adding the given data + """Return a new :class:`_expression.Values` construct, + adding the given data to the data list. E.g.:: @@ -2113,7 +2184,8 @@ class Values(Generative, FromClause): my_values = my_values.data([(1, 'value 1'), (2, 'value2')]) :param values: a sequence (i.e. list) of tuples that map to the - column expressions given in the :class:`.Values` constructor. + column expressions given in the :class:`_expression.Values` + constructor. """ @@ -2142,8 +2214,9 @@ class SelectBase( """Base class for SELECT statements. - This includes :class:`.Select`, :class:`.CompoundSelect` and - :class:`.TextualSelect`. + This includes :class:`_expression.Select`, + :class:`_expression.CompoundSelect` and + :class:`_expression.TextualSelect`. """ @@ -2159,11 +2232,14 @@ class SelectBase( @property def selected_columns(self): - """A :class:`.ColumnCollection` representing the columns that + """A :class:`_expression.ColumnCollection` + representing the columns that this SELECT statement or similar construct returns in its result set. - This collection differs from the :attr:`.FromClause.columns` collection - of a :class:`.FromClause` in that the columns within this collection + This collection differs from the + :attr:`_expression.FromClause.columns` collection + of a :class:`_expression.FromClause` + in that the columns within this collection cannot be directly nested inside another SELECT statement; a subquery must be applied first which provides for the necessary parenthesization required by SQL. @@ -2175,19 +2251,21 @@ class SelectBase( @property def exported_columns(self): - """A :class:`.ColumnCollection` that represents the "exported" - columns of this :class:`.Selectable`. + """A :class:`_expression.ColumnCollection` + that represents the "exported" + columns of this :class:`expression.Selectable`. - The "exported" columns for a :class:`.SelectBase` object are synonymous - with the :attr:`.SelectBase.selected_columns` collection. + The "exported" columns for a :class:`_expression.SelectBase` + object are synonymous + with the :attr:`_expression.SelectBase.selected_columns` collection. .. versionadded:: 1.4 .. seealso: - :attr:`.Selectable.exported_columns` + :attr:`expression.Selectable.exported_columns` - :attr:`.FromClause.exported_columns` + :attr:`_expression.FromClause.exported_columns` """ @@ -2196,13 +2274,16 @@ class SelectBase( @property @util.deprecated( "1.4", - "The :attr:`.SelectBase.c` and :attr:`.SelectBase.columns` attributes " + "The :attr:`_expression.SelectBase.c` and " + ":attr:`_expression.SelectBase.columns` attributes " "are deprecated and will be removed in a future release; these " "attributes implicitly create a subquery that should be explicit. " - "Please call :meth:`.SelectBase.subquery` first in order to create " + "Please call :meth:`_expression.SelectBase.subquery` " + "first in order to create " "a subquery, which then contains this attribute. To access the " "columns that this SELECT object SELECTs " - "from, use the :attr:`.SelectBase.selected_columns` attribute.", + "from, use the :attr:`_expression.SelectBase.selected_columns` " + "attribute.", ) def c(self): return self._implicit_subquery.columns @@ -2213,10 +2294,11 @@ class SelectBase( @util.deprecated( "1.4", - "The :meth:`.SelectBase.select` method is deprecated " + "The :meth:`_expression.SelectBase.select` method is deprecated " "and will be removed in a future release; this method implicitly " "creates a subquery that should be explicit. " - "Please call :meth:`.SelectBase.subquery` first in order to create " + "Please call :meth:`_expression.SelectBase.subquery` " + "first in order to create " "a subquery, which then can be seleted.", ) def select(self, *arg, **kw): @@ -2224,10 +2306,11 @@ class SelectBase( @util.deprecated( "1.4", - "The :meth:`.SelectBase.join` method is deprecated " + "The :meth:`_expression.SelectBase.join` method is deprecated " "and will be removed in a future release; this method implicitly " "creates a subquery that should be explicit. " - "Please call :meth:`.SelectBase.subquery` first in order to create " + "Please call :meth:`_expression.SelectBase.subquery` " + "first in order to create " "a subquery, which then can be selected.", ) def join(self, *arg, **kw): @@ -2235,10 +2318,11 @@ class SelectBase( @util.deprecated( "1.4", - "The :meth:`.SelectBase.outerjoin` method is deprecated " + "The :meth:`_expression.SelectBase.outerjoin` method is deprecated " "and will be removed in a future release; this method implicitly " "creates a subquery that should be explicit. " - "Please call :meth:`.SelectBase.subquery` first in order to create " + "Please call :meth:`_expression.SelectBase.subquery` " + "first in order to create " "a subquery, which then can be selected.", ) def outerjoin(self, *arg, **kw): @@ -2250,9 +2334,10 @@ class SelectBase( @util.deprecated( "1.4", - "The :meth:`.SelectBase.as_scalar` method is deprecated and will be " + "The :meth:`_expression.SelectBase.as_scalar` " + "method is deprecated and will be " "removed in a future release. Please refer to " - ":meth:`.SelectBase.scalar_subquery`.", + ":meth:`_expression.SelectBase.scalar_subquery`.", ) def as_scalar(self): return self.scalar_subquery() @@ -2267,11 +2352,12 @@ class SelectBase( an enclosing SELECT. Note that the scalar subquery differentiates from the FROM-level - subquery that can be produced using the :meth:`.SelectBase.subquery` + subquery that can be produced using the + :meth:`_expression.SelectBase.subquery` method. .. versionchanged: 1.4 - the ``.as_scalar()`` method was renamed to - :meth:`.SelectBase.scalar_subquery`. + :meth:`_expression.SelectBase.scalar_subquery`. """ if self._label_style is not LABEL_STYLE_NONE: @@ -2285,16 +2371,16 @@ class SelectBase( .. seealso:: - :meth:`~.SelectBase.as_scalar`. + :meth:`_expression.SelectBase.as_scalar`. """ return self.scalar_subquery().label(name) def lateral(self, name=None): - """Return a LATERAL alias of this :class:`.Selectable`. + """Return a LATERAL alias of this :class:`expression.Selectable`. - The return value is the :class:`.Lateral` construct also - provided by the top-level :func:`~.expression.lateral` function. + The return value is the :class:`_expression.Lateral` construct also + provided by the top-level :func:`_expression.lateral` function. .. versionadded:: 1.1 @@ -2310,7 +2396,7 @@ class SelectBase( return [self] def subquery(self, name=None): - """Return a subquery of this :class:`.SelectBase`. + """Return a subquery of this :class:`_expression.SelectBase`. A subquery is from a SQL perspective a parentheized, named construct that can be placed in the FROM clause of another SELECT statement. @@ -2335,10 +2421,14 @@ class SelectBase( SELECT anon_1.id, anon_1.name FROM (SELECT table.id, table.name FROM table) AS anon_1 - Historically, :meth:`.SelectBase.subquery` is equivalent to calling - the :meth:`.FromClause.alias` method on a FROM object; however, - as a :class:`.SelectBase` object is not directly FROM object, - the :meth:`.SelectBase.subquery` method provides clearer semantics. + Historically, :meth:`_expression.SelectBase.subquery` + is equivalent to calling + the :meth:`_expression.FromClause.alias` + method on a FROM object; however, + as a :class:`_expression.SelectBase` + object is not directly FROM object, + the :meth:`_expression.SelectBase.subquery` + method provides clearer semantics. .. versionadded:: 1.4 @@ -2355,22 +2445,25 @@ class SelectBase( raise NotImplementedError() def alias(self, name=None, flat=False): - """Return a named subquery against this :class:`.SelectBase`. + """Return a named subquery against this + :class:`_expression.SelectBase`. - For a :class:`.SelectBase` (as opposed to a :class:`.FromClause`), + For a :class:`_expression.SelectBase` (as opposed to a + :class:`_expression.FromClause`), this returns a :class:`.Subquery` object which behaves mostly the - same as the :class:`.Alias` object that is used with a - :class:`.FromClause`. + same as the :class:`_expression.Alias` object that is used with a + :class:`_expression.FromClause`. - .. versionchanged:: 1.4 The :meth:`.SelectBase.alias` method is now - a synonym for the :meth:`.SelectBase.subquery` method. + .. versionchanged:: 1.4 The :meth:`_expression.SelectBase.alias` + method is now + a synonym for the :meth:`_expression.SelectBase.subquery` method. """ return self.subquery(name=name) class SelectStatementGrouping(GroupedElement, SelectBase): - """Represent a grouping of a :class:`.SelectBase`. + """Represent a grouping of a :class:`_expression.SelectBase`. This differs from :class:`.Subquery` in that we are still an "inner" SELECT statement, this is strictly for grouping inside of @@ -2417,7 +2510,8 @@ class SelectStatementGrouping(GroupedElement, SelectBase): @property def selected_columns(self): - """A :class:`.ColumnCollection` representing the columns that + """A :class:`_expression.ColumnCollection` + representing the columns that the embedded SELECT statement returns in its result set. .. versionadded:: 1.4 @@ -2437,9 +2531,10 @@ class SelectStatementGrouping(GroupedElement, SelectBase): class DeprecatedSelectBaseGenerations(object): @util.deprecated( "1.4", - "The :meth:`.GenerativeSelect.append_order_by` method is deprecated " + "The :meth:`_expression.GenerativeSelect.append_order_by` " + "method is deprecated " "and will be removed in a future release. Use the generative method " - ":meth:`.GenerativeSelect.order_by`.", + ":meth:`_expression.GenerativeSelect.order_by`.", ) def append_order_by(self, *clauses): """Append the given ORDER BY criterion applied to this selectable. @@ -2447,21 +2542,23 @@ class DeprecatedSelectBaseGenerations(object): The criterion will be appended to any pre-existing ORDER BY criterion. This is an **in-place** mutation method; the - :meth:`~.GenerativeSelect.order_by` method is preferred, as it + :meth:`_expression.GenerativeSelect.order_by` method is preferred, + as it provides standard :term:`method chaining`. .. seealso:: - :meth:`.GenerativeSelect.order_by` + :meth:`_expression.GenerativeSelect.order_by` """ self.order_by.non_generative(self, *clauses) @util.deprecated( "1.4", - "The :meth:`.GenerativeSelect.append_group_by` method is deprecated " + "The :meth:`_expression.GenerativeSelect.append_group_by` " + "method is deprecated " "and will be removed in a future release. Use the generative method " - ":meth:`.GenerativeSelect.group_by`.", + ":meth:`_expression.GenerativeSelect.group_by`.", ) def append_group_by(self, *clauses): """Append the given GROUP BY criterion applied to this selectable. @@ -2469,12 +2566,13 @@ class DeprecatedSelectBaseGenerations(object): The criterion will be appended to any pre-existing GROUP BY criterion. This is an **in-place** mutation method; the - :meth:`~.GenerativeSelect.group_by` method is preferred, as it + :meth:`_expression.GenerativeSelect.group_by` method is preferred, + as it provides standard :term:`method chaining`. .. seealso:: - :meth:`.GenerativeSelect.group_by` + :meth:`_expression.GenerativeSelect.group_by` """ self.group_by.non_generative(self, *clauses) @@ -2489,10 +2587,13 @@ class GenerativeSelect(DeprecatedSelectBaseGenerations, SelectBase): """Base class for SELECT statements where additional elements can be added. - This serves as the base for :class:`.Select` and :class:`.CompoundSelect` + This serves as the base for :class:`_expression.Select` and + :class:`_expression.CompoundSelect` where elements such as ORDER BY, GROUP BY can be added and column - rendering can be controlled. Compare to :class:`.TextualSelect`, which, - while it subclasses :class:`.SelectBase` and is also a SELECT construct, + rendering can be controlled. Compare to + :class:`_expression.TextualSelect`, which, + while it subclasses :class:`_expression.SelectBase` + and is also a SELECT construct, represents a fixed textual string which cannot be altered at this level, only wrapped as a subquery. @@ -2540,7 +2641,8 @@ class GenerativeSelect(DeprecatedSelectBaseGenerations, SelectBase): skip_locked=False, key_share=False, ): - """Specify a ``FOR UPDATE`` clause for this :class:`.GenerativeSelect`. + """Specify a ``FOR UPDATE`` clause for this + :class:`_expression.GenerativeSelect`. E.g.:: @@ -2569,7 +2671,8 @@ class GenerativeSelect(DeprecatedSelectBaseGenerations, SelectBase): ``nowait``, will render ``FOR SHARE NOWAIT``. :param of: SQL expression or list of SQL expression elements - (typically :class:`.Column` objects or a compatible expression) which + (typically :class:`_schema.Column` + objects or a compatible expression) which will render into a ``FOR UPDATE OF`` clause; supported by PostgreSQL and Oracle. May render as a table or as a column depending on backend. @@ -2708,7 +2811,7 @@ class GenerativeSelect(DeprecatedSelectBaseGenerations, SelectBase): support ``LIMIT`` will attempt to provide similar functionality. - .. versionchanged:: 1.0.0 - :meth:`.Select.limit` can now + .. versionchanged:: 1.0.0 - :meth:`_expression.Select.limit` can now accept arbitrary SQL expressions as well as integer values. :param limit: an integer LIMIT parameter, or a SQL expression @@ -2730,7 +2833,7 @@ class GenerativeSelect(DeprecatedSelectBaseGenerations, SelectBase): functionality. - .. versionchanged:: 1.0.0 - :meth:`.Select.offset` can now + .. versionchanged:: 1.0.0 - :meth:`_expression.Select.offset` can now accept arbitrary SQL expressions as well as integer values. :param offset: an integer OFFSET parameter, or a SQL expression @@ -2749,7 +2852,8 @@ class GenerativeSelect(DeprecatedSelectBaseGenerations, SelectBase): stmt = select([table]).order_by(table.c.id, table.c.name) - :param \*order_by: a series of :class:`.ColumnElement` constructs + :param \*order_by: a series of :class:`_expression.ColumnElement` + constructs which will be used to generate an ORDER BY clause. .. seealso:: @@ -2776,7 +2880,8 @@ class GenerativeSelect(DeprecatedSelectBaseGenerations, SelectBase): stmt = select([table.c.name, func.max(table.c.stat)]).\ group_by(table.c.name) - :param \*group_by: a series of :class:`.ColumnElement` constructs + :param \*group_by: a series of :class:`_expression.ColumnElement` + constructs which will be used to generate an GROUP BY clause. .. seealso:: @@ -2810,17 +2915,17 @@ class CompoundSelect(HasCompileState, GenerativeSelect): .. seealso:: - :func:`.union` + :func:`_expression.union` - :func:`.union_all` + :func:`_expression.union_all` - :func:`.intersect` + :func:`_expression.intersect` - :func:`.intersect_all` + :func:`_expression.intersect_all` - :func:`.except` + :func:`_expression.except` - :func:`.except_all` + :func:`_expression.except_all` """ @@ -2863,13 +2968,13 @@ class CompoundSelect(HasCompileState, GenerativeSelect): r"""Return a ``UNION`` of multiple selectables. The returned object is an instance of - :class:`.CompoundSelect`. + :class:`_expression.CompoundSelect`. A similar :func:`union()` method is available on all - :class:`.FromClause` subclasses. + :class:`_expression.FromClause` subclasses. \*selects - a list of :class:`.Select` instances. + a list of :class:`_expression.Select` instances. \**kwargs available keyword arguments are the same as those of @@ -2883,13 +2988,13 @@ class CompoundSelect(HasCompileState, GenerativeSelect): r"""Return a ``UNION ALL`` of multiple selectables. The returned object is an instance of - :class:`.CompoundSelect`. + :class:`_expression.CompoundSelect`. A similar :func:`union_all()` method is available on all - :class:`.FromClause` subclasses. + :class:`_expression.FromClause` subclasses. \*selects - a list of :class:`.Select` instances. + a list of :class:`_expression.Select` instances. \**kwargs available keyword arguments are the same as those of @@ -2903,10 +3008,10 @@ class CompoundSelect(HasCompileState, GenerativeSelect): r"""Return an ``EXCEPT`` of multiple selectables. The returned object is an instance of - :class:`.CompoundSelect`. + :class:`_expression.CompoundSelect`. \*selects - a list of :class:`.Select` instances. + a list of :class:`_expression.Select` instances. \**kwargs available keyword arguments are the same as those of @@ -2920,10 +3025,10 @@ class CompoundSelect(HasCompileState, GenerativeSelect): r"""Return an ``EXCEPT ALL`` of multiple selectables. The returned object is an instance of - :class:`.CompoundSelect`. + :class:`_expression.CompoundSelect`. \*selects - a list of :class:`.Select` instances. + a list of :class:`_expression.Select` instances. \**kwargs available keyword arguments are the same as those of @@ -2937,10 +3042,10 @@ class CompoundSelect(HasCompileState, GenerativeSelect): r"""Return an ``INTERSECT`` of multiple selectables. The returned object is an instance of - :class:`.CompoundSelect`. + :class:`_expression.CompoundSelect`. \*selects - a list of :class:`.Select` instances. + a list of :class:`_expression.Select` instances. \**kwargs available keyword arguments are the same as those of @@ -2954,10 +3059,10 @@ class CompoundSelect(HasCompileState, GenerativeSelect): r"""Return an ``INTERSECT ALL`` of multiple selectables. The returned object is an instance of - :class:`.CompoundSelect`. + :class:`_expression.CompoundSelect`. \*selects - a list of :class:`.Select` instances. + a list of :class:`_expression.Select` instances. \**kwargs available keyword arguments are the same as those of @@ -3035,11 +3140,13 @@ class CompoundSelect(HasCompileState, GenerativeSelect): @property def selected_columns(self): - """A :class:`.ColumnCollection` representing the columns that + """A :class:`_expression.ColumnCollection` + representing the columns that this SELECT statement or similar construct returns in its result set. - For a :class:`.CompoundSelect`, the - :attr:`.CompoundSelect.selected_columns` attribute returns the selected + For a :class:`_expression.CompoundSelect`, the + :attr:`_expression.CompoundSelect.selected_columns` + attribute returns the selected columns of the first SELECT statement contained within the series of statements within the set operation. @@ -3067,16 +3174,18 @@ class CompoundSelect(HasCompileState, GenerativeSelect): class DeprecatedSelectGenerations(object): @util.deprecated( "1.4", - "The :meth:`.Select.append_correlation` method is deprecated " + "The :meth:`_expression.Select.append_correlation` " + "method is deprecated " "and will be removed in a future release. Use the generative " - "method :meth:`.Select.correlate`.", + "method :meth:`_expression.Select.correlate`.", ) def append_correlation(self, fromclause): """append the given correlation expression to this select() construct. This is an **in-place** mutation method; the - :meth:`~.Select.correlate` method is preferred, as it provides + :meth:`_expression.Select.correlate` method is preferred, + as it provides standard :term:`method chaining`. """ @@ -3085,9 +3194,9 @@ class DeprecatedSelectGenerations(object): @util.deprecated( "1.4", - "The :meth:`.Select.append_column` method is deprecated " + "The :meth:`_expression.Select.append_column` method is deprecated " "and will be removed in a future release. Use the generative " - "method :meth:`.Select.column`.", + "method :meth:`_expression.Select.column`.", ) def append_column(self, column): """append the given column expression to the columns clause of this @@ -3098,28 +3207,30 @@ class DeprecatedSelectGenerations(object): my_select.append_column(some_table.c.new_column) This is an **in-place** mutation method; the - :meth:`~.Select.column` method is preferred, as it provides standard + :meth:`_expression.Select.column` method is preferred, + as it provides standard :term:`method chaining`. - See the documentation for :meth:`.Select.with_only_columns` + See the documentation for :meth:`_expression.Select.with_only_columns` for guidelines on adding /replacing the columns of a - :class:`.Select` object. + :class:`_expression.Select` object. """ self.add_columns.non_generative(self, column) @util.deprecated( "1.4", - "The :meth:`.Select.append_prefix` method is deprecated " + "The :meth:`_expression.Select.append_prefix` method is deprecated " "and will be removed in a future release. Use the generative " - "method :meth:`.Select.prefix_with`.", + "method :meth:`_expression.Select.prefix_with`.", ) def append_prefix(self, clause): """append the given columns clause prefix expression to this select() construct. This is an **in-place** mutation method; the - :meth:`~.Select.prefix_with` method is preferred, as it provides + :meth:`_expression.Select.prefix_with` method is preferred, + as it provides standard :term:`method chaining`. """ @@ -3127,9 +3238,10 @@ class DeprecatedSelectGenerations(object): @util.deprecated( "1.4", - "The :meth:`.Select.append_whereclause` method is deprecated " + "The :meth:`_expression.Select.append_whereclause` " + "method is deprecated " "and will be removed in a future release. Use the generative " - "method :meth:`.Select.where`.", + "method :meth:`_expression.Select.where`.", ) def append_whereclause(self, whereclause): """append the given expression to this select() construct's WHERE @@ -3138,7 +3250,8 @@ class DeprecatedSelectGenerations(object): The expression will be joined to existing WHERE criterion via AND. This is an **in-place** mutation method; the - :meth:`~.Select.where` method is preferred, as it provides standard + :meth:`_expression.Select.where` method is preferred, + as it provides standard :term:`method chaining`. """ @@ -3146,9 +3259,9 @@ class DeprecatedSelectGenerations(object): @util.deprecated( "1.4", - "The :meth:`.Select.append_having` method is deprecated " + "The :meth:`_expression.Select.append_having` method is deprecated " "and will be removed in a future release. Use the generative " - "method :meth:`.Select.having`.", + "method :meth:`_expression.Select.having`.", ) def append_having(self, having): """append the given expression to this select() construct's HAVING @@ -3157,7 +3270,8 @@ class DeprecatedSelectGenerations(object): The expression will be joined to existing HAVING criterion via AND. This is an **in-place** mutation method; the - :meth:`~.Select.having` method is preferred, as it provides standard + :meth:`_expression.Select.having` method is preferred, + as it provides standard :term:`method chaining`. """ @@ -3166,16 +3280,17 @@ class DeprecatedSelectGenerations(object): @util.deprecated( "1.4", - "The :meth:`.Select.append_from` method is deprecated " + "The :meth:`_expression.Select.append_from` method is deprecated " "and will be removed in a future release. Use the generative " - "method :meth:`.Select.select_from`.", + "method :meth:`_expression.Select.select_from`.", ) def append_from(self, fromclause): """append the given FromClause expression to this select() construct's FROM clause. This is an **in-place** mutation method; the - :meth:`~.Select.select_from` method is preferred, as it provides + :meth:`_expression.Select.select_from` method is preferred, + as it provides standard :term:`method chaining`. """ @@ -3353,32 +3468,38 @@ class Select( @classmethod def _create_select(cls, *entities): - r"""Construct a new :class:`.Select` using the 2.x style API. + r"""Construct a new :class:`_expression.Select` using the 2. + x style API. .. versionadded:: 2.0 - the :func:`.future.select` construct is the same construct as the one returned by - :func:`.sql.expression.select`, except that the function only + :func:`_expression.select`, except that the function only accepts the "columns clause" entities up front; the rest of the state of the SELECT should be built up using generative methods. Similar functionality is also available via the - :meth:`.FromClause.select` method on any :class:`.FromClause`. + :meth:`_expression.FromClause.select` method on any + :class:`_expression.FromClause`. .. seealso:: :ref:`coretutorial_selecting` - Core Tutorial description of - :func:`~.sql.expression.select`. + :func:`_expression.select`. :param \*entities: Entities to SELECT from. For Core usage, this is typically a series - of :class:`.ColumnElement` and / or :class:`.FromClause` + of :class:`_expression.ColumnElement` and / or + :class:`_expression.FromClause` objects which will form the columns clause of the resulting statement. For those objects that are instances of - :class:`.FromClause` (typically :class:`.Table` or :class:`.Alias` - objects), the :attr:`.FromClause.c` collection is extracted - to form a collection of :class:`.ColumnElement` objects. - - This parameter will also accept :class:`.Text` constructs as + :class:`_expression.FromClause` (typically :class:`_schema.Table` + or :class:`_expression.Alias` + objects), the :attr:`_expression.FromClause.c` + collection is extracted + to form a collection of :class:`_expression.ColumnElement` objects. + + This parameter will also accept :class:`_expression.TextClause` + constructs as given, as well as ORM-mapped classes. """ @@ -3417,82 +3538,102 @@ class Select( suffixes=None, **kwargs ): - """Construct a new :class:`.Select` using the 1.x style API. + """Construct a new :class:`_expression.Select` using the 1.x style API + . Similar functionality is also available via the - :meth:`.FromClause.select` method on any :class:`.FromClause`. + :meth:`_expression.FromClause.select` method on any + :class:`_expression.FromClause`. - All arguments which accept :class:`.ClauseElement` arguments also + All arguments which accept :class:`_expression.ClauseElement` + arguments also accept string arguments, which will be converted as appropriate into - either :func:`.text()` or :func:`.literal_column()` constructs. + either :func:`_expression.text()` or + :func:`_expression.literal_column()` constructs. .. seealso:: :ref:`coretutorial_selecting` - Core Tutorial description of - :func:`~.sql.expression.select`. + :func:`_expression.select`. :param columns: - A list of :class:`.ColumnElement` or :class:`.FromClause` + A list of :class:`_expression.ColumnElement` or + :class:`_expression.FromClause` objects which will form the columns clause of the resulting statement. For those objects that are instances of - :class:`.FromClause` (typically :class:`.Table` or :class:`.Alias` - objects), the :attr:`.FromClause.c` collection is extracted - to form a collection of :class:`.ColumnElement` objects. - - This parameter will also accept :class:`.Text` constructs as + :class:`_expression.FromClause` (typically :class:`_schema.Table` + or :class:`_expression.Alias` + objects), the :attr:`_expression.FromClause.c` + collection is extracted + to form a collection of :class:`_expression.ColumnElement` objects. + + This parameter will also accept :class:`_expression.TextClause` + constructs as given, as well as ORM-mapped classes. .. note:: - The :paramref:`.select.columns` parameter is not available - in the method form of :func:`~.sql.expression.select`, e.g. - :meth:`.FromClause.select`. + The :paramref:`_expression.select.columns` + parameter is not available + in the method form of :func:`_expression.select`, e.g. + :meth:`_expression.FromClause.select`. .. seealso:: - :meth:`.Select.column` + :meth:`_expression.Select.column` - :meth:`.Select.with_only_columns` + :meth:`_expression.Select.with_only_columns` :param whereclause: - A :class:`.ClauseElement` expression which will be used to form the + A :class:`_expression.ClauseElement` + expression which will be used to form the ``WHERE`` clause. It is typically preferable to add WHERE - criterion to an existing :class:`.Select` using method chaining - with :meth:`.Select.where`. + criterion to an existing :class:`_expression.Select` + using method chaining + with :meth:`_expression.Select.where`. .. seealso:: - :meth:`.Select.where` + :meth:`_expression.Select.where` :param from_obj: - A list of :class:`.ClauseElement` objects which will be added to the + A list of :class:`_expression.ClauseElement` + objects which will be added to the ``FROM`` clause of the resulting statement. This is equivalent - to calling :meth:`.Select.select_from` using method chaining on - an existing :class:`.Select` object. + to calling :meth:`_expression.Select.select_from` + using method chaining on + an existing :class:`_expression.Select` object. .. seealso:: - :meth:`.Select.select_from` - full description of explicit + :meth:`_expression.Select.select_from` + - full description of explicit FROM clause specification. :param bind=None: - an :class:`~.Engine` or :class:`~.Connection` instance + an :class:`_engine.Engine` or :class:`_engine.Connection` instance to which the - resulting :class:`.Select` object will be bound. The - :class:`.Select` object will otherwise automatically bind to + resulting :class:`_expression.Select` object will be bound. The + :class:`_expression.Select` + object will otherwise automatically bind to whatever :class:`~.base.Connectable` instances can be located within - its contained :class:`.ClauseElement` members. + its contained :class:`_expression.ClauseElement` members. :param correlate=True: - indicates that this :class:`.Select` object should have its - contained :class:`.FromClause` elements "correlated" to an enclosing - :class:`.Select` object. It is typically preferable to specify - correlations on an existing :class:`.Select` construct using - :meth:`.Select.correlate`. + indicates that this :class:`_expression.Select` + object should have its + contained :class:`_expression.FromClause` + elements "correlated" to an enclosing + :class:`_expression.Select` object. + It is typically preferable to specify + correlations on an existing :class:`_expression.Select` + construct using + :meth:`_expression.Select.correlate`. .. seealso:: - :meth:`.Select.correlate` - full description of correlation. + :meth:`_expression.Select.correlate` + - full description of correlation. :param distinct=False: when ``True``, applies a ``DISTINCT`` qualifier to the columns @@ -3503,66 +3644,74 @@ class Select( is understood by the PostgreSQL dialect to render the ``DISTINCT ON (<columns>)`` syntax. - ``distinct`` is also available on an existing :class:`.Select` - object via the :meth:`~.Select.distinct` method. + ``distinct`` is also available on an existing + :class:`_expression.Select` + object via the :meth:`_expression.Select.distinct` method. .. seealso:: - :meth:`.Select.distinct` + :meth:`_expression.Select.distinct` :param group_by: - a list of :class:`.ClauseElement` objects which will comprise the + a list of :class:`_expression.ClauseElement` + objects which will comprise the ``GROUP BY`` clause of the resulting select. This parameter is typically specified more naturally using the - :meth:`.Select.group_by` method on an existing :class:`.Select`. + :meth:`_expression.Select.group_by` method on an existing + :class:`_expression.Select`. .. seealso:: - :meth:`.Select.group_by` + :meth:`_expression.Select.group_by` :param having: - a :class:`.ClauseElement` that will comprise the ``HAVING`` clause + a :class:`_expression.ClauseElement` + that will comprise the ``HAVING`` clause of the resulting select when ``GROUP BY`` is used. This parameter is typically specified more naturally using the - :meth:`.Select.having` method on an existing :class:`.Select`. + :meth:`_expression.Select.having` method on an existing + :class:`_expression.Select`. .. seealso:: - :meth:`.Select.having` + :meth:`_expression.Select.having` :param limit=None: a numerical value which usually renders as a ``LIMIT`` expression in the resulting select. Backends that don't support ``LIMIT`` will attempt to provide similar functionality. This parameter is typically specified more - naturally using the :meth:`.Select.limit` method on an existing - :class:`.Select`. + naturally using the :meth:`_expression.Select.limit` + method on an existing + :class:`_expression.Select`. .. seealso:: - :meth:`.Select.limit` + :meth:`_expression.Select.limit` :param offset=None: a numeric value which usually renders as an ``OFFSET`` expression in the resulting select. Backends that don't support ``OFFSET`` will attempt to provide similar functionality. This parameter is typically specified more naturally - using the :meth:`.Select.offset` method on an existing - :class:`.Select`. + using the :meth:`_expression.Select.offset` method on an existing + :class:`_expression.Select`. .. seealso:: - :meth:`.Select.offset` + :meth:`_expression.Select.offset` :param order_by: - a scalar or list of :class:`.ClauseElement` objects which will + a scalar or list of :class:`_expression.ClauseElement` + objects which will comprise the ``ORDER BY`` clause of the resulting select. This parameter is typically specified more naturally using the - :meth:`.Select.order_by` method on an existing :class:`.Select`. + :meth:`_expression.Select.order_by` method on an existing + :class:`_expression.Select`. .. seealso:: - :meth:`.Select.order_by` + :meth:`_expression.Select.order_by` :param use_labels=False: when ``True``, the statement will be generated using labels @@ -3570,16 +3719,18 @@ class Select( column with its parent table's (or aliases) name so that name conflicts between columns in different tables don't occur. The format of the label is <tablename>_<column>. The "c" - collection of the resulting :class:`.Select` object will use these + collection of the resulting :class:`_expression.Select` + object will use these names as well for targeting column members. This parameter can also be specified on an existing - :class:`.Select` object using the :meth:`.Select.apply_labels` + :class:`_expression.Select` object using the + :meth:`_expression.Select.apply_labels` method. .. seealso:: - :meth:`.Select.apply_labels` + :meth:`_expression.Select.apply_labels` """ util.warn_deprecated_20( @@ -3656,9 +3807,10 @@ class Select( return self._compile_state_factory(self, None)._get_display_froms() def with_statement_hint(self, text, dialect_name="*"): - """add a statement hint to this :class:`.Select`. + """add a statement hint to this :class:`_expression.Select`. - This method is similar to :meth:`.Select.with_hint` except that + This method is similar to :meth:`_expression.Select.with_hint` + except that it does not require an individual table, and instead applies to the statement as a whole. @@ -3670,7 +3822,7 @@ class Select( .. seealso:: - :meth:`.Select.with_hint` + :meth:`_expression.Select.with_hint` :meth:.`.Select.prefix_with` - generic SELECT prefixing which also can suit some database-specific HINT syntaxes such as MySQL @@ -3682,11 +3834,12 @@ class Select( @_generative def with_hint(self, selectable, text, dialect_name="*"): r"""Add an indexing or other executional context hint for the given - selectable to this :class:`.Select`. + selectable to this :class:`_expression.Select`. The text of the hint is rendered in the appropriate location for the database backend in use, relative - to the given :class:`.Table` or :class:`.Alias` passed as the + to the given :class:`_schema.Table` or :class:`_expression.Alias` + passed as the ``selectable`` argument. The dialect implementation typically uses Python string substitution syntax with the token ``%(name)s`` to render the name of @@ -3710,7 +3863,7 @@ class Select( .. seealso:: - :meth:`.Select.with_statement_hint` + :meth:`_expression.Select.with_statement_hint` """ if selectable is None: @@ -3724,7 +3877,7 @@ class Select( be rendered into the columns clause of the resulting SELECT statement. This method is legacy as of 1.4 and is superseded by the - :attr:`.Select.exported_columns` collection. + :attr:`_expression.Select.exported_columns` collection. """ @@ -3795,9 +3948,10 @@ class Select( my_select = my_select.add_columns(table.c.new_column) - See the documentation for :meth:`.Select.with_only_columns` + See the documentation for + :meth:`_expression.Select.with_only_columns` for guidelines on adding /replacing the columns of a - :class:`.Select` object. + :class:`_expression.Select` object. """ # memoizations should be cleared here as of @@ -3812,9 +3966,9 @@ class Select( @util.deprecated( "1.4", - "The :meth:`.Select.column` method is deprecated and will " + "The :meth:`_expression.Select.column` method is deprecated and will " "be removed in a future release. Please use " - ":meth:`.Select.add_columns`", + ":meth:`_expression.Select.add_columns`", ) def column(self, column): """return a new select() construct with the given column expression @@ -3824,9 +3978,10 @@ class Select( my_select = my_select.column(table.c.new_column) - See the documentation for :meth:`.Select.with_only_columns` + See the documentation for + :meth:`_expression.Select.with_only_columns` for guidelines on adding /replacing the columns of a - :class:`.Select` object. + :class:`_expression.Select` object. """ return self.add_columns(column) @@ -3841,7 +3996,8 @@ class Select( comparison in the WHERE clause of the statement. The primary purpose of this method is to automatically construct a select statement with all uniquely-named columns, without the need to use - table-qualified labels as :meth:`.apply_labels` does. + table-qualified labels as :meth:`_expression.Select.apply_labels` does + . When columns are omitted based on foreign key, the referred-to column is the one that's kept. When columns are omitted based on @@ -3863,11 +4019,11 @@ class Select( @_generative def with_only_columns(self, columns): - r"""Return a new :func:`~.sql.expression.select` construct with its columns + r"""Return a new :func:`_expression.select` construct with its columns clause replaced with the given columns. This method is exactly equivalent to as if the original - :func:`~.sql.expression.select` had been called with the given columns + :func:`_expression.select` had been called with the given columns clause. I.e. a statement:: s = select([table1.c.a, table1.c.b]) @@ -3893,7 +4049,7 @@ class Select( The preferred way to maintain a specific FROM clause in the construct, assuming it won't be represented anywhere else (i.e. not in the WHERE clause, etc.) is to set it using - :meth:`.Select.select_from`:: + :meth:`_expression.Select.select_from`:: >>> s1 = select([table1.c.a, table2.c.b]).\ ... select_from(table1.join(table2, @@ -3903,13 +4059,15 @@ class Select( SELECT t2.b FROM t1 JOIN t2 ON t1.a=t2.a Care should also be taken to use the correct set of column objects - passed to :meth:`.Select.with_only_columns`. Since the method is - essentially equivalent to calling the :func:`~.sql.expression.select` + passed to :meth:`_expression.Select.with_only_columns`. + Since the method is + essentially equivalent to calling the :func:`_expression.select` construct in the first place with the given columns, the columns passed - to :meth:`.Select.with_only_columns` should usually be a subset of - those which were passed to the :func:`~.sql.expression.select` + to :meth:`_expression.Select.with_only_columns` + should usually be a subset of + those which were passed to the :func:`_expression.select` construct, not those which are available from the ``.c`` collection of - that :func:`~.sql.expression.select`. That is:: + that :func:`_expression.select`. That is:: s = select([table1.c.a, table1.c.b]).select_from(table1) s = s.with_only_columns([table1.c.b]) @@ -3925,7 +4083,7 @@ class Select( FROM (SELECT t1.a AS a, t1.b AS b FROM t1), t1 - Since the :func:`~.sql.expression.select` construct is essentially + Since the :func:`_expression.select` construct is essentially being asked to select both from ``table1`` as well as itself. """ @@ -3945,7 +4103,8 @@ class Select( @property def _whereclause(self): - """Legacy, return the WHERE clause as a :class:`.BooleanClauseList`""" + """Legacy, return the WHERE clause as a """ + """:class:`_expression.BooleanClauseList`""" return and_(*self._where_criteria) @@ -3990,7 +4149,7 @@ class Select( @_generative def select_from(self, *froms): - r"""return a new :func:`~.sql.expression.select` construct with the + r"""return a new :func:`_expression.select` construct with the given FROM expression(s) merged into its list of FROM objects. @@ -4004,14 +4163,17 @@ class Select( ) The "from" list is a unique set on the identity of each element, - so adding an already present :class:`.Table` or other selectable - will have no effect. Passing a :class:`.Join` that refers - to an already present :class:`.Table` or other selectable will have + so adding an already present :class:`_schema.Table` + or other selectable + will have no effect. Passing a :class:`_expression.Join` that refers + to an already present :class:`_schema.Table` + or other selectable will have the effect of concealing the presence of that selectable as an individual element in the rendered FROM list, instead rendering it into a JOIN clause. - While the typical purpose of :meth:`.Select.select_from` is to + While the typical purpose of :meth:`_expression.Select.select_from` + is to replace the default, derived FROM clause with a join, it can also be called with individual table elements, multiple times if desired, in the case that the FROM clause cannot be fully @@ -4028,41 +4190,52 @@ class Select( @_generative def correlate(self, *fromclauses): - r"""return a new :class:`.Select` which will correlate the given FROM - clauses to that of an enclosing :class:`.Select`. + r"""return a new :class:`_expression.Select` + which will correlate the given FROM + clauses to that of an enclosing :class:`_expression.Select`. - Calling this method turns off the :class:`.Select` object's + Calling this method turns off the :class:`_expression.Select` object's default behavior of "auto-correlation". Normally, FROM elements - which appear in a :class:`.Select` that encloses this one via + which appear in a :class:`_expression.Select` + that encloses this one via its :term:`WHERE clause`, ORDER BY, HAVING or - :term:`columns clause` will be omitted from this :class:`.Select` + :term:`columns clause` will be omitted from this + :class:`_expression.Select` object's :term:`FROM clause`. Setting an explicit correlation collection using the - :meth:`.Select.correlate` method provides a fixed list of FROM objects + :meth:`_expression.Select.correlate` + method provides a fixed list of FROM objects that can potentially take place in this process. - When :meth:`.Select.correlate` is used to apply specific FROM clauses + When :meth:`_expression.Select.correlate` + is used to apply specific FROM clauses for correlation, the FROM elements become candidates for - correlation regardless of how deeply nested this :class:`.Select` - object is, relative to an enclosing :class:`.Select` which refers to + correlation regardless of how deeply nested this + :class:`_expression.Select` + object is, relative to an enclosing :class:`_expression.Select` + which refers to the same FROM object. This is in contrast to the behavior of "auto-correlation" which only correlates to an immediate enclosing - :class:`.Select`. Multi-level correlation ensures that the link - between enclosed and enclosing :class:`.Select` is always via + :class:`_expression.Select`. + Multi-level correlation ensures that the link + between enclosed and enclosing :class:`_expression.Select` + is always via at least one WHERE/ORDER BY/HAVING/columns clause in order for correlation to take place. - If ``None`` is passed, the :class:`.Select` object will correlate + If ``None`` is passed, the :class:`_expression.Select` + object will correlate none of its FROM entries, and all will render unconditionally in the local FROM clause. - :param \*fromclauses: a list of one or more :class:`.FromClause` + :param \*fromclauses: a list of one or more + :class:`_expression.FromClause` constructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate collection. .. seealso:: - :meth:`.Select.correlate_except` + :meth:`_expression.Select.correlate_except` :ref:`correlated_subqueries` @@ -4078,26 +4251,29 @@ class Select( @_generative def correlate_except(self, *fromclauses): - r"""return a new :class:`.Select` which will omit the given FROM + r"""return a new :class:`_expression.Select` + which will omit the given FROM clauses from the auto-correlation process. - Calling :meth:`.Select.correlate_except` turns off the - :class:`.Select` object's default behavior of + Calling :meth:`_expression.Select.correlate_except` turns off the + :class:`_expression.Select` object's default behavior of "auto-correlation" for the given FROM elements. An element specified here will unconditionally appear in the FROM list, while all other FROM elements remain subject to normal auto-correlation behaviors. - If ``None`` is passed, the :class:`.Select` object will correlate + If ``None`` is passed, the :class:`_expression.Select` + object will correlate all of its FROM entries. - :param \*fromclauses: a list of one or more :class:`.FromClause` + :param \*fromclauses: a list of one or more + :class:`_expression.FromClause` constructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate-exception collection. .. seealso:: - :meth:`.Select.correlate` + :meth:`_expression.Select.correlate` :ref:`correlated_subqueries` @@ -4113,18 +4289,22 @@ class Select( @HasMemoized.memoized_attribute def selected_columns(self): - """A :class:`.ColumnCollection` representing the columns that + """A :class:`_expression.ColumnCollection` + representing the columns that this SELECT statement or similar construct returns in its result set. - This collection differs from the :attr:`.FromClause.columns` collection - of a :class:`.FromClause` in that the columns within this collection + This collection differs from the + :attr:`_expression.FromClause.columns` collection + of a :class:`_expression.FromClause` + in that the columns within this collection cannot be directly nested inside another SELECT statement; a subquery must be applied first which provides for the necessary parenthesization required by SQL. - For a :func:`~.sql.expression.select` construct, the collection here is + For a :func:`_expression.select` construct, the collection here is exactly what would be rendered inside the "SELECT" statement, and the - :class:`.ColumnElement` objects are directly present as they were + :class:`_expression.ColumnElement` + objects are directly present as they were given, e.g.:: col1 = column('q', Integer) @@ -4133,9 +4313,11 @@ class Select( Above, ``stmt.selected_columns`` would be a collection that contains the ``col1`` and ``col2`` objects directly. For a statement that is - against a :class:`.Table` or other :class:`.FromClause`, the collection - will use the :class:`.ColumnElement` objects that are in the - :attr:`.FromClause.c` collection of the from element. + against a :class:`_schema.Table` or other + :class:`_expression.FromClause`, the collection + will use the :class:`_expression.ColumnElement` + objects that are in the + :attr:`_expression.FromClause.c` collection of the from element. .. versionadded:: 1.4 @@ -4425,7 +4607,7 @@ class ScalarSelect(roles.InElementRole, Generative, Grouping): @_generative def where(self, crit): """Apply a WHERE clause to the SELECT statement referred to - by this :class:`.ScalarSelect`. + by this :class:`_expression.ScalarSelect`. """ self.element = self.element.where(crit) @@ -4442,8 +4624,8 @@ class Exists(UnaryExpression): _from_objects = [] def __init__(self, *args, **kwargs): - """Construct a new :class:`.Exists` against an existing - :class:`.Select` object. + """Construct a new :class:`_expression.Exists` against an existing + :class:`_expression.Select` object. Calling styles are of the following forms:: @@ -4499,8 +4681,10 @@ class Exists(UnaryExpression): return e def select_from(self, clause): - """return a new :class:`.Exists` construct, applying the given - expression to the :meth:`.Select.select_from` method of the select + """return a new :class:`_expression.Exists` construct, + applying the given + expression to the :meth:`_expression.Select.select_from` + method of the select statement contained. """ @@ -4519,25 +4703,30 @@ class Exists(UnaryExpression): class TextualSelect(SelectBase): - """Wrap a :class:`.TextClause` construct within a :class:`.SelectBase` + """Wrap a :class:`_expression.TextClause` construct within a + :class:`_expression.SelectBase` interface. - This allows the :class:`.TextClause` object to gain a ``.c`` collection - and other FROM-like capabilities such as :meth:`.FromClause.alias`, - :meth:`.SelectBase.cte`, etc. + This allows the :class:`_expression.TextClause` object to gain a ``. + c`` collection + and other FROM-like capabilities such as + :meth:`_expression.FromClause.alias`, + :meth:`_expression.SelectBase.cte`, etc. - The :class:`.TextualSelect` construct is produced via the - :meth:`.TextClause.columns` method - see that method for details. + The :class:`_expression.TextualSelect` construct is produced via the + :meth:`_expression.TextClause.columns` + method - see that method for details. - .. versionchanged:: 1.4 the :class:`.TextualSelect` class was renamed + .. versionchanged:: 1.4 the :class:`_expression.TextualSelect` + class was renamed from ``TextAsFrom``, to more correctly suit its role as a SELECT-oriented object and not a FROM clause. .. seealso:: - :func:`.text` + :func:`_expression.text` - :meth:`.TextClause.columns` - primary creation interface. + :meth:`_expression.TextClause.columns` - primary creation interface. """ @@ -4562,18 +4751,23 @@ class TextualSelect(SelectBase): @HasMemoized.memoized_attribute def selected_columns(self): - """A :class:`.ColumnCollection` representing the columns that + """A :class:`_expression.ColumnCollection` + representing the columns that this SELECT statement or similar construct returns in its result set. - This collection differs from the :attr:`.FromClause.columns` collection - of a :class:`.FromClause` in that the columns within this collection + This collection differs from the + :attr:`_expression.FromClause.columns` collection + of a :class:`_expression.FromClause` + in that the columns within this collection cannot be directly nested inside another SELECT statement; a subquery must be applied first which provides for the necessary parenthesization required by SQL. - For a :class:`.TextualSelect` construct, the collection contains the - :class:`.ColumnElement` objects that were passed to the constructor, - typically via the :meth:`.TextClause.columns` method. + For a :class:`_expression.TextualSelect` construct, + the collection contains the + :class:`_expression.ColumnElement` + objects that were passed to the constructor, + typically via the :meth:`_expression.TextClause.columns` method. .. versionadded:: 1.4 diff --git a/lib/sqlalchemy/sql/sqltypes.py b/lib/sqlalchemy/sql/sqltypes.py index 245b809ae..ba8a25821 100644 --- a/lib/sqlalchemy/sql/sqltypes.py +++ b/lib/sqlalchemy/sql/sqltypes.py @@ -210,7 +210,8 @@ class String(Concatenable, TypeEngine): In the vast majority of cases, the :class:`.Unicode` or :class:`.UnicodeText` datatypes should be used for a - :class:`.Column` that expects to store non-ascii data. These + :class:`_schema.Column` that expects to store non-ascii data. + These datatypes will ensure that the correct types are used on the database side as well as set up the correct Unicode behaviors under Python 2. @@ -218,7 +219,7 @@ class String(Concatenable, TypeEngine): .. seealso:: :paramref:`.create_engine.convert_unicode` - - :class:`.Engine`-wide parameter + :class:`_engine.Engine`-wide parameter :param unicode_error: Optional, a method to use to handle Unicode conversion errors. Behaves like the ``errors`` keyword argument to @@ -440,7 +441,7 @@ class UnicodeText(Text): """ Create a Unicode-converting Text type. - Parameters are the same as that of :class:`.Text`, + Parameters are the same as that of :class:`_expression.TextClause`, with the exception that ``convert_unicode`` defaults to ``True``. @@ -774,7 +775,7 @@ class DateTime(_LookupExpressionAdapter, TypeEngine): backends include additional options, such as timezone support and fractional seconds support. For fractional seconds, use the dialect-specific datatype, such as :class:`.mysql.TIME`. For - timezone support, use at least the :class:`~.types.TIMESTAMP` datatype, + timezone support, use at least the :class:`_types.TIMESTAMP` datatype, if not the dialect-specific datatype object. """ @@ -787,7 +788,7 @@ class DateTime(_LookupExpressionAdapter, TypeEngine): :param timezone: boolean. Indicates that the datetime type should enable timezone support, if available on the **base date/time-holding type only**. It is recommended - to make use of the :class:`~.types.TIMESTAMP` datatype directly when + to make use of the :class:`_types.TIMESTAMP` datatype directly when using this flag, as some databases include separate generic date/time-holding types distinct from the timezone-capable TIMESTAMP datatype, such as Oracle. @@ -980,7 +981,7 @@ class SchemaType(SchemaEventTarget): :meth:`.DDLEvents.before_parent_attach` and :meth:`.DDLEvents.after_parent_attach` events, where the events fire off surrounding the association of the type object with a parent - :class:`.Column`. + :class:`_schema.Column`. .. seealso:: @@ -1231,7 +1232,7 @@ class Enum(Emulated, String, SchemaType): .. seealso:: - :class:`.postgresql.ENUM` - PostgreSQL-specific type, + :class:`_postgresql.ENUM` - PostgreSQL-specific type, which has additional functionality. :class:`.mysql.ENUM` - MySQL-specific type @@ -1312,16 +1313,17 @@ class Enum(Emulated, String, SchemaType): The ``schema`` of the :class:`.Enum` type does not by default make use of the ``schema`` established on the - owning :class:`.Table`. If this behavior is desired, + owning :class:`_schema.Table`. If this behavior is desired, set the ``inherit_schema`` flag to ``True``. :param quote: Set explicit quoting preferences for the type's name. :param inherit_schema: When ``True``, the "schema" from the owning - :class:`.Table` will be copied to the "schema" attribute of this + :class:`_schema.Table` + will be copied to the "schema" attribute of this :class:`.Enum`, replacing whatever value was passed for the ``schema`` attribute. This also takes effect when using the - :meth:`.Table.tometadata` operation. + :meth:`_schema.Table.tometadata` operation. :param validate_strings: when True, string values that are being passed to the database in a SQL statement will be checked @@ -1935,7 +1937,8 @@ class Interval(Emulated, _AbstractInterval, TypeDecorator): class JSON(Indexable, TypeEngine): """Represent a SQL JSON type. - .. note:: :class:`.types.JSON` is provided as a facade for vendor-specific + .. note:: :class:`_types.JSON` + is provided as a facade for vendor-specific JSON types. Since it supports JSON SQL operations, it only works on backends that have an actual JSON type, currently: @@ -1945,10 +1948,10 @@ class JSON(Indexable, TypeEngine): * SQLite as of version 3.9 - :class:`.types.JSON` is part of the Core in support of the growing + :class:`_types.JSON` is part of the Core in support of the growing popularity of native JSON datatypes. - The :class:`.types.JSON` type stores arbitrary JSON format data, e.g.:: + The :class:`_types.JSON` type stores arbitrary JSON format data, e.g.:: data_table = Table('data_table', metadata, Column('id', Integer, primary_key=True), @@ -1963,7 +1966,8 @@ class JSON(Indexable, TypeEngine): **JSON-Specific Expression Operators** - The :class:`.types.JSON` datatype provides these additional SQL operations: + The :class:`_types.JSON` + datatype provides these additional SQL operations: * Keyed index operations:: @@ -1985,15 +1989,16 @@ class JSON(Indexable, TypeEngine): .. versionadded:: 1.3.11 Additional operations may be available from the dialect-specific versions - of :class:`.types.JSON`, such as :class:`.postgresql.JSON` and - :class:`.postgresql.JSONB` which both offer additional PostgreSQL-specific + of :class:`_types.JSON`, such as :class:`_postgresql.JSON` and + :class:`_postgresql.JSONB` which both offer additional PostgreSQL-specific operations. **Casting JSON Elements to Other Types** Index operations, i.e. those invoked by calling upon the expression using the Python bracket operator as in ``some_column['some key']``, return an - expression object whose type defaults to :class:`.JSON` by default, so that + expression object whose type defaults to :class:`_types.JSON` by default, + so that further JSON-oriented instructions may be called upon the result type. However, it is likely more common that an index operation is expected to return a specific scalar element, such as a string or integer. In @@ -2042,7 +2047,7 @@ class JSON(Indexable, TypeEngine): **Detecting Changes in JSON columns when using the ORM** - The :class:`.JSON` type, when used with the SQLAlchemy ORM, does not + The :class:`_types.JSON` type, when used with the SQLAlchemy ORM, does not detect in-place mutations to the structure. In order to detect these, the :mod:`sqlalchemy.ext.mutable` extension must be used. This extension will allow "in-place" changes to the datastructure to produce events which @@ -2051,7 +2056,8 @@ class JSON(Indexable, TypeEngine): **Support for JSON null vs. SQL NULL** - When working with NULL values, the :class:`.JSON` type recommends the + When working with NULL values, the :class:`_types.JSON` + type recommends the use of two specific constants in order to differentiate between a column that evaluates to SQL NULL, e.g. no value, vs. the JSON-encoded string of ``"null"``. To insert or select against a value that is SQL NULL, @@ -2061,23 +2067,24 @@ class JSON(Indexable, TypeEngine): conn.execute(table.insert(), json_value=null()) To insert or select against a value that is JSON ``"null"``, use the - constant :attr:`.JSON.NULL`:: + constant :attr:`_types.JSON.NULL`:: conn.execute(table.insert(), json_value=JSON.NULL) - The :class:`.JSON` type supports a flag - :paramref:`.JSON.none_as_null` which when set to True will result + The :class:`_types.JSON` type supports a flag + :paramref:`_types.JSON.none_as_null` which when set to True will result in the Python constant ``None`` evaluating to the value of SQL NULL, and when set to False results in the Python constant ``None`` evaluating to the value of JSON ``"null"``. The Python value ``None`` may be used in conjunction with either - :attr:`.JSON.NULL` and :func:`.null` in order to indicate NULL + :attr:`_types.JSON.NULL` and :func:`.null` in order to indicate NULL values, but care must be taken as to the value of the - :paramref:`.JSON.none_as_null` in these cases. + :paramref:`_types.JSON.none_as_null` in these cases. **Customizing the JSON Serializer** - The JSON serializer and deserializer used by :class:`.JSON` defaults to + The JSON serializer and deserializer used by :class:`_types.JSON` + defaults to Python's ``json.dumps`` and ``json.loads`` functions; in the case of the psycopg2 dialect, psycopg2 may be using its own custom loader function. @@ -2099,13 +2106,13 @@ class JSON(Indexable, TypeEngine): .. seealso:: - :class:`.postgresql.JSON` + :class:`_postgresql.JSON` - :class:`.postgresql.JSONB` + :class:`_postgresql.JSONB` :class:`.mysql.JSON` - :class:`.sqlite.JSON` + :class:`_sqlite.JSON` .. versionadded:: 1.1 @@ -2121,9 +2128,11 @@ class JSON(Indexable, TypeEngine): This value is used to force the JSON value of ``"null"`` to be used as the value. A value of Python ``None`` will be recognized either as SQL NULL or JSON ``"null"``, based on the setting - of the :paramref:`.JSON.none_as_null` flag; the :attr:`.JSON.NULL` + of the :paramref:`_types.JSON.none_as_null` flag; the + :attr:`_types.JSON.NULL` constant can be used to always resolve to JSON ``"null"`` regardless - of this setting. This is in contrast to the :func:`.sql.null` construct, + of this setting. This is in contrast to the :func:`_expression.null` + construct, which always resolves to SQL NULL. E.g.:: from sqlalchemy import null @@ -2139,15 +2148,16 @@ class JSON(Indexable, TypeEngine): session.commit() In order to set JSON NULL as a default value for a column, the most - transparent method is to use :func:`.text`:: + transparent method is to use :func:`_expression.text`:: Table( 'my_table', metadata, Column('json_data', JSON, default=text("'null'")) ) - While it is possible to use :attr:`.JSON.NULL` in this context, the - :attr:`.JSON.NULL` value will be returned as the value of the column, + While it is possible to use :attr:`_types.JSON.NULL` in this context, the + :attr:`_types.JSON.NULL` value will be returned as the value of the column + , which in the context of the ORM or other repurposing of the default value, may not be desirable. Using a SQL expression means the value will be re-fetched from the database within the context of retrieving @@ -2157,7 +2167,7 @@ class JSON(Indexable, TypeEngine): """ def __init__(self, none_as_null=False): - """Construct a :class:`.types.JSON` type. + """Construct a :class:`_types.JSON` type. :param none_as_null=False: if True, persist the value ``None`` as a SQL NULL value, not the JSON encoding of ``null``. Note that @@ -2169,9 +2179,9 @@ class JSON(Indexable, TypeEngine): .. note:: - :paramref:`.JSON.none_as_null` does **not** apply to the - values passed to :paramref:`.Column.default` and - :paramref:`.Column.server_default`; a value of ``None`` + :paramref:`_types.JSON.none_as_null` does **not** apply to the + values passed to :paramref:`_schema.Column.default` and + :paramref:`_schema.Column.server_default`; a value of ``None`` passed for these parameters means "no default present". .. seealso:: @@ -2236,7 +2246,7 @@ class JSON(Indexable, TypeEngine): """ class Comparator(Indexable.Comparator, Concatenable.Comparator): - """Define comparison operations for :class:`.types.JSON`.""" + """Define comparison operations for :class:`_types.JSON`.""" def _setup_getitem(self, index): if not isinstance(index, util.string_types) and isinstance( @@ -2366,7 +2376,7 @@ class JSON(Indexable, TypeEngine): @property def should_evaluate_none(self): - """Alias of :attr:`.JSON.none_as_null`""" + """Alias of :attr:`_types.JSON.none_as_null`""" return not self.none_as_null @should_evaluate_none.setter @@ -2417,17 +2427,18 @@ class ARRAY(SchemaEventTarget, Indexable, Concatenable, TypeEngine): .. note:: This type serves as the basis for all ARRAY operations. However, currently **only the PostgreSQL backend has support for SQL arrays in SQLAlchemy**. It is recommended to use the - :class:`.postgresql.ARRAY` type directly when using ARRAY types + :class:`_postgresql.ARRAY` type directly when using ARRAY types with PostgreSQL, as it provides additional operators specific to that backend. - :class:`.types.ARRAY` is part of the Core in support of various SQL - standard functions such as :class:`.array_agg` which explicitly involve + :class:`_types.ARRAY` is part of the Core in support of various SQL + standard functions such as :class:`_functions.array_agg` + which explicitly involve arrays; however, with the exception of the PostgreSQL backend and possibly some third-party dialects, no other SQLAlchemy built-in dialect has support for this type. - An :class:`.types.ARRAY` type is constructed given the "type" + An :class:`_types.ARRAY` type is constructed given the "type" of element:: mytable = Table("mytable", metadata, @@ -2444,7 +2455,7 @@ class ARRAY(SchemaEventTarget, Indexable, Concatenable, TypeEngine): data=[1,2,3] ) - The :class:`.types.ARRAY` type can be constructed given a fixed number + The :class:`_types.ARRAY` type can be constructed given a fixed number of dimensions:: mytable = Table("mytable", metadata, @@ -2470,10 +2481,10 @@ class ARRAY(SchemaEventTarget, Indexable, Concatenable, TypeEngine): >>> expr = table.c.column[5] # returns ARRAY(Integer, dimensions=1) >>> expr = expr[6] # returns Integer - For 1-dimensional arrays, an :class:`.types.ARRAY` instance with no + For 1-dimensional arrays, an :class:`_types.ARRAY` instance with no dimension parameter will generally assume single-dimensional behaviors. - SQL expressions of type :class:`.types.ARRAY` have support for "index" and + SQL expressions of type :class:`_types.ARRAY` have support for "index" and "slice" behavior. The Python ``[]`` operator works normally here, given integer indexes or slices. Arrays default to 1-based indexing. The operator produces binary expression @@ -2482,7 +2493,8 @@ class ARRAY(SchemaEventTarget, Indexable, Concatenable, TypeEngine): select([mytable.c.data[5], mytable.c.data[2:7]]) - as well as UPDATE statements when the :meth:`.Update.values` method + as well as UPDATE statements when the :meth:`_expression.Update.values` + method is used:: mytable.update().values({ @@ -2490,16 +2502,16 @@ class ARRAY(SchemaEventTarget, Indexable, Concatenable, TypeEngine): mytable.c.data[2:7]: [1, 2, 3] }) - The :class:`.types.ARRAY` type also provides for the operators + The :class:`_types.ARRAY` type also provides for the operators :meth:`.types.ARRAY.Comparator.any` and :meth:`.types.ARRAY.Comparator.all`. The PostgreSQL-specific version of - :class:`.types.ARRAY` also provides additional operators. + :class:`_types.ARRAY` also provides additional operators. .. versionadded:: 1.1.0 .. seealso:: - :class:`.postgresql.ARRAY` + :class:`_postgresql.ARRAY` """ @@ -2511,7 +2523,7 @@ class ARRAY(SchemaEventTarget, Indexable, Concatenable, TypeEngine): class Comparator(Indexable.Comparator, Concatenable.Comparator): - """Define comparison operations for :class:`.types.ARRAY`. + """Define comparison operations for :class:`_types.ARRAY`. More operators are available on the dialect-specific form of this type. See :class:`.postgresql.ARRAY.Comparator`. @@ -2586,7 +2598,7 @@ class ARRAY(SchemaEventTarget, Indexable, Concatenable, TypeEngine): .. seealso:: - :func:`.sql.expression.any_` + :func:`_expression.any_` :meth:`.types.ARRAY.Comparator.all` @@ -2622,7 +2634,7 @@ class ARRAY(SchemaEventTarget, Indexable, Concatenable, TypeEngine): .. seealso:: - :func:`.sql.expression.all_` + :func:`_expression.all_` :meth:`.types.ARRAY.Comparator.any` @@ -2639,7 +2651,7 @@ class ARRAY(SchemaEventTarget, Indexable, Concatenable, TypeEngine): def __init__( self, item_type, as_tuple=False, dimensions=None, zero_indexes=False ): - """Construct an :class:`.types.ARRAY`. + """Construct an :class:`_types.ARRAY`. E.g.:: @@ -2662,7 +2674,7 @@ class ARRAY(SchemaEventTarget, Indexable, Concatenable, TypeEngine): on the database, how it goes about interpreting Python and result values, as well as how expression behavior in conjunction with the "getitem" operator works. See the description at - :class:`.types.ARRAY` for additional detail. + :class:`_types.ARRAY` for additional detail. :param zero_indexes=False: when True, index values will be converted between Python zero-based and SQL one-based indexes, e.g. @@ -2764,7 +2776,7 @@ class TIMESTAMP(DateTime): """The SQL TIMESTAMP type. - :class:`~.types.TIMESTAMP` datatypes have support for timezone + :class:`_types.TIMESTAMP` datatypes have support for timezone storage on some backends, such as PostgreSQL and Oracle. Use the :paramref:`~types.TIMESTAMP.timezone` argument in order to enable "TIMESTAMP WITH TIMEZONE" for these backends. @@ -2774,7 +2786,7 @@ class TIMESTAMP(DateTime): __visit_name__ = "TIMESTAMP" def __init__(self, timezone=False): - """Construct a new :class:`.TIMESTAMP`. + """Construct a new :class:`_types.TIMESTAMP`. :param timezone: boolean. Indicates that the TIMESTAMP type should enable timezone support, if available on the target database. @@ -2895,7 +2907,8 @@ class NullType(TypeEngine): by the :class:`.Dialect` * When constructing SQL expressions using plain Python objects of unknown types (e.g. ``somecolumn == my_special_object``) - * When a new :class:`.Column` is created, and the given type is passed + * When a new :class:`_schema.Column` is created, + and the given type is passed as ``None`` or is not passed at all. The :class:`.NullType` can be used within SQL expression invocation @@ -2904,7 +2917,8 @@ class NullType(TypeEngine): :class:`.NullType` will result in a :exc:`.CompileError` if the compiler is asked to render the type itself, such as if it is used in a :func:`.cast` operation or within a schema creation operation such as that - invoked by :meth:`.MetaData.create_all` or the :class:`.CreateTable` + invoked by :meth:`_schema.MetaData.create_all` or the + :class:`.CreateTable` construct. """ diff --git a/lib/sqlalchemy/sql/traversals.py b/lib/sqlalchemy/sql/traversals.py index 032488826..4a135538e 100644 --- a/lib/sqlalchemy/sql/traversals.py +++ b/lib/sqlalchemy/sql/traversals.py @@ -165,7 +165,7 @@ class HasCacheKey(HasMemoized): each one; these bound parameters must be consulted in order to execute the statement with the correct parameters. - a :class:`.ClauseElement` structure that does not implement + a :class:`_expression.ClauseElement` structure that does not implement a :meth:`._gen_cache_key` method and does not implement a :attr:`.traverse_internals` attribute will not be cacheable; when such an element is embedded into a larger structure, this method diff --git a/lib/sqlalchemy/sql/type_api.py b/lib/sqlalchemy/sql/type_api.py index e9632c502..ccda21e11 100644 --- a/lib/sqlalchemy/sql/type_api.py +++ b/lib/sqlalchemy/sql/type_api.py @@ -82,7 +82,8 @@ class TypeEngine(Traversible): This method determines the type of a resulting binary expression given two source types and an operator. For example, two - :class:`.Column` objects, both of the type :class:`.Integer`, will + :class:`_schema.Column` objects, both of the type + :class:`.Integer`, will produce a :class:`.BinaryExpression` that also has the type :class:`.Integer` when compared via the addition (``+``) operator. However, using the addition operator with an :class:`.Integer` @@ -116,7 +117,8 @@ class TypeEngine(Traversible): comparator_factory = Comparator """A :class:`.TypeEngine.Comparator` class which will apply - to operations performed by owning :class:`.ColumnElement` objects. + to operations performed by owning :class:`_expression.ColumnElement` + objects. The :attr:`.comparator_factory` attribute is a hook consulted by the core expression system when column and SQL expression operations @@ -195,14 +197,15 @@ class TypeEngine(Traversible): In all cases, the actual NULL SQL value can be always be persisted in any column by using - the :obj:`~.expression.null` SQL construct in an INSERT statement + the :obj:`_expression.null` SQL construct in an INSERT statement or associated with an ORM-mapped attribute. .. note:: The "evaluates none" flag does **not** apply to a value - of ``None`` passed to :paramref:`.Column.default` or - :paramref:`.Column.server_default`; in these cases, ``None`` + of ``None`` passed to :paramref:`_schema.Column.default` or + :paramref:`_schema.Column.server_default`; in these cases, + ``None`` still means "no default". .. versionadded:: 1.1 @@ -676,7 +679,7 @@ class UserDefinedType(util.with_metaclass(VisitableCheckKWArg, TypeEngine)): The ``get_col_spec()`` method will in most cases receive a keyword argument ``type_expression`` which refers to the owning expression - of the type as being compiled, such as a :class:`.Column` or + of the type as being compiled, such as a :class:`_schema.Column` or :func:`.cast` construct. This keyword is only sent if the method accepts keyword arguments (e.g. ``**kw``) in its argument signature; introspection is used to check for this in order to support legacy @@ -859,7 +862,7 @@ class TypeDecorator(SchemaEventTarget, TypeEngine): If the :class:`.TypeDecorator` is augmenting a type that requires special logic for certain types of operators, this method **must** be overridden. A key example is when decorating - the :class:`.postgresql.JSON` and :class:`.postgresql.JSONB` types; + the :class:`_postgresql.JSON` and :class:`_postgresql.JSONB` types; the default rules of :meth:`.TypeEngine.coerce_compared_value` should be used in order to deal with operators like index operations:: diff --git a/lib/sqlalchemy/sql/visitors.py b/lib/sqlalchemy/sql/visitors.py index 29ed01309..8f6bb2333 100644 --- a/lib/sqlalchemy/sql/visitors.py +++ b/lib/sqlalchemy/sql/visitors.py @@ -228,35 +228,37 @@ class InternalTraversal(util.with_metaclass(_InternalTraversalType, object)): """Visit a :class:`.HasCacheKey` object.""" dp_clauseelement = symbol("CE") - """Visit a :class:`.ClauseElement` object.""" + """Visit a :class:`_expression.ClauseElement` object.""" dp_fromclause_canonical_column_collection = symbol("FC") - """Visit a :class:`.FromClause` object in the context of the + """Visit a :class:`_expression.FromClause` object in the context of the ``columns`` attribute. The column collection is "canonical", meaning it is the originally defined location of the :class:`.ColumnClause` objects. Right now - this means that the object being visited is a :class:`.TableClause` - or :class:`.Table` object only. + this means that the object being visited is a + :class:`_expression.TableClause` + or :class:`_schema.Table` object only. """ dp_clauseelement_tuples = symbol("CT") - """Visit a list of tuples which contain :class:`.ClauseElement` + """Visit a list of tuples which contain :class:`_expression.ClauseElement` objects. """ dp_clauseelement_list = symbol("CL") - """Visit a list of :class:`.ClauseElement` objects. + """Visit a list of :class:`_expression.ClauseElement` objects. """ dp_clauseelement_unordered_set = symbol("CU") - """Visit an unordered set of :class:`.ClauseElement` objects. """ + """Visit an unordered set of :class:`_expression.ClauseElement` + objects. """ dp_fromclause_ordered_set = symbol("CO") - """Visit an ordered set of :class:`.FromClause` objects. """ + """Visit an ordered set of :class:`_expression.FromClause` objects. """ dp_string = symbol("S") """Visit a plain string value. @@ -320,7 +322,7 @@ class InternalTraversal(util.with_metaclass(_InternalTraversalType, object)): """visit a dialect options structure.""" dp_string_clauseelement_dict = symbol("CD") - """Visit a dictionary of string keys to :class:`.ClauseElement` + """Visit a dictionary of string keys to :class:`_expression.ClauseElement` objects. """ @@ -361,18 +363,20 @@ class InternalTraversal(util.with_metaclass(_InternalTraversalType, object)): """ dp_prefix_sequence = symbol("PS") - """Visit the sequence represented by :class:`.HasPrefixes` - or :class:`.HasSuffixes`. + """Visit the sequence represented by :class:`_expression.HasPrefixes` + or :class:`_expression.HasSuffixes`. """ dp_table_hint_list = symbol("TH") - """Visit the ``_hints`` collection of a :class:`.Select` object. + """Visit the ``_hints`` collection of a :class:`_expression.Select` object + . """ dp_statement_hint_list = symbol("SH") - """Visit the ``_statement_hints`` collection of a :class:`.Select` + """Visit the ``_statement_hints`` collection of a + :class:`_expression.Select` object. """ @@ -383,7 +387,8 @@ class InternalTraversal(util.with_metaclass(_InternalTraversalType, object)): """ dp_dml_ordered_values = symbol("DML_OV") - """visit the values() ordered tuple list of an :class:`.Update` object.""" + """visit the values() ordered tuple list of an + :class:`_expression.Update` object.""" dp_dml_values = symbol("DML_V") """visit the values() dictionary of a :class:`.ValuesBase` @@ -393,7 +398,7 @@ class InternalTraversal(util.with_metaclass(_InternalTraversalType, object)): dp_dml_multi_values = symbol("DML_MV") """visit the values() multi-valued list of dictionaries of an - :class:`~.sql.expression.Insert` object. + :class:`_expression.Insert` object. """ @@ -401,7 +406,7 @@ class InternalTraversal(util.with_metaclass(_InternalTraversalType, object)): class ExtendedInternalTraversal(InternalTraversal): """defines additional symbols that are useful in caching applications. - Traversals for :class:`.ClauseElement` objects only need to use + Traversals for :class:`_expression.ClauseElement` objects only need to use those symbols present in :class:`.InternalTraversal`. However, for additional caching use cases within the ORM, symbols dealing with the :class:`.HasCacheKey` class are added here. @@ -570,14 +575,18 @@ def iterate(obj, opts): The central API feature used by the :func:`.visitors.iterate` and :func:`.visitors.iterate_depthfirst` functions is the - :meth:`.ClauseElement.get_children` method of :class:`.ClauseElement` - objects. This method should return all the :class:`.ClauseElement` objects - which are associated with a particular :class:`.ClauseElement` object. + :meth:`_expression.ClauseElement.get_children` method of + :class:`_expression.ClauseElement` + objects. This method should return all the + :class:`_expression.ClauseElement` objects + which are associated with a particular :class:`_expression.ClauseElement` + object. For example, a :class:`.Case` structure will refer to a series of - :class:`.ColumnElement` objects within its "whens" and "else\_" member + :class:`_expression.ColumnElement` + objects within its "whens" and "else\_" member variables. - :param obj: :class:`.ClauseElement` structure to be traversed + :param obj: :class:`_expression.ClauseElement` structure to be traversed :param opts: dictionary of iteration options. This dictionary is usually empty in modern usage. @@ -603,7 +612,7 @@ def iterate_depthfirst(obj, opts): traversal is configured to be depth-first. - :param obj: :class:`.ClauseElement` structure to be traversed + :param obj: :class:`_expression.ClauseElement` structure to be traversed :param opts: dictionary of iteration options. This dictionary is usually empty in modern usage. @@ -637,11 +646,13 @@ def traverse_using(iterator, obj, visitors): functions. :param iterator: an iterable or sequence which will yield - :class:`.ClauseElement` structures; the iterator is assumed to be the + :class:`_expression.ClauseElement` + structures; the iterator is assumed to be the product of the :func:`.visitors.iterate` or :func:`.visitors.iterate_depthfirst` functions. - :param obj: the :class:`.ClauseElement` that was used as the target of the + :param obj: the :class:`_expression.ClauseElement` + that was used as the target of the :func:`.iterate` or :func:`.iterate_depthfirst` function. :param visitors: dictionary of visit functions. See :func:`.traverse` @@ -679,7 +690,7 @@ def traverse(obj, opts, visitors): The iteration of objects uses the :func:`.visitors.iterate` function, which does a breadth-first traversal using a stack. - :param obj: :class:`.ClauseElement` structure to be traversed + :param obj: :class:`_expression.ClauseElement` structure to be traversed :param opts: dictionary of iteration options. This dictionary is usually empty in modern usage. @@ -718,9 +729,12 @@ def cloned_traverse(obj, opts, visitors): The central API feature used by the :func:`.visitors.cloned_traverse` and :func:`.visitors.replacement_traverse` functions, in addition to the - :meth:`.ClauseElement.get_children` function that is used to achieve - the iteration, is the :meth:`.ClauseElement._copy_internals` method. - For a :class:`.ClauseElement` structure to support cloning and replacement + :meth:`_expression.ClauseElement.get_children` + function that is used to achieve + the iteration, is the :meth:`_expression.ClauseElement._copy_internals` + method. + For a :class:`_expression.ClauseElement` + structure to support cloning and replacement traversals correctly, it needs to be able to pass a cloning function into its internal members in order to make copies of them. |