Class: CassandraStore::Base

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Dirty, ActiveModel::Validations, Hooks
Defined in:
lib/cassandra_store/base.rb

Direct Known Subclasses

SchemaMigration

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Base

Returns a new instance of Base.



51
52
53
54
55
56
# File 'lib/cassandra_store/base.rb', line 51

def initialize(attributes = {})
  @persisted = false
  @destroyed = false

  assign(attributes)
end

Class Method Details

.cast_value(value, type) ⇒ Object



228
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_store/base.rb', line 228

def self.cast_value(value, type)
  return nil if value.nil?

  case type
  when :text
    value.to_s
  when :int, :bigint
    Integer(value)
  when :boolean
    return true if [1, "1", "true", true].include?(value)
    return false if [0, "0", "false", false].include?(value)

    raise ArgumentError, "Can't cast '#{value}' to #{type}"
  when :date
    if value.is_a?(String) then Date.parse(value)
    elsif value.respond_to?(:to_date) then value.to_date
    else raise(ArgumentError, "Can't cast '#{value}' to #{type}")
    end
  when :timestamp
    if value.is_a?(String) then Time.parse(value)
    elsif value.respond_to?(:to_time) then value.to_time
    elsif value.is_a?(Numeric) then Time.at(value)
    else raise(ArgumentError, "Can't cast '#{value}' to #{type}")
    end.utc.round(3)
  when :timeuuid
    return value if value.is_a?(Cassandra::TimeUuid)
    return Cassandra::TimeUuid.new(value) if value.is_a?(String) || value.is_a?(Integer)

    raise ArgumentError, "Can't cast '#{value}' to #{type}"
  when :uuid
    return value if value.is_a?(Cassandra::Uuid)
    return Cassandra::Uuid.new(value) if value.is_a?(String) || value.is_a?(Integer)

    raise ArgumentError, "Can't cast '#{value}' to #{type}"
  else
    raise CassandraStore::UnknownType, "Unknown type #{type}"
  end
end

.cluster_execute(statement, options = {}) ⇒ Object



304
305
306
307
308
309
310
# File 'lib/cassandra_store/base.rb', line 304

def self.cluster_execute(statement, options = {})
  logger.debug(statement)

  cluster_pool.with do |connection|
    connection.execute(statement, options)
  end
end

.clustering_key_columnsObject



198
199
200
# File 'lib/cassandra_store/base.rb', line 198

def self.clustering_key_columns
  columns.select { |_, options| options[:clustering_key] }
end

.column(name, type, partition_key: false, clustering_key: false) ⇒ Object



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/cassandra_store/base.rb', line 202

def self.column(name, type, partition_key: false, clustering_key: false)
  self.columns = columns.merge(name => { type: type, partition_key: partition_key, clustering_key: clustering_key })

  define_attribute_methods name

  define_method name do
    read_raw_attribute(name)
  end

  define_method :"#{name}=" do |value|
    raise(ArgumentError, "Can't update key '#{name}' for persisted records") if persisted? && (self.class.columns[name][:partition_key] || self.class.columns[name][:clustering_key])

    send :"#{name}_will_change!" unless read_raw_attribute(name) == value

    write_raw_attribute(name, self.class.cast_value(value, type))
  end
end

.configure(hosts: ["127.0.0.1"], keyspace:, cluster_settings: {}, replication: {}, durable_writes: true, pool: { size: 5, timeout: 5 }) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/cassandra_store/base.rb', line 23

def self.configure(hosts: ["127.0.0.1"], keyspace:, cluster_settings: {}, replication: {}, durable_writes: true, pool: { size: 5, timeout: 5 })
  self.keyspace_settings = { name: keyspace, replication: replication, durable_writes: durable_writes }

  self.cluster_pool = ConnectionPool.new(pool) do
    Cassandra.cluster(cluster_settings.merge(hosts: hosts)).connect
  end

  self.connection_pool = ConnectionPool.new(pool) do
    Cassandra.cluster(cluster_settings.merge(hosts: hosts)).connect(keyspace)
  end
end

.create(attributes = {}) ⇒ Object



100
101
102
# File 'lib/cassandra_store/base.rb', line 100

def self.create(attributes = {})
  new(attributes).tap(&:save)
end

.create!(attributes = {}) ⇒ Object



96
97
98
# File 'lib/cassandra_store/base.rb', line 96

