Skip to content

Commit d65c674

Browse files
hagitaquasecido50
authored andcommitted
Support GetCount on union queries
This commit fixes GetCount on union statements, and update columns/limits/offsets on all the union statements instead of applying it on the first statement only. There was a runtime error on a union query, because the columns of the union statements remained as they were, while the columns of the first statement changed.
1 parent ca6e42f commit d65c674

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

select.go

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -573,14 +573,41 @@ func (stmt *SelectStmt) GetAllContext(ctx context.Context, into interface{}) err
573573
// total number of matching results. This is useful when
574574
// paginating results.
575575
func (stmt *SelectStmt) GetCount() (count int64, err error) {
576+
defer stmt.HandleError(err)
577+
576578
countStmt := *stmt
577579
countStmt.Columns = []string{"COUNT(*)"}
578580
countStmt.LimitTo = 0
579581
countStmt.OffsetFrom = 0
580582
countStmt.OffsetRows = 0
581583
countStmt.Ordering = []SQLStmt{}
582584

583-
err = countStmt.GetRow(&count)
585+
for _, st := range countStmt.Unions {
586+
st.Columns = []string{"COUNT(*)"}
587+
st.LimitTo = 0
588+
st.OffsetFrom = 0
589+
st.OffsetRows = 0
590+
st.Ordering = []SQLStmt{}
591+
}
592+
593+
rows, err := countStmt.GetAllAsRows()
594+
if err != nil {
595+
return count, err
596+
}
597+
defer rows.Close()
598+
599+
for rows.Next() {
600+
var stmtCount int64
601+
err = rows.Scan(&stmtCount)
602+
603+
if err != nil {
604+
return count, err
605+
}
606+
607+
count += stmtCount
608+
}
609+
610+
err = rows.Err()
584611

585612
return count, err
586613
}

0 commit comments

Comments
 (0)