Skip to content

Commit

Permalink
Added stats to Batch struct
Browse files Browse the repository at this point in the history
  • Loading branch information
Phillip Couto committed Sep 4, 2014
1 parent ae293f4 commit f4cc7cb
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 6 deletions.
25 changes: 25 additions & 0 deletions cassandra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1186,3 +1186,28 @@ func TestQueryStats(t *testing.T) {
}
}
}

//TestBatchStats confirms that the stats are returning valid data. Accuracy may be questionable.
func TestBatchStats(t *testing.T) {
session := createSession(t)
defer session.Close()

if err := createTable(session, "CREATE TABLE batchStats (id int, PRIMARY KEY (id))"); err != nil {
t.Fatalf("failed to create table with error '%v'", err)
}

b := session.NewBatch(LoggedBatch)
b.Query("INSERT INTO batchStats (id) VALUES (?)", 1)
b.Query("INSERT INTO batchStats (id) VALUES (?)", 2)

if err := session.ExecuteBatch(b); err != nil {
t.Fatalf("query failed. %v", err)
} else {
if b.Attempts() < 1 {
t.Fatal("expected at least 1 attempt, but got 0")
}
if b.Latency() <= 0 {
t.Fatalf("expected latency to be greater than 0, but got %v instead.", b.Latency())
}
}
}
31 changes: 25 additions & 6 deletions session.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,16 +175,20 @@ func (s *Session) ExecuteBatch(batch *Batch) error {
}

var err error
for count := 0; count <= batch.rt.NumRetries; count++ {
batch.attempts = 0
batch.totalLatency = 0
for batch.attempts <= batch.rt.NumRetries {
conn := s.Pool.Pick(nil)

//Assign the error unavailable and break loop
if conn == nil {
err = ErrNoConnections
break
}

t := time.Now()
err = conn.executeBatch(batch)
batch.totalLatency += time.Now().Sub(t).Nanoseconds()
batch.attempts++
//Exit loop if operation executed correctly
if err == nil {
return nil
Expand Down Expand Up @@ -418,10 +422,12 @@ func (n *nextIter) fetch() *Iter {
}

type Batch struct {
Type BatchType
Entries []BatchEntry
Cons Consistency
rt RetryPolicy
Type BatchType
Entries []BatchEntry
Cons Consistency
rt RetryPolicy
attempts int
totalLatency int64
}

// NewBatch creates a new batch operation without defaults from the cluster
Expand All @@ -434,6 +440,19 @@ func (s *Session) NewBatch(typ BatchType) *Batch {
return &Batch{Type: typ, rt: s.cfg.RetryPolicy}
}

// Attempts returns the number of attempts made to execute the batch.
func (b *Batch) Attempts() int {
return b.attempts
}

//Latency returns the average number of nanoseconds to execute a single attempt of the batch.
func (b *Batch) Latency() int64 {
if b.attempts > 0 {
return b.totalLatency / int64(b.attempts)
}
return 0
}

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

0 comments on commit f4cc7cb

Please sign in to comment.