Class: DatastaxRails::Cql::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/datastax_rails/cql/base.rb

Overview

Base class for CQL generation

Instance Method Summary collapse

Constructor Details

#initialize(klass, *_args) ⇒ Base

Base initialize that sets the default consistency.



6
7
8
9
10
# File 'lib/datastax_rails/cql/base.rb', line 6

def initialize(klass, *_args)
  @consistency = klass.default_consistency.to_s.downcase.to_sym
  @keyspace = DatastaxRails::Base.config[:keyspace]
  @values = []
end

Instance Method Details

#executeObject

Generates the CQL and calls Cassandra to execute it. If you are using this outside of Rails, then DatastaxRails::Base.connection must have already been set up (Rails does this for you).



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/datastax_rails/cql/base.rb', line 25

def execute
  cql = to_cql
  puts cql if ENV['DEBUG_CQL'] == 'true'
  pp @values if ENV['DEBUG_CQL'] == 'true'
  digest = Digest::MD5.digest cql
  try_again = true
  begin
    stmt = DatastaxRails::Base.statement_cache[digest] ||= DatastaxRails::Base.connection.prepare(cql)
    if @consistency
      stmt.execute(*@values, consistency: @consistency)
    else
      stmt.execute(*@values)
    end
  rescue ::Cql::NotConnectedError
    if try_again
      Rails.logger.warn('Lost connection to Cassandra. Attempting to reconnect...')
      try_again = false
      DatastaxRails::Base.reconnect
      retry
    else
      raise
    end
  end
end

#to_cqlObject

Abstract. Should be overridden by subclasses



18
19
20
# File 'lib/datastax_rails/cql/base.rb', line 18

def to_cql
  fail NotImplementedError
end

#using(consistency) ⇒ Object



12
13
14
15
# File 'lib/datastax_rails/cql/base.rb', line 12

def using(consistency)
  @consistency = consistency.to_s.downcase.to_sym
  self
end