go-jet / jet

Type safe SQL builder with code generation and automatic query result data mapping
Apache License 2.0
2.23k stars 110 forks source link

query fails, debugSql produces valid query #303

Closed QuittyMR closed 5 months ago

QuittyMR commented 6 months ago

Describe the bug DebugSql returns a prefectly valid query, but the execution via Go-Jet results in a SQL error. I suspect the issue is a boolean expression, appearing both in the group by and selection. I have tried several different approaches, code-wise, but to no avail.

Environment (please complete the following information):

Code snippet Code:

interactionCounts := CTE("interactionCounts")
isSelf := BoolColumn("is_self").From(interactionCounts)

col := InsightsInteractions.AuthUserID.EQ(UUID(uuid.MustParse(*authUserID)))
interactionCountsQuery := SELECT(col.AS(isSelf.Name())).FROM(InsightsInteractions).GROUP_BY(col)
err = interactionCountsQuery.Query(d.GetDBConn(), &results)

Resulting query (via DebugSql):

SELECT (insights_interactions.auth_user_id = '...') AS "is_self"
FROM public.insights_interactions
GROUP BY insights_interactions.auth_user_id = '...';

Error: ERROR: column "insights_interactions.auth_user_id" must appear in the GROUP BY clause or be used in an aggregate function (SQLSTATE 42803)

Expected behavior Well, besides the obvious, I'm wondering how reliable is DebugSql if the query being executed is obviously not the one being returned from that function.

houten11 commented 6 months ago

DebugSql doesn't return a query executed on db.

debugSql - this query string can be copy-pasted to sql editor and executed. It is not intended to be used in production. For debug purposes only!!!

Sql will return the query and parameters passed to db. Sql of your query will probably return something like this:

SELECT (insights_interactions.auth_user_id = $1) AS "is_self"
FROM public.insights_interactions
GROUP BY insights_interactions.auth_user_id = $2;

Because different parameters ($1 and $2) are used in select and group by postgres returns an error.

To fix it, you can use named column in group by:

interactionCountsQuery := SELECT(
    InsightsInteractions.AuthUserID.EQ(UUID(uuid.MustParse(*authUserID))).AS(isSelf.Name()),
).FROM(
    InsightsInteractions,
).GROUP_BY(
    BoolColumn(isSelf.Name()),
)