Skip to content

Selecting a subquery with a GROUP BY clause produces invalid SQL #1999

@yomatters

Description

@yomatters

Describe the bug
Starting in version 0.24.0, selecting a subquery containing a GROUP BY clause produces invalid SQL. The field names in the GROUP BY clause are given aliases, which causes a SQL error when the query is executed.

To Reproduce
This example script illustrates the problem:

from tortoise import fields, run_async, Tortoise
from tortoise.expressions import Subquery
from tortoise.models import Model


class A(Model):
    id = fields.IntField(primary_key=True)
    name = fields.TextField()


class B(Model):
    id = fields.IntField(primary_key=True)
    name = fields.TextField()


async def main():
    await Tortoise.init(db_url="sqlite://:memory:", modules={"models": ["__main__"]})
    await Tortoise.generate_schemas()

    query = A.annotate(b_name=Subquery(B.all().group_by("name").order_by("name").limit(1).values("name")))
    print(query.sql())

run_async(main())

Starting in version 0.24.0, the output of the script contains an invalid field alias b__name in the GROUP BY clause of the subquery:

SELECT "id","name",(SELECT "name" "name" FROM "b" GROUP BY "name" "b__name" ORDER BY "name" ASC LIMIT ?) "b_name" FROM "a"

Expected behavior
Versions 0.23.0 and earlier produce a valid GROUP BY clause without field aliases:

SELECT "id","name",(SELECT "name" "name" FROM "b" GROUP BY "name" ORDER BY "name" ASC LIMIT ?) "b_name" FROM "a"

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions