Skip to content

Conversation

@henadzit
Copy link
Contributor

@henadzit henadzit commented Nov 8, 2024

Description

This PR:

  • Adds support for referencing relationship fields in F(), e.g. F("author__name") that automatically introduces joins to the query
  • Allows referencing annotations in F(), e.g. IntFields.annotate(intnum_plus_1=F("intnum") + 1).annotate(intnum_plus_2=F("intnum_plus_1") + 1)

In order to achieve that, the following implementation details changed

  • The behavior of Expression.resolve was unified to always return a ResolveResult. Previously it could have been either a tuple or dictionary.
  • F was changed to be an Expression instead of pypika's Field. This allowed to move the F's resolution code inside F.resolve and simplify the resolution code in general because F can be treated as other Expressions.
  • CombinedExpression was introduced to handle arithmetic operations on F(), e.g. F("a") + 1. It was inspired by Django's CombinedExpression and replaces pypika's arithmetic. CombinedExpression is a child of Expression, so it can be resolved without knowing the exact type of the object as opposed to pypika's ArithmeticExpression that was used previosly.

As part of this PR, I had to change how custom functions can be defined. It changed from

from tortoise.expressions import F
from pypika.terms import Function

class JsonSet(Function):
    def __init__(self, field: F, expression: str, value: Any):
        super().__init__("JSON_SET", field, expression, value)

to

from tortoise.functions import Function
from pypika.terms import Function as PupikaFunction

# it is a tortoise Function now, not Pypika's Function
class PypikaJsonSet(Function):
    def __init__(self, field: F, expression: str, value: Any):
        super().__init__("JSON_SET", field, expression, value)
    
    database_func = PypikaJsonSet

Effectively now custom functions are supposed to be a tortoise Function, not a Pypika's Function. The change had to be done because the Pypika's Function is no longer compatible with F and, frankly, having the interface that accepts both Pypika's functions and tortoise functions is a bit messy and makes the code quite convoluted.

Motivation and Context

This introduces functionality supported by Django but also there is a clear demand for these features in the tortoise community. The following issues should be fixed by this PR

How Has This Been Tested?

  • Tested on a sample web app
  • Added tests

Checklist:

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added the changelog accordingly.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • All new and existing tests passed.

@henadzit henadzit force-pushed the feat/annotations-in-f branch from 1d68e34 to 5f45331 Compare November 8, 2024 12:09
@coveralls
Copy link

coveralls commented Nov 8, 2024

Pull Request Test Coverage Report for Build 11742066623

Details

  • 216 of 219 (98.63%) changed or added relevant lines in 5 files are covered.
  • 2 unchanged lines in 2 files lost coverage.
  • Overall coverage increased (+0.09%) to 89.162%

Changes Missing Coverage Covered Lines Changed/Added Lines %
tortoise/backends/base/executor.py 13 14 92.86%
tortoise/expressions.py 139 141 98.58%
Files with Coverage Reduction New Missed Lines %
tortoise/queryset.py 1 94.47%
tortoise/backends/base/executor.py 1 91.35%
Totals Coverage Status
Change from base Build 11660093686: 0.09%
Covered Lines: 6084
Relevant Lines: 6709

💛 - Coveralls

@henadzit henadzit force-pushed the feat/annotations-in-f branch from 5f45331 to aadc8f9 Compare November 8, 2024 12:25
res = ResolveResult(
term=term,
joins=function_arg.joins,
output_field=function_arg.output_field, # type: ignore
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why you had to use so many type ignores?

Copy link
Contributor Author

@henadzit henadzit Nov 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch! This is something I never ran into before. Basically the Field class has the following type checking code:

    # These methods are just to make IDE/Linters happy:
    if TYPE_CHECKING:

        def __new__(cls, *args: Any, **kwargs: Any) -> "Field[VALUE]":
            return super().__new__(cls)

        @overload
        def __get__(self, instance: None, owner: Type["Model"]) -> "Field[VALUE]": ...

        @overload
        def __get__(self, instance: "Model", owner: Type["Model"]) -> VALUE: ...

        def __get__(
            self, instance: Optional["Model"], owner: Type["Model"]
        ) -> "Field[VALUE] | VALUE": ...

        def __set__(self, instance: "Model", value: VALUE) -> None: ...

that makes it possible to have type hints for both the Model classes but also for Model instances. However, this seems to limit who can have the field attribute to only Model and its subclasses because of instance and owner arg typing.

I added the Field property to ResolveResult to be able to use Field for type conversions and this is what caused warnings that are being ignored.

I tried to add overloaded versions of __get__ to Field but this looks ugly because Field has to know about the ResolveResult:

        @overload
        def __get__(self, instance: None, owner: Type["Model"]) -> "Field[VALUE]": ...

        @overload
        def __get__(self, instance: "Model", owner: Type["Model"]) -> VALUE: ...

        @overload
        def __get__(
            self, instance: ResolveResult, owner: Type["ResolveResult"]
        ) -> "Field[VALUE]": ...

        def __get__(
            self,
            instance: Union[Optional["Model"], ResolveResult],
            owner: Union[Type["Model"], Type[ResolveResult]],
        ) -> "Field[VALUE] | VALUE": ...

Please let me know if you have ideas on how to handle this better, thanks!

@abondar abondar merged commit fe4dc39 into tortoise:develop Nov 10, 2024
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants