Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add BatchN to create a batch with an initial capacity. #1879

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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