Class: CassandraObject::Adapters::CassandraAdapter

Inherits:
AbstractAdapter show all
Defined in:
lib/cassandra_object/adapters/cassandra_adapter.rb

Defined Under Namespace

Classes: QueryBuilder

Instance Attribute Summary

Attributes inherited from AbstractAdapter

#config

Instance Method Summary collapse

Methods inherited from AbstractAdapter

#batch, #batching?, #execute_batchable, #initialize, #statement_with_options

Constructor Details

This class inherits a constructor from CassandraObject::Adapters::AbstractAdapter

Instance Method Details

#cassandra_cluster_optionsObject



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 51

def cassandra_cluster_options
  cluster_options = config.slice(*[
      :auth_provider,
      :client_cert,
      :compression,
      :compressor,
      :connect_timeout,
      :connections_per_local_node,
      :connections_per_remote_node,
      :consistency,
      :credentials,
      :futures_factory,
      :hosts,
      :load_balancing_policy,
      :logger,
      :page_size,
      :passphrase,
      :password,
      :port,
      :private_key,
      :protocol_version,
      :reconnection_policy,
      :retry_policy,
      :schema_refresh_delay,
      :schema_refresh_timeout,
      :server_cert,
      :ssl,
      :timeout,
      :trace,
      :username
  ])

  {
      load_balancing_policy: 'Cassandra::LoadBalancing::Policies::%s',
      reconnection_policy: 'Cassandra::Reconnection::Policies::%s',
      retry_policy: 'Cassandra::Retry::Policies::%s'
  }.each do |policy_key, class_template|
    if cluster_options[policy_key]
      cluster_options[policy_key] = (class_template % [policy_key.classify]).constantize
    end
  end

  # Setting defaults
  cluster_options.merge!({
                             consistency: cluster_options[:consistency] || :quorum,
                             protocol_version: cluster_options[:protocol_version] || 3,
                             page_size: cluster_options[:page_size] || 10000
                         })
  return cluster_options
end

#cassandra_versionObject



215
216
217
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 215

def cassandra_version
  @cassandra_version ||= execute('select release_version from system.local').rows.first['release_version'].to_f
end

#connectionObject



103
104
105
106
107
108
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 103

def connection
  @connection ||= begin
    cluster = Cassandra.cluster cassandra_cluster_options
    cluster.connect config[:keyspace]
  end
end

#consistencyObject

/SCHEMA



221
222
223
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 221

def consistency
  defined?(@consistency) ? @consistency : nil
end

#consistency=(val) ⇒ Object



225
226
227
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 225

def consistency=(val)
  @consistency = val
end

#create_table(table_name, params = {}) ⇒ Object

SCHEMA



187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 187

def create_table(table_name, params = {})
  stmt = "CREATE TABLE #{table_name} "
  if params.any? && !params[:attributes].present?
    raise 'No attributes for the table'
  elsif !params[:attributes].include? 'PRIMARY KEY'
    raise 'No PRIMARY KEY defined'
  end

  stmt += "(#{params[:attributes]})"
  # WITH COMPACT STORAGE
  schema_execute statement_create_with_options(stmt, params[:options]), config[:keyspace]
end

#delete(table, key, ids) ⇒ Object



170
171
172
173
174
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 170

def delete(table, key, ids)
  ids = [ids] if !ids.is_a?(Array)
  statement = "DELETE FROM #{table} WHERE #{key} IN (#{ids.map{|id| "'#{id}'"}.join(',')})"
  execute(statement, nil)
end

#drop_table(table_name, confirm = false) ⇒ Object



200
201
202
203
204
205
206
207
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 200

def drop_table(table_name, confirm = false)
  count = (schema_execute "SELECT count(*) FROM #{table_name}", config[:keyspace]).rows.first['count']
  if confirm || count == 0
    schema_execute "DROP TABLE #{table_name}", config[:keyspace]
  else
    raise "The table #{table_name} is not empty! If you want to drop it add the option confirm = true"
  end
end

#execute(statement, arguments = []) ⇒ Object



110
111
112
113
114
115
116
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 110

def execute(statement, arguments = [])
  ActiveSupport::Notifications.instrument('cql.cassandra_object', cql: statement) do
    type_hints = []
    arguments.each { |a| type_hints << CassandraObject::Types::TypeHelper.guess_type(a) } unless arguments.nil?
    connection.execute statement, arguments: arguments, type_hints: type_hints, consistency: consistency, page_size: config[:page_size]
  end
end

#execute_async(queries, arguments = []) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 118

def execute_async(queries, arguments = [])
  futures = queries.map do |q|
    ActiveSupport::Notifications.instrument('cql.cassandra_object', cql: q) do
      connection.execute_async q, arguments: arguments, consistency: consistency, page_size: config[:page_size]
    end
  end
  futures.map do |future|
    rows = future.get
    rows
  end
end

#execute_batch(statements) ⇒ Object



176
177
178
179
180
181
182
183
184
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 176

def execute_batch(statements)
  raise 'No can do' if statements.empty?
  batch = connection.batch do |b|
    statements.each do |statement|
      b.add(statement[:query], arguments: statement[:arguments])
    end
  end
  connection.execute(batch, page_size: config[:page_size])
end

#insert(table, id, attributes, ttl = nil) ⇒ Object



141
142
143
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 141

def insert(table, id, attributes, ttl = nil)
  write(table, id, attributes, ttl)
end

#schema_execute(cql, keyspace) ⇒ Object



209
210
211
212
213
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 209

def schema_execute(cql, keyspace)
  schema_db = Cassandra.cluster cassandra_cluster_options
  connection = schema_db.connect keyspace
  connection.execute cql, consistency: consistency
end

#select(scope) ⇒ Object



130
131
132
133
134
135
136
137
138
139
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 130

def select(scope)
  queries = QueryBuilder.new(self, scope).to_query_async
  # todo paginate
  cql_rows = execute_async(queries).map{|item| item.rows.map{|x| x}}.flatten!
  cql_rows.each do |cql_row|
    attributes = cql_row.to_hash
    key = attributes.delete(scope._key)
    yield(key, attributes) unless attributes.empty?
  end
end

#statement_create_with_options(stmt, options = '') ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 229

def statement_create_with_options(stmt, options = '')
  if !options.nil?
    statement_with_options stmt, options
  else
    # standard
    if cassandra_version < 3
      "#{stmt} WITH bloom_filter_fp_chance = 0.001
        AND caching = '{\"keys\":\"ALL\", \"rows_per_partition\":\"NONE\"}'
        AND comment = ''
        AND compaction = {'min_sstable_size': '52428800', 'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'}
        AND compression = {'chunk_length_kb': '64', 'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
        AND dclocal_read_repair_chance = 0.0
        AND default_time_to_live = 0
        AND gc_grace_seconds = 864000
        AND max_index_interval = 2048
        AND memtable_flush_period_in_ms = 0
        AND min_index_interval = 128
        AND read_repair_chance = 1.0
        AND speculative_retry = 'NONE';"
    else
      "#{stmt} WITH read_repair_chance = 0.0
        AND dclocal_read_repair_chance = 0.1
        AND gc_grace_seconds = 864000
        AND bloom_filter_fp_chance = 0.01
        AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 'NONE' }
        AND comment = ''
        AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold' : 32, 'min_threshold' : 4 }
        AND compression = { 'chunk_length_in_kb' : 64, 'class' : 'org.apache.cassandra.io.compress.LZ4Compressor' }
        AND default_time_to_live = 0
        AND speculative_retry = '99PERCENTILE'
        AND min_index_interval = 128
        AND max_index_interval = 2048
        AND crc_check_chance = 1.0;
      "
    end
  end
end

#update(table, id, attributes, ttl = nil) ⇒ Object



145
146
147
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 145

def update(table, id, attributes, ttl = nil)
  write_update(table, id, attributes)
end

#write(table, id, attributes, ttl = nil) ⇒ Object



149
150
151
152
153
154
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 149

def write(table, id, attributes, ttl = nil)
  statement = "INSERT INTO #{table} (#{(attributes.keys).join(',')}) VALUES (#{(['?'] * attributes.size).join(',')})"
  statement += " USING TTL #{ttl.to_s}" if ttl.present?
  arguments = attributes.values
  execute(statement, arguments)
end

#write_update(table, id, attributes) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/cassandra_object/adapters/cassandra_adapter.rb', line 156

def write_update(table, id, attributes)
  queries =[]
  # id here is the name of the key of the model
  id_value = attributes[id]
  if (not_nil_attributes = attributes.reject { |key, value| value.nil? }).any?
    statement = "INSERT INTO #{table} (#{(not_nil_attributes.keys).join(',')}) VALUES (#{(['?'] * not_nil_attributes.size).join(',')})"
    queries << {query: statement, arguments: not_nil_attributes.values}
  end
  if (nil_attributes = attributes.select { |key, value| value.nil? }).any?
    queries << {query: "DELETE #{nil_attributes.keys.join(',')} FROM #{table} WHERE #{id} = ?", arguments: [id_value.to_s]}
  end
  execute_batchable(queries)
end