Add Len() method to *pgx.Batch

This makes the API slightly easier to use when number of calls to
Queue() cannot be trivially computed.

For example, if the program contains the loop like the following,
a separate variable counting the iterations is needed:

    numHeaders := 0
    for _, header := range prepareHeadersForInsert(*res.Headers) {
        headerBatch.Queue("INSERT ...", ...)
        numHeaders++
    }

    headerBatchResult := tx.SendBatch(ctx, headerBatch)

    for i := 0; i < numHeaders; i++ {
        _, err := headerBatchResult.Exec()
        // ...
    }

With method Len(), this extra variable can be eliminated.
pull/682/head
WGH 2020-02-21 22:28:34 +03:00
parent 542c9a97f1
commit c01721e3ba
1 changed files with 5 additions and 0 deletions

View File

@ -26,6 +26,11 @@ func (b *Batch) Queue(query string, arguments ...interface{}) {
})
}
// Len returns number of queries that have been queued so far.
func (b *Batch) Len() int {
return len(b.items)
}
type BatchResults interface {
// Exec reads the results from the next query in the batch as if the query has been sent with Conn.Exec.
Exec() (pgconn.CommandTag, error)