Skip to content

Conversation

@StounhandJ
Copy link

  • Do only one thing
  • Non breaking API changes
  • Tested

What did this pull request do?

When creating a Count request, if a Select was passed with count, substitute it in Clause to avoid unexpected addition of the request.

User Case Description

InnerJoins is used here as adding an internal verification condition.

r.db.Model(&models.KubeRBAC{}).
	Select("count(distinct(subj->>'kind', subj->>'apiGroup', subj->>'name', subj->>'namespace', \"ClusterRef\".id))").
	InnerJoins("ClusterRef").
	Count(&total)

Extra fields appear in the final sql, which violates the correctness of the work.

SELECT
  count(distinct(
    subj->>'kind',
    subj->>'apiGroup',
    subj->>'name',
    subj->>'namespace',
    "ClusterRef".id
  )),
  "ClusterRef"."id"         AS "ClusterRef__id",
  "ClusterRef"."name"       AS "ClusterRef__name",
  "ClusterRef"."updated_at" AS "ClusterRef__updated_at",
  "ClusterRef"."created_at" AS "ClusterRef__created_at"
FROM
  "kube_rbac"
INNER JOIN
  "kube_clusters" "ClusterRef"
    ON "kube_rbac"."kube_cluster_id" = "ClusterRef"."id"
    AND "ClusterRef"."updated_at" > now() - '1 hours'::interval;

The result after correction

SELECT
  count(distinct(
    subj->>'kind',
    subj->>'apiGroup',
    subj->>'name',
    subj->>'namespace',
    "ClusterRef".id
  ))
FROM
  "kube_rbac"
INNER JOIN
  "kube_clusters" "ClusterRef"
    ON "kube_rbac"."kube_cluster_id" = "ClusterRef"."id"
    AND "ClusterRef"."updated_at" > now() - '1 hours'::interval;

@propel-code-bot
Copy link
Contributor

Ensure Correct COUNT Clause Handling With Custom SELECTs

This PR addresses an issue in the Count method of the GORM ORM where providing a custom SELECT clause including a count expression could lead to extraneous fields being included in the generated SQL. The update ensures that if a SELECT starting with count( is passed, it is used directly in the clause, preventing accidental addition of unrelated fields to the final SQL statement. This corrects scenarios where inner joins and custom select count logic (e.g., distinct multi-column counts) would otherwise result in corrupt or incorrect SQL.

Key Changes

• Modified Count method logic in finisher_api.go.
• Added handling: if tx.Statement.Selects[0] begins with count(, directly inject that SQL into the clause.Select for the query.
• Prevents extra columns from being included in generated SQL SELECT statements during COUNT operations with custom SELECT expressions.

Affected Areas

Count logic in finisher_api.go

This summary was automatically generated by @propel-code-bot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant