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) } }