Class: DatastaxRails::Cql::Select

Inherits:
Base show all
Defined in:
lib/datastax_rails/cql/select.rb

Overview

CQL generation for SELECT

Instance Method Summary collapse

Methods inherited from Base

#execute, #using

Constructor Details

#initialize(klass, select) ⇒ Select


5
6
7
8
9
10
11
12
13
# File 'lib/datastax_rails/cql/select.rb', line 5

def initialize(klass, select)
  @select = select.join(',')
  @limit = nil
  @conditions = {}
  @order = nil
  @paginate = nil
  @allow_filtering = nil
  super
end

Instance Method Details

#allow_filteringObject


15
16
17
18
# File 'lib/datastax_rails/cql/select.rb', line 15

def allow_filtering
  @allow_filtering = true
  self
end

#conditions(conditions) ⇒ Object


25
26
27
28
# File 'lib/datastax_rails/cql/select.rb', line 25

def conditions(conditions)
  @conditions.merge!(conditions)
  self
end

#limit(limit) ⇒ Object


30
31
32
33
# File 'lib/datastax_rails/cql/select.rb', line 30

def limit(limit)
  @limit = limit
  self
end

#order(order) ⇒ Object


35
36
37
38
# File 'lib/datastax_rails/cql/select.rb', line 35

def order(order)
  @order = order
  self
end

#paginate(start) ⇒ Object


20
21
22
23
# File 'lib/datastax_rails/cql/select.rb', line 20

def paginate(start)
  @paginate = start
  self
end

#to_cqlObject


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/datastax_rails/cql/select.rb', line 40

def to_cql
  conditions = []
  stmt = "SELECT #{@select} FROM #{@klass.column_family} "

  if @paginate
    conditions << "token(#{@klass.primary_key}) > token(?)"
    @values << @paginate
  end

  @conditions.each do |k, v|
    if k.to_s == @klass.primary_key && v.is_a?(Array)
      conditions << "\"#{k}\" IN (#{('?' * v.size).split(//).join(',')})"
      @values += v
    else
      v = v.first if v.is_a?(Array)
      conditions << "\"#{k}\" = ?"
      @values << v
    end
  end

  stmt << "WHERE #{conditions.join(' AND ')} " unless conditions.empty?
  stmt << "ORDER BY #{@order} " if @order
  stmt << "LIMIT #{@limit} " if @limit
  stmt << 'ALLOW FILTERING ' if @allow_filtering
  stmt
end