// CreateKeyspace creates a keyspace if necessary // ks -> keyspace name // rs -> replication strategy class // rf -> replication factor func CreateKeyspace(c *gocql.ClusterConfig, ks string, rs string, rf int) error { kis, err := GetKeyspaces(c) if err != nil { return err } kss := set.NewStringSet(kis) if !kss.Contains(ks) { log.Printf("Creating keyspace: %v\n", ks) c.Keyspace = "" s, err := c.CreateSession() if err != nil { return err } defer s.Close() if rs == "" { rs = "SimpleStrategy" } err = s.Query(fmt.Sprintf("CREATE KEYSPACE IF NOT EXISTS %v WITH REPLICATION = {'class': '%v', 'replication_factor': %v};", ks, rs, rf)).Exec() if err != nil { return err } } c.Keyspace = ks return nil }
// CreateKeyspaceWithNetworkTopologyStrategy creates a keyspace if necesary with NetworkTopologyStrategy // ks -> keyspace name // rfmap -> map of datacenter name to replication factor for that DC func CreateKeyspaceWithNetworkTopologyStrategy(c *gocql.ClusterConfig, ks string, rfmap map[string]uint) error { kis, err := GetKeyspaces(c) if err != nil { return err } kss := set.NewStringSet(kis) if !kss.Contains(ks) { log.Printf("Creating keyspace: %v\n", ks) c.Keyspace = "" s, err := c.CreateSession() if err != nil { return err } defer s.Close() q := fmt.Sprintf("CREATE KEYSPACE IF NOT EXISTS %v WITH REPLICATION = {'class': '%v', ", ks, "NetworkTopologyStrategy") rfsl := []string{} for dc, rf := range rfmap { rfsl = append(rfsl, fmt.Sprintf("'%v' : %v", dc, rf)) } q = fmt.Sprintf("%v%v};", q, strings.Join(rfsl, ", ")) err = s.Query(q).Exec() if err != nil { return err } } c.Keyspace = ks return nil }
func prepareCassandraCluster(cluster *gocql.ClusterConfig) { cluster.Keyspace = "system" session, err := cluster.CreateSession() if err != nil { panic(err) } defer session.Close() err = session.Query("DROP KEYSPACE IF EXISTS ?", cassandraKeyspace).RetryPolicy(nil).Exec() if err != nil { panic(err) } err = session.Query("DROP KEYSPACE IF EXISTS ?", cassandraKeyspace).RetryPolicy(nil).Exec() if err != nil { panic(err) } err = session.Query("CREATE KEYSPACE ? WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }", cassandraKeyspace).RetryPolicy(nil).Exec() if err != nil { panic(err) } err = session.Query("CREATE TABLE ?.kvbench (id UUID primary key, value varchar)", cassandraKeyspace).RetryPolicy(nil).Exec() if err != nil { panic(err) } }
// DropKeyspace deletes a keyspace and all data associated with it func DropKeyspace(c *gocql.ClusterConfig, ks string) error { c.Keyspace = "" s, err := c.CreateSession() if err != nil { return err } defer s.Close() log.Printf("Dropping keyspace: %v\n", ks) err = s.Query(fmt.Sprintf("DROP KEYSPACE IF EXISTS %v\n", ks)).Exec() if err != nil { return err } return nil }