Browse Source

Merge pull request #56 from phillipCouto/master

Return Error when user provides an empty array for hosts
Christoph Hack 12 years ago
parent
commit
44eda643c1
2 changed files with 28 additions and 4 deletions
  1. 13 2
      cluster.go
  2. 15 2
      gocql_test/main.go

+ 13 - 2
cluster.go

@@ -5,6 +5,7 @@
 package gocql
 
 import (
+	"errors"
 	"fmt"
 	"log"
 	"strings"
@@ -52,7 +53,13 @@ func NewCluster(hosts ...string) *ClusterConfig {
 
 // CreateSession initializes the cluster based on this config and returns a
 // session object that can be used to interact with the database.
-func (cfg *ClusterConfig) CreateSession() *Session {
+func (cfg *ClusterConfig) CreateSession() (*Session, error) {
+
+	//Check that hosts in the ClusterConfig is not empty
+	if len(cfg.Hosts) < 1 {
+		return nil, ErrNoHosts
+	}
+
 	impl := &clusterImpl{
 		cfg:      *cfg,
 		hostPool: NewRoundRobin(),
@@ -74,7 +81,7 @@ func (cfg *ClusterConfig) CreateSession() *Session {
 	impl.wgStart.Wait()
 	s := NewSession(impl)
 	s.SetConsistency(cfg.Consistency)
-	return s
+	return s, nil
 }
 
 type clusterImpl struct {
@@ -223,3 +230,7 @@ func (c *clusterImpl) Close() {
 		}
 	})
 }
+
+var (
+	ErrNoHosts = errors.New("no hosts provided")
+)

+ 15 - 2
gocql_test/main.go

@@ -23,7 +23,7 @@ func init() {
 	// uncomment the following two lines if you want to use Cassandra 1.2
 	// cluster.ProtoVersion = 1
 	// cluster.CQLVersion = "3.0.0"
-	session = cluster.CreateSession()
+	session, _ = cluster.CreateSession()
 }
 
 type Page struct {
@@ -56,7 +56,7 @@ func initSchema() error {
 	time.Sleep(15 * time.Second)
 	log.Println("If there were error messages that an address cannot be assigned then the test failed.")
 	cluster.Keyspace = "gocql_test"
-	session = cluster.CreateSession()
+	session, _ = cluster.CreateSession()
 
 	if err := session.Query(`CREATE TABLE page (
 			title       varchar,
@@ -141,7 +141,20 @@ func getPage(title string, revid uuid.UUID) (*Page, error) {
 	return p, err
 }
 
+//This test checks to make sure a valid error and a nil reference to
+//a session are returned when an empty array of hosts are provided
+//to the cluster configuration
+func TestEmptyHosts() error {
+	empty := make([]string, 0)
+	cfg := gocql.NewCluster(empty...)
+	_, err := cfg.CreateSession()
+	return err
+}
+
 func main() {
+	if err := TestEmptyHosts(); err == nil {
+		log.Fatal("Failed to error when empty host list is provided.")
+	}
 	if err := initSchema(); err != nil {
 		log.Fatal("initSchema: ", err)
 	}