Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: 🐛 apply relation functions on count queries #848

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions query_select.go
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,17 @@ func (q *SelectQuery) Count(ctx context.Context) (int, error) {
return 0, q.err
}

if err := q.forEachInlineRelJoin(func(j *relationJoin) error {
j.applyTo(q)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this function modifies the q. Meaning that it will be applied twice when run with ScanAndCount:

  • first it will be applied by Scan
  • second it will be applied by Count

If that is true, then the query generation becomes racy and unsafe....

Copy link
Author

@enzalito enzalito Sep 12, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ScanAndCount calls the unexported count function that corresponds to Count on the main branch. If I remember correctly the lines you mention do in fact modify q but they are only run when Count (not count) is called directly.

I made this PR a while ago so I might be missing something, you tell me

return nil
}); err != nil {
return 0, err
}

return q.count(ctx)
}

func (q *SelectQuery) count(ctx context.Context) (int, error) {
qq := countQuery{q}

queryBytes, err := qq.AppendQuery(q.db.fmter, nil)
Expand All @@ -942,6 +953,10 @@ func (q *SelectQuery) Count(ctx context.Context) (int, error) {
}

func (q *SelectQuery) ScanAndCount(ctx context.Context, dest ...interface{}) (int, error) {
if q.err != nil {
return 0, q.err
}

if _, ok := q.conn.(*DB); ok {
return q.scanAndCountConc(ctx, dest...)
}
Expand Down Expand Up @@ -974,7 +989,7 @@ func (q *SelectQuery) scanAndCountConc(ctx context.Context, dest ...interface{})
defer wg.Done()

var err error
count, err = q.Count(ctx)
count, err = q.count(ctx)
if err != nil {
mu.Lock()
if firstErr == nil {
Expand All @@ -995,7 +1010,7 @@ func (q *SelectQuery) scanAndCountSeq(ctx context.Context, dest ...interface{})
firstErr = q.Scan(ctx, dest...)
}

count, err := q.Count(ctx)
count, err := q.count(ctx)
if err != nil && firstErr == nil {
firstErr = err
}
Expand Down