django-stubs icon indicating copy to clipboard operation
django-stubs copied to clipboard

Add ORM protocols `Compilable` and `Resolvable`

Open adamchainz opened this issue 8 months ago • 2 comments

Suggested by @charettes on a Django forum discussion regrading adding types to Django:

from __future__ import annotations

from typing import Protocol

from django.db.models import fields
from django.db.models.sql import compiler, query


class Compilable(Protocol):
    """
    Object that can be compiled to a PEP 249 compliant tuple comprised of
    a SQL string and its associated parameters sequence.

    It can optionally have `as_vendor` methods defined to specialize the
    compilation on different backends (e.g. `as_postgres`).
    """

    def get_source_expressions(self) -> list[Compilable | None]: ...

    def as_sql(
        self, compiler: compiler.SQLCompiler, connection
    ) -> tuple[str, tuple]: ...


class Resolvable(Protocol):
    """
    Object that can resolve any field and transform reference it has in
    the context of a query and return an object ready to be compiled for
    execution.
    """

    output_field: fields.Field

    def get_source_expressions(self) -> list[Resolvable | None]: ...

    def resolve_expression(
        self,
        query: query.Query,
        allow_joins: bool = True,
        reuse: set[str] | None = None,
        summarize: bool = False,
        for_save: bool = False,
    ) -> Compilable: ...

I think we could try adding these in django-stubs and seeing how much simpler and more comprehensible they make things.

adamchainz avatar Mar 15 '25 00:03 adamchainz

I think we could try adding these in django-stubs and seeing how much simpler and more comprehensible they make things.

This will require TYPING_CHECKING only imports, because django-stubs does not have runtime. If you want them to be user accessible, then we can add them to django-stubs-ext

sobolevn avatar Mar 15 '25 08:03 sobolevn

Making them user-accessible is probably the way forwards, so we can document them and explain how to use them. But it would need some experimentation.

adamchainz avatar Mar 15 '25 20:03 adamchainz