package api import ( "context" "github.com/stephenafamo/bob" "github.com/stephenafamo/bob/dialect/sqlite" "github.com/stephenafamo/bob/dialect/sqlite/dialect" "github.com/stephenafamo/bob/dialect/sqlite/sm" "github.com/tigorlazuardi/bluemage/go/gen/models" device "github.com/tigorlazuardi/bluemage/go/gen/proto/device/v1" "github.com/tigorlazuardi/bluemage/go/pkg/errs" "github.com/tigorlazuardi/bluemage/go/pkg/telemetry" . "github.com/go-jet/jet/v2/sqlite" . "github.com/tigorlazuardi/bluemage/go/gen/jet/table" ) func queryFromCountDevicesRequest(req *device.CountDevicesRequest) (expr []bob.Mod[*dialect.SelectQuery]) { switch req.Disabled { case device.DisabledFilter_DISABLED_FILTER_TRUE: expr = append(expr, models.SelectWhere.Devices.Disabled.EQ(1)) case device.DisabledFilter_DISABLED_FILTER_FALSE: expr = append(expr, models.SelectWhere.Devices.Disabled.EQ(0)) } if req.Search != "" { arg := sqlite.Arg("%" + req.Search + "%") expr = append(expr, sm.Where( models.DeviceColumns.Name.Like(arg).Or(models.DeviceColumns.Slug.Like(arg)), ), ) } return expr } func (api *API) DevicesCount(ctx context.Context, request *device.CountDevicesRequest) (count uint64, err error) { ctx, span := tracer.Start(ctx, "DevicesCount") defer func() { telemetry.EndWithStatus(span, err) }() cond := Bool(true) switch request.Disabled { case device.DisabledFilter_DISABLED_FILTER_TRUE: cond.AND(Devices.Disabled.EQ(Int(1))) case device.DisabledFilter_DISABLED_FILTER_FALSE: cond.AND(Devices.Disabled.EQ(Int(0))) } if request.Search != "" { cond.AND(Devices.Name.LIKE(String("%" + request.Search + "%"))) } stmt := SELECT(COUNT(Int(1))).WHERE(cond) query, args := stmt.Sql() err = api.DB.QueryRowContext(ctx, query, args...).Scan(&count) if err != nil { return count, errs.Wrapw(err, "failed to count devices", "request", request, "query", stmt.DebugSql(), ) } return count, nil }