Skip to content

Commit

Permalink
Exec() method for batch was added & Query() method was refactored
Browse files Browse the repository at this point in the history
  • Loading branch information
tengu-alt committed Jun 4, 2024
1 parent 34fdeeb commit 7353ad6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
16 changes: 14 additions & 2 deletions example_batch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ package gocql_test
import (
"context"
"fmt"
"github.com/gocql/gocql"
"log"
"testing"

"github.com/gocql/gocql"
)

// Example_batch demonstrates how to execute a batch of statements.
func Example_batch() {
func TestExample_batch(t *testing.T) {
/* The example assumes the following CQL was used to setup the keyspace:
create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
create table example.batches(pk int, ck int, description text, PRIMARY KEY(pk, ck));
Expand All @@ -35,11 +37,19 @@ func Example_batch() {
Args: []interface{}{1, 3, "1.3"},
Idempotent: true,
})

err = session.ExecuteBatch(b)
if err != nil {
log.Fatal(err)
}

err = b.Query("INSERT INTO example.batches (pk, ck, description) VALUES (?, ?, ?)", 1, 4, "1.4").
Query("INSERT INTO example.batches (pk, ck, description) VALUES (?, ?, ?)", 1, 5, "1.5").
Exec()
if err != nil {
log.Fatal(err)
}

scanner := session.Query("SELECT pk, ck, description FROM example.batches").Iter().Scanner()
for scanner.Next() {
var pk, ck int32
Expand All @@ -52,4 +62,6 @@ func Example_batch() {
}
// 1 2 1.2
// 1 3 1.3
// 1 4 1.4
// 1 5 1.5
}
8 changes: 7 additions & 1 deletion session.go
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,11 @@ func (b *Batch) execute(ctx context.Context, conn *Conn) *Iter {
return conn.executeBatch(ctx, b)
}

func (b *Batch) Exec() error {
iter := b.session.executeBatch(b)
return iter.Close()
}

func (s *Session) executeBatch(batch *Batch) *Iter {
// fail fast
if s.Closed() {
Expand Down Expand Up @@ -1840,8 +1845,9 @@ func (b *Batch) SpeculativeExecutionPolicy(sp SpeculativeExecutionPolicy) *Batch
}

// Query adds the query to the batch operation
func (b *Batch) Query(stmt string, args ...interface{}) {
func (b *Batch) Query(stmt string, args ...interface{}) *Batch {
b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
return b
}

// Bind adds the query to the batch operation and correlates it with a binding callback
Expand Down

0 comments on commit 7353ad6

Please sign in to comment.