def self.create!(attributes = {})
  new(attributes).tap(&:save!)
end

.create_keyspace(name: , replication: , durable_writes: , if_not_exists: false) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/cassandra_store/base.rb', line 39

def self.create_keyspace(name: keyspace_settings[:name], replication: keyspace_settings[:replication], durable_writes: keyspace_settings[:durable_writes], if_not_exists: false)
  cql = <<~CQL
    CREATE KEYSPACE #{if_not_exists ? "IF NOT EXISTS" : ""} #{quote_keyspace_name(name)}
      WITH REPLICATION = {
        #{replication.map { |key, value| "#{quote_value(key)}: #{quote_value(value)}" }.join(", ")}
      }
      AND DURABLE_WRITES = #{quote_value(durable_writes)}
  CQL

  cluster_execute(cql)
end

.drop_keyspace(name: , if_exists: false) ⇒ Object



35
36
37
# File 'lib/cassandra_store/base.rb', line 35

def self.drop_keyspace(name: keyspace_settings[:name], if_exists: false)
  cluster_execute("DROP KEYSPACE #{if_exists ? "IF EXISTS" : ""} #{quote_keyspace_name(name)}")
end

.execute(statement, options = {}) ⇒ Object



312
313
314
315
316
317
318
# File 'lib/cassandra_store/base.rb', line 312

def self.execute(statement, options = {})
  logger.debug(statement)

  connection_pool.with do |connection|
    connection.execute(statement, options)
  end
end

.execute_batch(statements, options = {}) ⇒ Object



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/cassandra_store/base.rb', line 320

def self.execute_batch(statements, options = {})
  statements.each do |statement|
    logger.debug(statement)
  end

  connection_pool.with do |connection|
    batch = connection.send(:"#{options[:batch_type] || "logged"}_batch")

    statements.each do |statement|
      batch.add(statement)
    end

    connection.execute(batch, options.except(:batch_type))
  end
end

.key_columnsObject



190
191
192
# File 'lib/cassandra_store/base.rb', line 190

def self.key_columns
  partition_key_columns.merge(clustering_key_columns)
end

.partition_key_columnsObject



194
195
196
# File 'lib/cassandra_store/base.rb', line 194

def self.partition_key_columns
  columns.select { |_, options| options[:partition_key] }
end

.quote_column_name(column_name) ⇒ Object

Raises:

  • (ArgumentError)


275
276
277
278
279
# File 'lib/cassandra_store/base.rb', line 275

def self.quote_column_name(column_name)
  raise(ArgumentError, "Invalid column name #{column_name}") if column_name.to_s.include?("\"")

  "\"#{column_name}\""
end

.quote_keyspace_name(keyspace_name) ⇒ Object



267
268
269
# File 'lib/cassandra_store/base.rb', line 267

def self.quote_keyspace_name(keyspace_name)
  quote_column_name(keyspace_name)
end

.quote_string(string) ⇒ Object



296
297
298
# File 'lib/cassandra_store/base.rb', line 296

def self.quote_string(string)
  "'#{string.gsub("'", "''")}'"
end

.quote_table_name(table_name) ⇒ Object



271
272
273
# File 'lib/cassandra_store/base.rb', line 271

def self.quote_table_name(table_name)
  quote_column_name(table_name)
end

.quote_value(value) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/cassandra_store/base.rb', line 281

def self.quote_value(value)
  case value
  when Time, ActiveSupport::TimeWithZone
    (value.to_r * 1000).round.to_s
  when DateTime
    quote_value(value.utc.to_time)
  when Date
    quote_value(value.strftime("%Y-%m-%d"))
  when Numeric, true, false, Cassandra::Uuid
    value.to_s
  else
    quote_string(value.to_s)
  end
end

.relationObject



220
221
222
# File 'lib/cassandra_store/base.rb', line 220

def self.relation
  CassandraStore::Relation.new(target: self)
end

.statement(template, args = {}) ⇒ Object



336
337
338
339
340
341
342
343
344
# File 'lib/cassandra_store/base.rb', line 336

def self.statement(template, args = {})
  res = template.dup

  args.each do |key, value|
    res.gsub!(":#{key}", quote_value(value))
  end

  res
end

.table_nameObject



186
187
188
# File 'lib/cassandra_store/base.rb', line 186

def self.table_name
  name.tableize
end

.truncate_tableObject



