Skip to content

Count from subquery fails with missing alias in Postgres #1433

@eklatzer

Description

@eklatzer

Hey, with v4.17.0 the following fix was introduced:

Count from subquery if query uses HAVING or GROUP BY. This is because aggregate functions are run for each group separately, but we need to return the count of returned rows.
PR: #1398

When using this fix with Postgres, the following error is returned: pq: subquery in FROM must have an alias

Here an example:

CREATE TABLE items (
    id serial PRIMARY KEY,
    category varchar(255) NOT NULL,
    is_special boolean NOT NULL
);

Example usage:

count, err := models.Items(
	models.ItemWhere.IsSpecial.EQ(true),
	// group because of possible joins to other tables
	qm.GroupBy(models.ItemColumns.ID),
).Count(boil.WithDebug(ctx, true), s.DB)
require.NoError(t, err)

SQL:

SELECT COUNT(*) FROM (SELECT * FROM "items" WHERE ("items"."is_special" = $1) GROUP BY id);
[true]

You can try it in https://onecompiler.com/postgresql/435bk9nra if you remove the as foo

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions