2018-08-26 19:15:48 +08:00
|
|
|
//
|
|
|
|
// Copyright (c) 2018
|
|
|
|
// Mainflux
|
|
|
|
//
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
//
|
|
|
|
|
2018-06-08 20:25:55 +08:00
|
|
|
package cassandra
|
|
|
|
|
|
|
|
import "github.com/gocql/gocql"
|
|
|
|
|
|
|
|
const table = `CREATE TABLE IF NOT EXISTS messages (
|
2018-12-18 03:41:11 +08:00
|
|
|
id uuid,
|
|
|
|
channel text,
|
2019-03-16 01:38:07 +08:00
|
|
|
subtopic text,
|
2018-12-18 03:41:11 +08:00
|
|
|
publisher text,
|
2018-06-08 20:25:55 +08:00
|
|
|
protocol text,
|
|
|
|
name text,
|
|
|
|
unit text,
|
|
|
|
value double,
|
|
|
|
string_value text,
|
|
|
|
bool_value boolean,
|
|
|
|
data_value text,
|
|
|
|
value_sum double,
|
|
|
|
time double,
|
|
|
|
update_time double,
|
2018-12-18 03:41:11 +08:00
|
|
|
link text,
|
|
|
|
PRIMARY KEY (channel, time, id)
|
2019-05-16 05:31:41 +08:00
|
|
|
) WITH CLUSTERING ORDER BY (time DESC)`
|
|
|
|
|
|
|
|
// DBConfig contains Cassandra DB specific parameters.
|
|
|
|
type DBConfig struct {
|
|
|
|
Hosts []string
|
|
|
|
Keyspace string
|
|
|
|
Username string
|
|
|
|
Password string
|
|
|
|
Port int
|
|
|
|
}
|
2018-06-08 20:25:55 +08:00
|
|
|
|
|
|
|
// Connect establishes connection to the Cassandra cluster.
|
2019-05-16 05:31:41 +08:00
|
|
|
func Connect(cfg DBConfig) (*gocql.Session, error) {
|
|
|
|
cluster := gocql.NewCluster(cfg.Hosts...)
|
|
|
|
cluster.Keyspace = cfg.Keyspace
|
2018-06-08 20:25:55 +08:00
|
|
|
cluster.Consistency = gocql.Quorum
|
2019-05-16 05:31:41 +08:00
|
|
|
cluster.Authenticator = gocql.PasswordAuthenticator{
|
|
|
|
Username: cfg.Username,
|
|
|
|
Password: cfg.Password,
|
|
|
|
}
|
|
|
|
cluster.Port = cfg.Port
|
2018-06-08 20:25:55 +08:00
|
|
|
|
|
|
|
session, err := cluster.CreateSession()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-08-06 23:06:55 +08:00
|
|
|
if err := session.Query(table).Exec(); err != nil {
|
2018-06-08 20:25:55 +08:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return session, nil
|
|
|
|
}
|