Example #1
0
func BuildKeySpace(migrationsPath *string) (*gocql.Session, error) {
	var (
		cassandraIP = os.Getenv("CASSANDRA_IP")
		keySpace    = os.Getenv("CASSANDRA_KEY_SPACE")
	)

	if cassandraIP == "" {
		cassandraIP = defaultCassandraIP
	}

	if keySpace == "" {
		keySpace = fmt.Sprintf("%s%d", defaultKeyspace, rand.Int31())
	}

	cluster := gocql.NewCluster(cassandraIP)
	cluster.Consistency = gocql.All
	cluster.ProtoVersion = protocolVersion

	session, err := cluster.CreateSession()

	if err != nil {
		return nil, err
	}

	defer session.Close()

	session.Query(`DROP KEYSPACE IF EXISTS ` + keySpace).Exec()
	session.Query(
		`CREATE KEYSPACE ` + keySpace + ` WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }`,
	).Exec()

	if migrationsPath != nil {
		errs, ok := migrate.UpSync(
			fmt.Sprintf(
				"cassandra://%s:%d/%s?protocol=%d",
				cassandraIP,
				cassandraPort,
				keySpace,
				protocolVersion,
			),
			*migrationsPath,
		)

		if !ok {
			strErrs := []string{}
			for _, migrationError := range errs {
				strErrs = append(strErrs, migrationError.Error())
			}

			return nil, errors.New(strings.Join(strErrs, ","))
		}
	}

	cluster.Keyspace = keySpace
	return cluster.CreateSession()
}
Example #2
0
// Cassandra Driver URL format:
// cassandra://host:port/keyspace?protocol=version
//
// Example:
// cassandra://localhost/SpaceOfKeys?protocol=4
func (driver *Driver) Initialize(rawurl string) error {
	u, err := url.Parse(rawurl)

	cluster := gocql.NewCluster(u.Host)
	cluster.Keyspace = u.Path[1:len(u.Path)]
	cluster.Consistency = gocql.All
	cluster.Timeout = 1 * time.Minute

	if len(u.Query().Get("protocol")) > 0 {
		protoversion, err := strconv.Atoi(u.Query().Get("protocol"))
		if err != nil {
			return err
		}

		cluster.ProtoVersion = protoversion
	}

	// Check if url user struct is null
	if u.User != nil {
		password, passwordSet := u.User.Password()

		if passwordSet == false {
			return fmt.Errorf("Missing password. Please provide password.")
		}

		cluster.Authenticator = gocql.PasswordAuthenticator{
			Username: u.User.Username(),
			Password: password,
		}

	}

	driver.session, err = cluster.CreateSession()

	if err != nil {
		return err
	}

	if err := driver.ensureVersionTableExists(); err != nil {
		return err
	}
	return nil
}