Class: CassandraDB::Dataset

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/cassandra_db/dataset.rb

Instance Method Summary collapse

Constructor Details

#initialize(db, from:, where: []) ⇒ Dataset

Returns a new instance of Dataset.



6
7
8
9
10
# File 'lib/cassandra_db/dataset.rb', line 6

def initialize(db, from:, where:[])
  @db = db
  @table = from
  @conditions = where
end

Instance Method Details

#allObject



28
29
30
# File 'lib/cassandra_db/dataset.rb', line 28

def all
  db.execute(*cql).to_a
end

#cqlObject



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cassandra_db/dataset.rb', line 32

def cql
  select = 'SELECT *'
  from = "FROM #{table}"
  where = conditions.any? ? "WHERE #{conditions.map { |c| "#{c[:field]} #{c[:operator]} :#{c[:field]}" }.join(' AND ')}" : ''
  arguments = conditions.each_with_object({}) { |c,h| h[c[:field]] = c[:value] }

  [
    "#{select} #{from} #{where}".strip,
    {arguments: arguments}
  ]
end

#each(&block) ⇒ Object



24
25
26
# File 'lib/cassandra_db/dataset.rb', line 24

def each(&block)
  all.each(&block)
end

#inspectObject



44
45
46
# File 'lib/cassandra_db/dataset.rb', line 44

def inspect
  "#<#{self.class.name}: #{cql.join(', ')}>"
end

#where(filters) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/cassandra_db/dataset.rb', line 12

def where(filters)
  new_conditions = filters.map do |field, value|
    {
      field: field,
      operator: value.is_a?(Array) ? 'IN' : '=',
      value: value
    }
  end

  Dataset.new db, from: table, where: conditions + new_conditions
end