Skip to content

Commit

Permalink
feat: Add BatchN to create a batch with an initial capacity.
Browse files Browse the repository at this point in the history
  • Loading branch information
s-l-teichmann committed Jan 18, 2024
1 parent a4ca091 commit f3d0c4e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
7 changes: 7 additions & 0 deletions batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,13 @@ func (b *Batch) Queue(query string, arguments ...any) *QueuedQuery {
return qq
}

// BatchN returns a new Batch with an initial capacity of n.
// This is useful to avoid allocations if you know beforehand how many queries
// at least you want to enqueue.
func BatchN(n int) Batch {
return Batch{queuedQueries: make([]*QueuedQuery, 0, n)}
}

// Len returns number of queries that have been queued so far.
func (b *Batch) Len() int {
return len(b.queuedQueries)
Expand Down
4 changes: 2 additions & 2 deletions batch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func TestConnSendBatch(t *testing.T) {
);`
mustExec(t, conn, sql)

batch := &pgx.Batch{}
batch := pgx.BatchN(7)
batch.Queue("insert into ledger(description, amount) values($1, $2)", "q1", 1)
batch.Queue("insert into ledger(description, amount) values($1, $2)", "q2", 2)
batch.Queue("insert into ledger(description, amount) values($1, $2)", "q3", 3)
Expand All @@ -40,7 +40,7 @@ func TestConnSendBatch(t *testing.T) {
batch.Queue("select * from ledger where false")
batch.Queue("select sum(amount) from ledger")

br := conn.SendBatch(ctx, batch)
br := conn.SendBatch(ctx, &batch)

ct, err := br.Exec()
if err != nil {
Expand Down

0 comments on commit f3d0c4e

Please sign in to comment.