summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/orm/context.py
Commit message (Collapse)AuthorAgeFilesLines
...
* Remove object in class definitionFederico Caselli2021-11-221-2/+2
| | | | | References: #4600 Change-Id: I2a62ddfe00bc562720f0eae700a497495d7a987a
* warnings: select_entity_from()Mike Bayer2021-10-251-2/+10
| | | | Change-Id: I8c259e61134c38a1fa907c308068337473c82914
* warn or deprecate for auto-aliasing in joinsMike Bayer2021-09-281-0/+24
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | An extra layer of warning messages has been added to the functionality of :meth:`_orm.Query.join` and the ORM version of :meth:`_sql.Select.join`, where a few places where "automatic aliasing" continues to occur will now be called out as a pattern to avoid, mostly specific to the area of joined table inheritance where classes that share common base tables are being joined together without using explicit aliases. One case emits a legacy warning for a pattern that's not recommended, the other case is fully deprecated. The automatic aliasing within ORM join() which occurs for overlapping mapped tables does not work consistently with all APIs such as ``contains_eager()``, and rather than continue to try to make these use cases work everywhere, replacing with a more user-explicit pattern is clearer, less prone to bugs and simplifies SQLAlchemy's internals further. The warnings include links to the errors.rst page where each pattern is demonstrated along with the recommended pattern to fix. * Improved the exception message generated when configuring a mapping with joined table inheritance where the two tables either have no foreign key relationships set up, or where they have multiple foreign key relationships set up. The message is now ORM specific and includes context that the :paramref:`_orm.Mapper.inherit_condition` parameter may be needed particularly for the ambiguous foreign keys case. * Add explicit support in the _expect_warnings() assertion for nested _expect_warnings calls * generalize the NoCache fixture, which we also need to catch warnings during compilation consistently * generalize the __str__() method for the HasCode mixin so all warnings and errors include the code link in their string Fixes: #6974 Change-Id: I84ed79ba2112c39eaab7973b6d6f46de7fa80842
* turn off deduping for col expressionsMike Bayer2021-09-041-8/+13
| | | | | | | | | | | | | Fixed ORM issue where column expressions passed to ``query()`` or ORM-enabled ``select()`` would be deduplicated on the identity of the object, such as a phrase like ``select(A.id, null(), null())`` would produce only one "NULL" expression, which previously was not the case in 1.3. However, the change also allows for ORM expressions to render as given as well, such as ``select(A.data, A.data)`` will produce a result row with two columns. Fixes: #6979 Change-Id: I4dd59d4c7b1baa711b686379eb959f87c44841c4
* qualify compile_state updates for non-current entitiesMike Bayer2021-08-231-11/+31
| | | | | | | | | | | Fixed issue in recently repaired ``Query.with_entities()`` method where the flag that determines automatic uniquing for legacy ORM ``Query`` objects only would be set to ``True`` inappropriately in cases where the ``with_entities()`` call would be setting the ``Query`` to return column-only rows, which are not uniqued. Fixes: #6924 Change-Id: I81120823914c989bb7a4d13ef2ec08809d8e5a4d
* remove lambda caching from loader strategiesMike Bayer2021-08-171-5/+5
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Adjusted ORM loader internals to no longer use the "lambda caching" system that was added in 1.4, as well as repaired one location that was still using the previous "baked query" system for a query. The lambda caching system remains an effective way to reduce the overhead of building up queries that have relatively fixed usage patterns. In the case of loader strategies, the queries used are responsible for moving through lots of arbitrary options and criteria, which is both generated and sometimes consumed by end-user code, that make the lambda cache concept not any more efficient than not using it, at the cost of more complexity. In particular the problems noted by :ticket:`6881` and :ticket:`6887` are made considerably less complicated by removing this feature internally. Fixed an issue where the :class:`_orm.Bundle` construct would not create proper cache keys, leading to inefficient use of the query cache. This had some impact on the "selectinload" strategy and was identified as part of :ticket:`6889`. Added a Select._create_raw_select() method which essentially performs ``__new__`` and then populates ``__dict__`` directly, with no coercions. This saves most of the overhead time that the lambda caching system otherwise seeks to avoid. Includes removal of bakedquery from mapper->_subclass_load_via_in() which was overlooked from the 1.4 refactor. Fixes: #6079 Fixes: #6889 Change-Id: Ieac2d9d709b71ec4270e5c121fbac6ac870e2bb1
* add columns_clause_froms and related use casesMike Bayer2021-08-071-0/+15
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | Added new attribute :attr:`_sql.Select.columns_clause_froms` that will retrieve the FROM list implied by the columns clause of the :class:`_sql.Select` statement. This differs from the old :attr:`_sql.Select.froms` collection in that it does not perform any ORM compilation steps, which necessarily deannotate the FROM elements and do things like compute joinedloads etc., which makes it not an appropriate candidate for the :meth:`_sql.Select.select_from` method. Additionally adds a new parameter :paramref:`_sql.Select.with_only_columns.maintain_column_froms` that transfers this collection to :meth:`_sql.Select.select_from` before replacing the columns collection. In addition, the :attr:`_sql.Select.froms` is renamed to :meth:`_sql.Select.get_final_froms`, to stress that this collection is not a simple accessor and is instead calculated given the full state of the object, which can be an expensive call when used in an ORM context. Additionally fixes a regression involving the :func:`_orm.with_only_columns` function to support applying criteria to column elements that were replaced with either :meth:`_sql.Select.with_only_columns` or :meth:`_orm.Query.with_entities` , which had broken as part of :ticket:`6503` released in 1.4.19. Fixes: #6808 Change-Id: Ib5d66cce488bbaca06dab4f68fb5cdaa73e8823e
* Apply new uniquing rules for future ORM selectsMike Bayer2021-07-211-2/+11
| | | | | | | | | | | | | | | | | | | | Fixed issue where usage of the :meth:`_result.Result.unique` method with an ORM result that included column expressions with unhashable types, such as ``JSON`` or ``ARRAY`` using non-tuples would silently fall back to using the ``id()`` function, rather than raising an error. This now raises an error when the :meth:`_result.Result.unique` method is used in a 2.0 style ORM query. Additionally, hashability is assumed to be True for result values of unknown type, such as often happens when using SQL functions of unknown return type; if values are truly not hashable then the ``hash()`` itself will raise. For legacy ORM queries, since the legacy :class:`_orm.Query` object uniquifies in all cases, the old rules remain in place, which is to use ``id()`` for result values of unknown type as this legacy uniquing is mostly for the purpose of uniquing ORM entities and not column values. Fixes: #6769 Change-Id: I5747f706f1e97c78867b5cf28c73360497273808
* Merge "Add additional support to honor _proxy_key in Core selects"mike bayer2021-07-091-1/+1
|\
| * Add additional support to honor _proxy_key in Core selectsMike Bayer2021-07-051-1/+1
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Fixed ORM regression where ad-hoc label names generated for hybrid properties and potentially other similar types of ORM-enabled expressions would usually be propagated outwards through subqueries, allowing the name to be retained in the final keys of the result set even when selecting from subqueries. Additional state is now tracked in this case that isn't lost when a hybrid is selected out of a Core select / subquery. as we have removed things like column.label() from ORM, since we now have to export the cols with the same names as what we will render, experiment with giving a greater role to the _proxy_key annotation so that a desired name can be carried through more transarently. Fixes: #6718 Change-Id: Icb313244c13ea1a8f58d3e05d07aa3e1039e15bf
* | Replace all http:// links to https://Federico Caselli2021-07-041-1/+1
|/ | | | | | Also replace http://pypi.python.org/pypi with https://pypi.org/project Change-Id: I84b5005c39969a82140706472989f2a30b0c7685
* Export deferred columns but not col props; fix CTE labelingMike Bayer2021-06-221-16/+7
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Refined the behavior of ORM subquery rendering with regards to deferred columns and column properties to be more compatible with that of 1.3 while also providing for 1.4's newer features. As a subquery in 1.4 does not make use of loader options, including :func:`_orm.deferred`, a subquery that is against an ORM entity with deferred attributes will now render those deferred attributes that refer directly to mapped table columns, as these are needed in the outer SELECT if that outer SELECT makes use of these columns; however a deferred attribute that refers to a composed SQL expression as we normally do with :func:`_orm.column_property` will not be part of the subquery, as these can be selected explicitly if needed in the subquery. If the entity is being SELECTed from this subquery, the column expression can still render on "the outside" in terms of the derived subquery columns. This produces essentially the same behavior as when working with 1.3. However in this case the fix has to also make sure that the ``.selected_columns`` collection of an ORM-enabled :func:`_sql.select` also follows these rules, which in particular allows recursive CTEs to render correctly in this scenario, which were previously failing to render correctly due to this issue. As part of this change the _exported_columns_iterator() method has been removed and logic simplified to use ._all_selected_columns from any SelectBase object where _exported_columns_iterator() was used before. Additionally sets up UpdateBase to include ReturnsRows in its hierarchy; the literal point of ReturnsRows was to be a common base for UpdateBase and SelectBase so it was kind of weird it wasn't there. Fixes: #6661 Fixed issue in CTE constructs mostly relevant to ORM use cases where a recursive CTE against "anonymous" labels such as those seen in ORM ``column_property()`` mappings would render in the ``WITH RECURSIVE xyz(...)`` section as their raw internal label and not a cleanly anonymized name. Fixes: #6663 Change-Id: I26219d4d8e6c0915b641426e9885540f74fae4d2
* memoize current options and joins w with_entities/with_only_colsMike Bayer2021-06-171-41/+162
| | | | | | | | | | | | | | | | Fixed further regressions in the same area as that of :ticket:`6052` where loader options as well as invocations of methods like :meth:`_orm.Query.join` would fail if the left side of the statement for which the option/join depends upon were replaced by using the :meth:`_orm.Query.with_entities` method, or when using 2.0 style queries when using the :meth:`_sql.Select.with_only_columns` method. A new set of state has been added to the objects which tracks the "left" entities that the options / join were made against which is memoized when the lead entities are changed. Fixes: #6503 Fixes: #6253 Change-Id: I211b2af98b0b20d1263fb15dc513884dcc5de6a4
* restore adapter logic in ORM loadingMike Bayer2021-06-081-10/+14
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | Fixed regression involving how the ORM would resolve a given mapped column to a result row, where under cases such as joined eager loading, a slightly more expensive "fallback" could take place to set up this resolution due to some logic that was removed since 1.3. The issue could also cause deprecation warnings involving column resolution to be emitted when using a 1.4 style query with joined eager loading. In order to ensure we don't look up columns by string name in the ORM, we've turned on future_result=True in all cases, which I thought was already the assumption here, but apparently not. That in turn led to the issue that Session autocommit relies on close_with_result=True, which is legacy result only. This was also hard to figure out. So a new exception is raised if one tries to use future_result=True along with close_with_result, and the Session now has an explicit path for "autocommit" that sets these flags to their legacy values. This does leave the possibility of some of these fallback cases emitting warnings for users using session in autocommit along with joined inheritance and column properties, as this patch identifies that joined inheritance + column properties produce the fallback logic when looking up in the result via the adapted column, which in those tests is actually a Label object that doesn't adapt nicely. Fixes: #6596 Change-Id: I107a47e873ae05ab50853bb00a9ea0e1a88d5aee
* init extra_criteria_entities in fromstatement w/ DMLMike Bayer2021-06-071-1/+3
| | | | | | | | | | | | Fixed issue in experimental "select ORM objects from INSERT/UPDATE" use case where an error was raised if the statement were against a single-table-inheritance subclass. Additionally makes some adjustments in the SQL assertion fixture to test a FromStatement w/ DML. Fixes: #6591 Change-Id: I53a627ab18a01dc6d9b5037e28312a1177891327
* Run SelectState from obj normalize ahead of calcing ORM joinsMike Bayer2021-05-171-2/+8
| | | | | | | | | | Fixed regression where the full combination of joined inheritance, global with_polymorphic, self-referential relationship and joined loading would fail to be able to produce a query with the scope of lazy loads and object refresh operations that also attempted to render the joined loader. Fixes: #6495 Change-Id: If74a744c237069e3a89617498096c18b9b6e5dde
* Correct cache key for proxy_owner, with_context_optionsMike Bayer2021-05-101-2/+2
| | | | | | | | | | | | | | | | | | Fixed issue in subquery loader strategy which prevented caching from working correctly. This would have been seen in the logs as a "generated" message instead of "cached" for all subqueryload SQL emitted, which by saturating the cache with new keys would degrade overall performance; it also would produce "LRU size alert" warnings. In this issue we also observe that the local LRU cache for lazyloader and selectinloader will get used for all subsequent loads as well, which makes it more likely to hit the limit of 30. However rather than trying to work this out, it would be better if we removed the loader-local LRU caches altogether once we are confident these are working well. Fixes: #6459 Change-Id: Id953e8f75536bb87f7e3315929cebcd8f84a5a50
* accommodate HasEntityNamespace in context.all_selected_columnsMike Bayer2021-04-291-6/+7
| | | | | | | | | | Fixed regression in hybrid_property where a hybrid against a SQL function would generate an ``AttributeError`` when attempting to generate an entry for the ``.c`` collection of a subquery in some cases; among other things this would impact its use in cases like that of ``Query.count()``. Fixes: #6401 Change-Id: Icc243c699e9a5c88448076c6427ec389eaa8b8ed
* Merge "add optional proxy_class to track w/ proxy_key"mike bayer2021-04-281-1/+2
|\
| * add optional proxy_class to track w/ proxy_keyMike Bayer2021-04-281-1/+2
| | | | | | | | | | | | | | | | | | | | | | Fixed regression in ORM where using hybrid property to indicate an expression from a different entity would confuse the column-labeling logic in the ORM and attempt to derive the name of the hybrid from that other class, leading to an attribute error. The owning class of the hybrid attribute is now tracked along with the name. Fixes: #6386 Change-Id: Ica9497ea34fef799d6265de44104c1f3f3b30232
* | don't mutate the statement in ORM compileMike Bayer2021-04-271-9/+9
|/ | | | | | | | | | | Fixed issue where using a :class:`_sql.Select` as a subquery in an ORM context would modify the :class:`_sql.Select` in place to disable eagerloads on that object, which would then cause that same :class:`_sql.Select` to not eagerload if it were then re-used in a top-level execution context. Fixes: #6378 Change-Id: I945048c4c148587b933fb65a3fc83a05d05c052d
* omit text from selected_columns; clear memoizationsMike Bayer2021-04-221-1/+12
| | | | | | | | | | | | | | | | | | | | | | | | | Fixed regression where usage of the :func:`_sql.text` construct inside the columns clause of a :class:`_sql.Select` construct, which is better handled by using a :func:`_sql.literal_column` construct, would nonetheless prevent constructs like :func:`_sql.union` from working correctly. Other use cases, such as constructing subuqeries, continue to work the same as in prior versions where the :func:`_sql.text` construct is silently omitted from the collection of exported columns. Also repairs similar use within the ORM. This adds a new internal method _all_selected_columns. The existing "selected_columns" collection can't store a TextClause and this never worked, so they are omitted. The TextClause is also not "exported", i.e. available for SELECT from a subquery, as was already the case in 1.3, so the "exported_columns" and "exported_columns_iterator" accessors are where we now omit TextClause. Fixed regression involving legacy methods such as :meth:`_sql.Select.append_column` where internal assertions would fail. Fixes: #6343 Fixes: #6261 Change-Id: I7c2e5b9ae5d94131c77599a020f4310dcf812bcf
* Merge "Ensure ClauseAdapter treats FunctionElement as a ColumnElement"mike bayer2021-03-191-0/+2
|\
| * Ensure ClauseAdapter treats FunctionElement as a ColumnElementMike Bayer2021-03-181-0/+2
| | | | | | | | | | | | | | | | | | | | Fixed regression where use of an unnamed SQL expression such as a SQL function would raise a column targeting error if the query itself were using joinedload for an entity and was also being wrapped in a subquery by the joinedload eager loading process. Fixes: #6086 Change-Id: I22cf4d6974685267c4f903bd7639be8271c6c1ef
* | repair legacy_last_joined_entity for no onclauseMike Bayer2021-03-181-1/+1
|/ | | | | | | | | Fixed regression where the :meth:`_orm.Query.filter_by` method would fail to locate the correct source entity if the :meth:`_orm.Query.join` method had been used targeting an entity without any kind of ON clause. Fixes: #6092 Change-Id: I38d9099844f842f314c6673bd922467242409cdb
* improve targeting and labeling for unary() in columns clauseMike Bayer2021-03-061-15/+73
| | | | | | | | | | | | | | | | | | | | | | Fixed regression where usage of the standalone :func:`_sql.distinct()` used in the form of being directly SELECTed would fail to be locatable in the result set by column identity, which is how the ORM locates columns. While standalone :func:`_sql.distinct()` is not oriented towards being directly SELECTed (use :meth:`_sql.select.distinct` for a regular ``SELECT DISTINCT..``) , it was usable to a limited extent in this way previously (but wouldn't work in subqueries, for example). The column targeting for unary expressions such as "DISTINCT <col>" has been improved so that this case works again, and an additional improvement has been made so that usage of this form in a subquery at least generates valid SQL which was not the case previously. The change additionally enhances the ability to target elements in ``row._mapping`` based on SQL expression objects in ORM-enabled SELECT statements, including whether the statement was invoked by ``connection.execute()`` or ``session.execute()``. Fixes: #6008 Change-Id: I5cfa39435f5418861d70a7db8f52ab4ced6a792e
* Allow update.returing() to work with from_statement()Mike Bayer2021-02-141-3/+10
| | | | | | | | | | The ORM used in :term:`2.0 style` can now return ORM objects from the rows returned by an UPDATE..RETURNING or INSERT..RETURNING statement, by supplying the construct to :meth:`_sql.Select.from_statement` in an ORM context. Change-Id: I59c9754ff1cb3184580dd5194ecd2971d4e7f8e8 References: #5940
* Further refine labeling for renamed columnsMike Bayer2021-02-121-2/+2
| | | | | | | | | | | | | | | Forked from I22f6cf0f0b3360e55299cdcb2452cead2b2458ea we are attempting to decide the case for columns mapped under a different name. since the .key feature of Column seems to support this fully, see if an annotation can be used to indicate an effective .key for a column. The effective change is that the labeling of column expressions in rows has been improved to retain the original name of the ORM attribute even if used in a subquery. References: #5933 Change-Id: If251f556f7d723f50d349f765f1690d6c679d2ef
* Apply consistent labeling for all future style ORM queriesMike Bayer2021-02-111-22/+67
| | | | | | | | | | | | | | | | Fixed issue in new 1.4/2.0 style ORM queries where a statement-level label style would not be preserved in the keys used by result rows; this has been applied to all combinations of Core/ORM columns / session vs. connection etc. so that the linkage from statement to result row is the same in all cases. also repairs a cache key bug where query.from_statement() vs. select().from_statement() would not be disambiguated; the compile options were not included in the cache key for FromStatement. Fixes: #5933 Change-Id: I22f6cf0f0b3360e55299cdcb2452cead2b2458ea
* Replace with_labels() and apply_labels() in ORM/CoreGord Thompson2021-01-261-2/+4
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Replace :meth:`_orm.Query.with_labels` and :meth:`_sql.GenerativeSelect.apply_labels` with explicit getters and setters ``get_label_style`` and ``set_label_style`` to accommodate the three supported label styles: ``LABEL_STYLE_DISAMBIGUATE_ONLY`` (default), ``LABEL_STYLE_TABLENAME_PLUS_COL``, and ``LABEL_STYLE_NONE``. In addition, for Core and "future style" ORM queries, ``LABEL_STYLE_DISAMBIGUATE_ONLY`` is now the default label style. This style differs from the existing "no labels" style in that labeling is applied in the case of column name conflicts; with ``LABEL_STYLE_NONE``, a duplicate column name is not accessible via name in any case. For legacy ORM queries using :class:`_query.Query`, the table-plus-column names labeling style applied by ``LABEL_STYLE_TABLENAME_PLUS_COL`` continues to be used so that existing test suites and logging facilities see no change in behavior by default, however this style of labeling is no longer required for SQLAlchemy queries to function, as result sets are commonly matched to columns using a positional approach since SQLAlchemy 1.0. Within test suites, all use of apply_labels() / use_labels now uses the new methods. New tests added to test/sql/test_deprecations.py nad test/orm/test_deprecations.py to cover just the old apply_labels() method call. Tests in ORM that made explicit use apply_labels()/ etc. where it isn't needed for the ORM to work correctly use default label style now. Co-authored-by: Mike Bayer <mike_mp@zzzcomputing.com> Fixes: #4757 Change-Id: I5fdcd2ed4ae8c7fe62f8be2b6d0e8f66409b6a54
* happy new yearMike Bayer2021-01-041-1/+1
| | | | Change-Id: Ic5bb19ca8be3cb47c95a0d3315d84cb484bac47c
* Repair and cover adaption call w/ ORM having()esoh2020-12-191-1/+1
| | | | | | | | | | | | | | Fixed 1.4 regression where the use of :meth:`_orm.Query.having` in conjunction with queries with internally adapted SQL elements (common in inheritance scenarios) would fail due to an incorrect function call. Pull request courtesy esoh. Fixes: #5781 Closes: #5782 Pull-request: https://github.com/sqlalchemy/sqlalchemy/pull/5782 Pull-request-sha: 5d37b0be0db68ec2a4dfea552ee47bcb3ef6778c Change-Id: I123b2c0a4a23b7c7c72929dec79801726afc71ee
* Ensure the "orm" plugin is used unconditionally for bundlesMike Bayer2020-11-161-5/+14
| | | | | | | | | | | | | | This also introduces that the "orm" plugin may be used when the plugin_subject is None. Fixed regression where the :paramref:`.Bundle.single_entity` flag would take effect for a :class:`.Bundle` even though it were not set. Additionally, this flag is legacy as it only makes sense for the :class:`_orm.Query` object and not 2.0 style execution. a deprecation warning is emitted when used with new-style execution. Fixes: #5702 Change-Id: If9f43365b9d966cb398890aeba2efa555658a7e5
* tutorial 2.0 WIPreview/mike_bayer/tutorial20Mike Bayer2020-10-311-0/+10
| | | | | | | | | | | | | | Add SelectBase.exists() method as it seems strange this is not available already. The Exists construct itself does not provide full SELECT-building capabilities so it makes sense this should be used more like a scalar_subquery. Make sure stream_results is getting set up when yield_per is used, for 2.0 style statements as well. this was hardcoded inside of Query.yield_per() and is now moved to take place within QueryContext. Change-Id: Icafcd4fd9b708772343d56edf40995c9e8f835d6
* upgrade to black 20.8b1Mike Bayer2020-09-281-3/+15
| | | | | | | It's better, the majority of these changes look more readable to me. also found some docstrings that had formatting / quoting issues. Change-Id: I582a45fde3a5648b2f36bab96bad56881321899b
* build the full compilestate every timeMike Bayer2020-09-271-2/+1
| | | | | | | | | | the ORMSelectCompileState was trying to get away with not building out the "froms" list of the state, but we need this for select.froms. Build this out and add some tests for select(), including some other state-oriented use cases. Fixes: #5614 Change-Id: I29ca200f292cbae87c722bc97a89d7c453d7d27a
* Provide a more detailed error message for Query.join()RamonWill2020-08-311-2/+24
| | | | | | | | | | | | | | An :class:`.ArgumentError` with more detail is now raised if the target parameter for :meth:`_query.Query.join` is set to an unmapped object. Prior to this change a less detailed ``AttributeError`` was raised. Pull request courtesy Ramon Williams. Fixes: #4428 Closes: #5452 Pull-request: https://github.com/sqlalchemy/sqlalchemy/pull/5452 Pull-request-sha: b148df547037e9a254fe331eff8e922c78426261 Change-Id: I873453d1fdb651178216aac698baac63ae5a94e8
* Further fixes for ticket 5470Mike Bayer2020-08-131-1/+5
| | | | | | | | | | The fix for #5470 didn't actually take into account that the "distinct" logic in query was also doubling up the criteria. Added many more tests. the 1.3 version here will be different than 1.4 as the regression is not quite the same. Fixes: #5470 Change-Id: I16a23917cab175761de9c867d9d9ac55031d9b97
* Implement relationship AND criteria; global loader criteriaMike Bayer2020-08-051-28/+79
| | | | | | | | | | | | | | | | | | | Added the ability to add arbitrary criteria to the ON clause generated by a relationship attribute in a query, which applies to methods such as :meth:`_query.Query.join` as well as loader options like :func:`_orm.joinedload`. Additionally, a "global" version of the option allows limiting criteria to be applied to particular entities in a query globally. Documentation is minimal at this point, new examples will be coming in a subsequent commit. Some adjustments to execution options in how they are represented in the ORMExecuteState as well as well as a few ORM tests that forgot to get merged in a preceding commit. Fixes: #4472 Change-Id: I2b8fc57092dedf35ebd16f6343ad0f0d7d332beb
* Convert lazy loader, selectinload, load_on_ident to lambda statementsMike Bayer2020-08-051-2/+14
| | | | | | | | | Building on newly robust lambdas in I29a513c98917b1d503abfdd61e6b6e8800851aa8, convert key loading off of the "baked" system so that baked is no longer used by the ORM. Change-Id: I3abfb45dd6e50f84f29d39434caa0b550ce27864
* Convert remaining ORM APIs to support 2.0 styleMike Bayer2020-07-111-16/+43
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | This is kind of a mixed bag of all kinds to help get us to 1.4 betas. The documentation stuff is a work in progress. Lots of other relatively small changes to APIs and things. More commits will follow to continue improving the documentation and transitioning to the 1.4/2.0 hybrid documentation. In particular some refinements to Session usage models so that it can match Engine's scoping / transactional patterns, and a decision to start moving away from "subtransactions" completely. * add select().from_statement() to produce FromStatement in an ORM context * begin referring to select() that has "plugins" for the few edge cases where select() will have ORM-only behaviors * convert dynamic.AppenderQuery to its own object that can use select(), though at the moment it uses Query to support legacy join calling forms. * custom query classes for AppenderQuery are replaced by do_orm_execute() hooks for custom actions, a separate gerrit will document this * add Session.get() to replace query.get() * Deprecate session.begin->subtransaction. propose within the test suite a hypothetical recipe for apps that rely on this pattern * introduce Session construction level context manager, sessionmaker context manager, rewrite the whole top of the session_transaction.rst documentation. Establish context manager patterns for Session that are identical to engine * ensure same begin_nested() / commit() behavior as engine * devise all new "join into an external transaction" recipe, add test support for it, add rules into Session so it just works, write new docs. need to ensure this doesn't break anything * vastly reduce the verbosity of lots of session docs as I dont think people read this stuff and it's difficult to keep current in any case * constructs like case(), with_only_columns() really need to move to *columns, add a coercion rule to just change these. * docs need changes everywhere I look. in_() is not in the Core tutorial? how do people even know about it? Remove tons of cruft from Select docs, etc. * build a system for common ORM options like populate_existing and autoflush to populate from execution options. * others? Change-Id: Ia4bea0f804250e54d90b3884cf8aab8b66b82ecf
* Add future=True to create_engine/Session; unify select()Mike Bayer2020-07-081-9/+19
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Several weeks of using the future_select() construct has led to the proposal there be just one select() construct again which features the new join() method, and otherwise accepts both the 1.x and 2.x argument styles. This would make migration simpler and reduce confusion. However, confusion may be increased by the fact that select().join() is different Current thinking is we may be better off with a few hard behavioral changes to old and relatively unknown APIs rather than trying to play both sides within two extremely similar but subtly different APIs. At the moment, the .join() thing seems to be the only behavioral change that occurs without the user taking any explicit steps. Session.execute() will still behave the old way as we are adding a future flag. This change also adds the "future" flag to Session() and session.execute(), so that interpretation of the incoming statement, as well as that the new style result is returned, does not occur for existing applications unless they add the use of this flag. The change in general is moving the "removed in 2.0" system further along where we want the test suite to fully pass even if the SQLALCHEMY_WARN_20 flag is set. Get many tests to pass when SQLALCHEMY_WARN_20 is set; this should be ongoing after this patch merges. Improve the RemovedIn20 warning; these are all deprecated "since" 1.4, so ensure that's what the messages read. Make sure the inforamtion link is on all warnings. Add deprecation warnings for parameters present and add warnings to all FromClause.select() types of methods. Fixes: #5379 Fixes: #5284 Change-Id: I765a0b912b3dcd0e995426427d8bb7997cbffd51 References: #5159
* introduce deferred lambdasMike Bayer2020-07-031-14/+34
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | The coercions system allows us to add in lambdas as arguments to Core and ORM elements without changing them at all. By allowing the lambda to produce a deterministic cache key where we can also cheat and yank out literal parameters means we can move towards having 90% of "baked" functionality in a clearer way right in Core / ORM. As a second step, we can have whole statements inside the lambda, and can then add generation with __add__(), so then we have 100% of "baked" functionality with full support of ad-hoc literal values. Adds some more short_selects tests for the moment for comparison. Other tweaks inside cache key generation as we're trying to approach a certain level of performance such that we can remove the use of "baked" from the loader strategies. As we have not yet closed #4639, however the caching feature has been fully integrated as of b0cfa7379cf8513a821a3dbe3028c4965d9f85bd, we will also add complete caching documentation here and close that issue as well. Closes: #4639 Fixes: #5380 Change-Id: If91f61527236fd4d7ae3cad1f24c38be921c90ba
* Fix a wide variety of typos and broken linksaplatkouski2020-06-251-10/+10
| | | | | | | | | | | | Note the PR has a few remaining doc linking issues listed in the comment that must be addressed separately. Signed-off-by: aplatkouski <5857672+aplatkouski@users.noreply.github.com> Closes: #5371 Pull-request: https://github.com/sqlalchemy/sqlalchemy/pull/5371 Pull-request-sha: 7e7d233cf3a0c66980c27db0fcdb3c7d93bc2510 Change-Id: I9c36e8d8804483950db4b42c38ee456e384c59e3
* Propose using RETURNING for bulk updates, deletesMike Bayer2020-06-231-5/+36
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | This patch makes several improvements in the area of bulk updates and deletes as well as the new session mechanics. RETURNING is now used for an UPDATE or DELETE statement emitted for a diaelct that supports "full returning" in order to satisfy the "fetch" strategy; this currently includes PostgreSQL and SQL Server. The Oracle dialect does not support RETURNING for more than one row, so a new dialect capability "full_returning" is added in addition to the existing "implicit_returning", indicating this dialect supports RETURNING for zero or more rows, not just a single identity row. The "fetch" strategy will gracefully degrade to the previous SELECT mechanics for dialects that do not support RETURNING. Additionally, the "fetch" strategy will attempt to use evaluation for the VALUES that were UPDATEd, rather than just expiring the updated attributes. Values should be evalutable in all cases where the value is not a SQL expression. The new approach also incurs some changes in the session.execute mechanics, where do_orm_execute() event handlers can now be chained to each return results; this is in turn used by the handler to detect on a per-bind basis if the fetch strategy needs to do a SELECT or if it can do RETURNING. A test suite is added to test_horizontal_shard that breaks up a single UPDATE or DELETE operation among multiple backends where some are SQLite and don't support RETURNING and others are PostgreSQL and do. The session event mechanics are corrected in terms of the "orm pre execute" hook, which now receives a flag "is_reentrant" so that the two ORM implementations for this can skip on their work if they are being called inside of ORMExecuteState.invoke(), where previously bulk update/delete were calling its SELECT a second time. In order for "fetch" to get the correct identity when called as pre-execute, it also requests the identity_token for each mapped instance which is now added as an optional capability of a SELECT for ORM columns. the identity_token that's placed by horizontal_sharding is now made available within each result row, so that even when fetching a merged result of plain rows we can tell which row belongs to which identity token. The evaluator that takes place within the ORM bulk update and delete for synchronize_session="evaluate" now supports the IN and NOT IN operators. Tuple IN is also supported. Fixes: #1653 Change-Id: I2292b56ae004b997cef0ba4d3fc350ae1dd5efc1
* perf tweaksMike Bayer2020-06-191-43/+43
| | | | | | | | | | | | | | - avoid abc checks in distill_20 - ColumnEntity subclasses are unique to their compile state and have no querycontext specific state. They can do a simple memoize of their fetch_column without using attributes, and they can memoize their _getter() too so that it goes into the cache, just like instance_processor() does. - unify ORMColumnEntity and RawColumnEntity for the row processor part, add some test coverage for the case where it is used in a from_statement - do a faster generate if there are no memoized entries - query._params is always immutabledict Change-Id: I1e2dfe607a1749b5b434fc11f9348ee631501dfa
* Turn on caching everywhere, add loggingMike Bayer2020-06-101-12/+25
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | A variety of caching issues found by running all tests with statement caching turned on. The cache system now has a more conservative approach where any subclass of a SQL element will by default invalidate the cache key unless it adds the flag inherit_cache=True at the class level, or if it implements its own caching. Add working caching to a few elements that were omitted previously; fix some caching implementations to suit lesser used edge cases such as json casts and array slices. Refine the way BaseCursorResult and CursorMetaData interact with caching; to suit cases like Alembic modifying table structures, don't cache the cursor metadata if it were created against a cursor.description using non-positional matching, e.g. "select *". if a table re-ordered its columns or added/removed, now that data is obsolete. Additionally we have to adapt the cursor metadata _keymap regardless of if we just processed cursor.description, because if we ran against a cached SQLCompiler we won't have the right columns in _keymap. Other refinements to how and when we do this adaption as some weird cases were exposed in the Postgresql dialect, a text() construct that names just one column that is not actually in the statement. Fixed that also as it looks like a cut-and-paste artifact that doesn't actually affect anything. Various issues with re-use of compiled result maps and cursor metadata in conjunction with tables being changed, such as change in order of columns. mappers can be cleared but the class remains, meaning a mapper has to use itself as the cache key not the class. lots of bound parameter / literal issues, due to Alembic creating a straight subclass of bindparam that renders inline directly. While we can update Alembic to not do this, we have to assume other people might be doing this, so bindparam() implements the inherit_cache=True logic as well that was a bit involved. turn on cache stats in logging. Includes a fix to subqueryloader which moves all setup to the create_row_processor() phase and elminates any storage within the compiled context. This includes some changes to create_row_processor() signature and a revising of the technique used to determine if the loader can participate in polymorphic queries, which is also applied to selectinloading. DML update.values() and ordered_values() now coerces the keys as we have tests that pass an arbitrary class here which only includes __clause_element__(), so the key can't be cached unless it is coerced. this in turn changed how composite attributes support bulk update to use the standard approach of ClauseElement with annotations that are parsed in the ORM context. memory profiling successfully caught that the Session from Query was getting passed into _statement_20() so that was a big win for that test suite. Apparently Compiler had .execute() and .scalar() methods stuck on it, these date back to version 0.4 and there was a single test in the PostgreSQL dialect tests that exercised it for no apparent reason. Removed these methods as well as the concept of a Compiler holding onto a "bind". Fixes: #5386 Change-Id: I990b43aab96b42665af1b2187ad6020bee778784
* Convert bulk update/delete to new execution modelMike Bayer2020-06-061-1/+3
| | | | | | | | | | | | | | | This reorganizes the BulkUD model in sqlalchemy.orm.persistence to be based on the CompileState concept and to allow plain update() / delete() to be passed to session.execute() where the ORM synchronize session logic will take place. Also gets "synchronize_session='fetch'" working with horizontal sharding. Adding a few more result.scalar_one() types of methods as scalar_one() seems like what is normally desired. Fixes: #5160 Change-Id: I8001ebdad089da34119eb459709731ba6c0ba975
* Inline a few ORM arguments, othersMike Bayer2020-06-031-15/+7
| | | | | | small changes Change-Id: Id89a0651196c431d0aaf6935f5a4e7b12dd70c6c
* Improve rendering of core statements w/ ORM elementsMike Bayer2020-05-311-252/+266
| | | | | | | | | | | | | | | | | | | | This patch contains a variety of ORM and expression layer tweaks to support ORM constructs in select() statements, without the 1.3.x requiremnt in Query that a full _compile_context() + new select() is needed in order to get a working statement object. Includes such tweaks as the ability to implement aliased class of an aliased class, as we are looking to fully support ACs against subqueries, as well as the ability to access anonymously-labeled ColumnProperty expressions within subqueries by naming the ".key" of the label after the property key. Some tuning to query.join() as well as ORMJoin internals to allow things to work more smoothly. Change-Id: Id810f485c5f7ed971529489b84694e02a3356d6d