300
301
302
# File 'lib/cassandra_store/base.rb', line 300

def self.truncate_table
  execute "TRUNCATE TABLE #{quote_table_name table_name}"
end

Instance Method Details

#==(other) ⇒ Object



58
59
60
# File 'lib/cassandra_store/base.rb', line 58

def ==(other)
  other.instance_of?(self.class) && key_values == other.key_values
end

#assign(attributes = {}) ⇒ Object



74
75
76
77
78
# File 'lib/cassandra_store/base.rb', line 74

def assign(attributes = {})
  attributes.each do |column, value|
    send(:"#{column}=", value)
  end
end

#attributesObject



80
81
82
83
84
# File 'lib/cassandra_store/base.rb', line 80

def attributes
  columns.each_with_object({}) do |(name, _), hash|
    hash[name] = read_raw_attribute(name)
  end
end

#deleteObject



178
179
180
181
182
183
184
# File 'lib/cassandra_store/base.rb', line 178

def delete
  raise CassandraStore::RecordNotPersisted unless persisted?

  self.class.execute(delete_record_statement)

  true
end

#destroyObject



164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/cassandra_store/base.rb', line 164

def destroy
  raise CassandraStore::RecordNotPersisted unless persisted?

  run_hook :before_destroy

  delete

  destroyed!

  run_hook :after_destroy

  true
end

#destroyed!Object



148
149
150
# File 'lib/cassandra_store/base.rb', line 148

def destroyed!
  @destroyed = true
end

#destroyed?Boolean

Returns:

  • (Boolean)


144
145
146
# File 'lib/cassandra_store/base.rb', line 144

def destroyed?
  !!@destroyed
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/cassandra_store/base.rb', line 62

def eql?(other)
  self == other
end

#hashObject



66
67
68
# File 'lib/cassandra_store/base.rb', line 66

def hash
  key_values.hash
end

#key_valuesObject



70
71
72
# File 'lib/cassandra_store/base.rb', line 70

def key_values
  self.class.key_columns.map { |column, _| read_raw_attribute(column) }
end

#new_record?Boolean

Returns:

  • (Boolean)


140
141
142
# File 'lib/cassandra_store/base.rb', line 140

def new_record?
  !persisted?
end

#persisted!Object



136
137
138
# File 'lib/cassandra_store/base.rb', line 136

def persisted!
  @persisted = true
end

#persisted?Boolean

Returns:

  • (Boolean)


132
133
134
# File 'lib/cassandra_store/base.rb', line 132

def persisted?
  !!@persisted
end

#read_raw_attribute(attribute) ⇒ Object



86
87
88
89
90
# File 'lib/cassandra_store/base.rb', line 86

def read_raw_attribute(attribute)
  return nil unless instance_variable_defined?(:"@#{attribute}")

  instance_variable_get(:"@#{attribute}")
end

#saveObject



110
111
112
113
114
# File 'lib/cassandra_store/base.rb', line 110

def save
  return false unless valid?

  _save
end

#save!Object



104
105
106
107
108
# File 'lib/cassandra_store/base.rb', line 104

def save!
  validate!

  _save
end

#update(attributes = {}) ⇒ Object



152
153
154
155
156
# File 'lib/cassandra_store/base.rb', line 152

def update(attributes = {})
  assign(attributes)

  save
end

#update!(attributes = {}) ⇒ Object



158
159
160
161
162
# File 'lib/cassandra_store/base.rb', line 158

def update!(attributes = {})
  assign(attributes)

  save!
end

#valid?(context = nil) ⇒ Boolean

Returns:

  • (Boolean)


116
117
118
119
120
121
122
123
124
125
126
# File 'lib/cassandra_store/base.rb', line 116

def valid?(context = nil)
  context ||= new_record? ? :create : :update

  run_hook :before_validation

  retval = super(context)

  run_hook :after_validation

  retval
end

#validate!(context = nil) ⇒ Object



128
129
130
# File 'lib/cassandra_store/base.rb', line 128

def validate!(context = nil)
  valid?(context) || raise(CassandraStore::RecordInvalid, errors.to_a.join(", "))
end

#write_raw_attribute(attribute, value) ⇒ Object



92
93
94
# File 'lib/cassandra_store/base.rb', line 92

def write_raw_attribute(attribute, value)
  instance_variable_set(:"@#{attribute}", value)
end