Class: CassandraDB::Database

Inherits:
Object
  • Object
show all
Defined in:
lib/cassandra_db/database.rb

Constant Summary collapse

DEFAULTS =
{
  keyspace: DEFAULT_KEYSPACE
}.freeze
DEFAULT_LOGGER =
Logger.new '/dev/null'

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Database



10
11
12
13
14
15
# File 'lib/cassandra_db/database.rb', line 10

def initialize(options={})
  @options = DEFAULTS.merge(options)
  keyspace = @options.delete :keyspace
  @cluster = Cassandra.cluster @options
  @session = use_keyspace keyspace
end

Instance Method Details

#create_keyspace(name, replication: DEFAULT_REPLICATION, durable_writes: true) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/cassandra_db/database.rb', line 40

def create_keyspace(name, replication:DEFAULT_REPLICATION, durable_writes:true)
  cql = %Q{
    CREATE KEYSPACE "#{name}"
      WITH REPLICATION = #{JSON.dump(replication).gsub('"', '\'')}
      AND DURABLE_WRITES = #{durable_writes};
  }
  execute cql
end

#drop_keyspace(name) ⇒ Object



49
50
51
# File 'lib/cassandra_db/database.rb', line 49

def drop_keyspace(name)
  execute "DROP KEYSPACE \"#{name}\";"
end

#execute(cql, options = {}) ⇒ Object



53
54
55
56
# File 'lib/cassandra_db/database.rb', line 53

def execute(cql, options={})
  logger.debug(self.class) { "#{cql} #{options.any? ? options : ''}".strip }
  session.execute cql, options
end

#from(table) ⇒ Object Also known as: []



35
36
37
# File 'lib/cassandra_db/database.rb', line 35

def from(table)
  Dataset.new self, table: table
end

#inspectObject



58
59
60
# File 'lib/cassandra_db/database.rb', line 58

def inspect
  "#<#{self.class.name}: options=#{options.inspect} keyspace=#{keyspace.inspect}>"
end

#keyspaceObject



17
18
19
# File 'lib/cassandra_db/database.rb', line 17

def keyspace
  session.keyspace.to_sym
end

#keyspacesObject



25
26
27
28
# File 'lib/cassandra_db/database.rb', line 25

def keyspaces
  cluster.refresh_schema
  cluster.keyspaces.map { |k| k.name.to_sym }.sort
end

#tablesObject



30
31
32
33
# File 'lib/cassandra_db/database.rb', line 30

def tables
  cluster.refresh_schema
  cluster.keyspace(session.keyspace).tables.map { |t| t.name.to_sym }.sort
end

#use_keyspace(name) ⇒ Object



21
22
23
# File 'lib/cassandra_db/database.rb', line 21

def use_keyspace(name)
  @session = cluster.connect name.to_s
end