@@ -185,10 +185,11 @@ func (q *Query) SearchLimit(limit int64) *Query {
185185}
186186
187187// RequestLimit specifies the maximum amount of requests to make against DynamoDB's API.
188- // func (q *Query) RequestLimit(limit int) *Query {
189- // q.reqLimit = limit
190- // return q
191- // }
188+ // A limit of zero or less means unlimited requests.
189+ func (q * Query ) RequestLimit (limit int ) * Query {
190+ q .reqLimit = limit
191+ return q
192+ }
192193
193194// Order specifies the desired result order.
194195// Requires a range key (a.k.a. partition key) to be specified.
@@ -286,22 +287,29 @@ func (q *Query) CountWithContext(ctx context.Context) (int64, error) {
286287 return 0 , q .err
287288 }
288289
289- var count int64
290+ var count , scanned int64
291+ var reqs int
290292 var res * dynamodb.QueryOutput
291293 for {
292- req := q .queryInput ()
293- req .Select = selectCount
294+ input := q .queryInput ()
295+ input .Select = selectCount
294296
295297 err := q .table .db .retry (ctx , func () error {
296298 var err error
297- res , err = q .table .db .client .QueryWithContext (ctx , req )
299+ res , err = q .table .db .client .QueryWithContext (ctx , input )
298300 if err != nil {
299301 return err
300302 }
303+ reqs ++
304+
301305 if res .Count == nil {
302- return errors .New ("nil count" )
306+ return errors .New ("malformed DynamoDB response: count is nil " )
303307 }
304308 count += * res .Count
309+ if res .ScannedCount != nil {
310+ scanned += * res .ScannedCount
311+ }
312+
305313 return nil
306314 })
307315 if err != nil {
@@ -312,7 +320,10 @@ func (q *Query) CountWithContext(ctx context.Context) (int64, error) {
312320 }
313321
314322 q .startKey = res .LastEvaluatedKey
315- if res .LastEvaluatedKey == nil || q .searchLimit > 0 {
323+ if res .LastEvaluatedKey == nil ||
324+ (q .limit > 0 && count >= q .limit ) ||
325+ (q .searchLimit > 0 && scanned >= q .searchLimit ) ||
326+ (q .reqLimit > 0 && reqs >= q .reqLimit ) {
316327 break
317328 }
318329 }
0 commit comments