689e022e3e
Adds CountResult, QueryCount, BuildQueryCountFn, and ReadableTable alias for Jet pagination total counts, with tests and docs. Co-authored-by: Cursor <cursoragent@cursor.com>
45 lines
1.0 KiB
Go
45 lines
1.0 KiB
Go
package dbx
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/go-jet/jet/v2/mysql"
|
|
)
|
|
|
|
// CountResult holds the count from a Jet COUNT query. Use with a SELECT that
|
|
// aliases the count as `CountResult.Count`, for example:
|
|
//
|
|
// SELECT(mysql.COUNT(col).AS("CountResult.Count"))
|
|
type CountResult struct {
|
|
Count int
|
|
}
|
|
|
|
// QueryCountFn counts rows matching pre-bound table and condition parameters.
|
|
type QueryCountFn func(sqlo Queryable) (int, error)
|
|
|
|
// QueryCount counts rows in tbl matching conds.
|
|
func QueryCount(
|
|
sqlo Queryable,
|
|
col Column,
|
|
tbl ReadableTable,
|
|
conds BoolExpression,
|
|
) (int, error) {
|
|
stmt := tbl.SELECT(mysql.COUNT(col).AS("CountResult.Count")).WHERE(conds)
|
|
var res CountResult
|
|
if err := stmt.Query(sqlo, &res); err != nil {
|
|
return 0, fmt.Errorf("query count: %w", err)
|
|
}
|
|
return res.Count, nil
|
|
}
|
|
|
|
// BuildQueryCountFn returns a QueryCountFn with col, tbl, and conds bound.
|
|
func BuildQueryCountFn(
|
|
col Column,
|
|
tbl ReadableTable,
|
|
conds BoolExpression,
|
|
) QueryCountFn {
|
|
return func(sqlo Queryable) (int, error) {
|
|
return QueryCount(sqlo, col, tbl, conds)
|
|
}
|
|
}
|