From 199f4c4683984a54644ca4fb7c3982af7b88ea86 Mon Sep 17 00:00:00 2001 From: Gabriel Hernandez Date: Fri, 11 Oct 2024 15:07:02 +0100 Subject: [PATCH] fix the GET /fleet_maintained_apps endpoint `query` param and count value (#22857) relates to #22826 fix to the `GET /fleet_maintained_apps` endpoint so it returns correct results is given a `query` query param. Also the total count takes into account the query in the request. --- server/datastore/mysql/maintained_apps.go | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/server/datastore/mysql/maintained_apps.go b/server/datastore/mysql/maintained_apps.go index e8dbb670a7..285db769cb 100644 --- a/server/datastore/mysql/maintained_apps.go +++ b/server/datastore/mysql/maintained_apps.go @@ -130,11 +130,6 @@ WHERE NOT EXISTS ( ) )` - // build the count statement before adding the pagination constraints to the - // default stmt. - dbReader := ds.reader(ctx) - getAppsCountStmt := fmt.Sprintf(`SELECT COUNT(DISTINCT s.id) FROM (%s) AS s`, stmt) - args := []any{teamID, teamID} if match := opt.MatchQuery; match != "" { @@ -143,6 +138,16 @@ WHERE NOT EXISTS ( args = append(args, match) } + // perform a second query to grab the counts. Build the count statement before + // adding the pagination constraints to the stmt but after including the + // MatchQuery option sql. + dbReader := ds.reader(ctx) + getAppsCountStmt := fmt.Sprintf(`SELECT COUNT(DISTINCT s.id) FROM (%s) AS s`, stmt) + var counts int + if err := sqlx.GetContext(ctx, dbReader, &counts, getAppsCountStmt, args...); err != nil { + return nil, nil, ctxerr.Wrap(ctx, err, "get fleet maintained apps count") + } + stmtPaged, args := appendListOptionsWithCursorToSQL(stmt, args, &opt) var avail []fleet.MaintainedApp @@ -150,12 +155,6 @@ WHERE NOT EXISTS ( return nil, nil, ctxerr.Wrap(ctx, err, "selecting available fleet managed apps") } - // perform a second query to grab the counts - var counts int - if err := sqlx.GetContext(ctx, dbReader, &counts, getAppsCountStmt, args...); err != nil { - return nil, nil, ctxerr.Wrap(ctx, err, "get fleet maintained apps count") - } - meta := &fleet.PaginationMetadata{HasPreviousResults: opt.Page > 0, TotalResults: uint(counts)} if len(avail) > int(opt.PerPage) { meta.HasNextResults = true