Module: Dynamoid::Persistence::ClassMethods

Defined in:
lib/dynamoid/persistence.rb

Instance Method Summary collapse

Instance Method Details

#create(attrs = {}) ⇒ Dynamoid::Document

Create a model.

Initializes a new object and immediately saves it to the database. Validates model and runs callbacks: before_create, before_save, after_save and after_create. Accepts both Hash and Array of Hashes and can create several models.

Parameters:

  • attrs (Hash|Array[Hash]) (defaults to: {})

    Attributes with which to create the object.

Returns:

Since:

  • 0.2.0



97
98
99
100
101
102
103
# File 'lib/dynamoid/persistence.rb', line 97

def create(attrs = {})
  if attrs.is_a?(Array)
    attrs.map { |attr| create(attr) }
  else
    build(attrs).tap(&:save)
  end
end

#create!(attrs = {}) ⇒ Dynamoid::Document

Create new model.

Initializes a new object and immediately saves it to the database. Raises an exception if validation failed. Accepts both Hash and Array of Hashes and can create several models.

Parameters:

  • attrs (Hash|Array[Hash]) (defaults to: {})

    Attributes with which to create the object.

Returns:

Since:

  • 0.2.0



116
117
118
119
120
121
122
# File 'lib/dynamoid/persistence.rb', line 116

def create!(attrs = {})
  if attrs.is_a?(Array)
    attrs.map { |attr| create!(attr) }
  else
    build(attrs).tap(&:save!)
  end
end

#create_table(options = {}) ⇒ Object

Create a table.

Parameters:

  • options (Hash) (defaults to: {})

    options to pass for table creation

Options Hash (options):

  • :id (Symbol)

    the id field for the table

  • :table_name (Symbol)

    the actual name for the table

  • :read_capacity (Integer)

    set the read capacity for the table; does not work on existing tables

  • :write_capacity (Integer)

    set the write capacity for the table; does not work on existing tables

  • {range_key (Hash)

    > :type} a hash of the name of the range key and a symbol of its type

  • :hash_key_type (Symbol)

    the dynamo type of the hash key (:string or :number)

Since:

  • 0.4.0



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/dynamoid/persistence.rb', line 41

def create_table(options = {})
  range_key_hash = if range_key
                     { range_key => PrimaryKeyTypeMapping.dynamodb_type(attributes[range_key][:type], attributes[range_key]) }
                   end

  options = {
    id: hash_key,
    table_name: table_name,
    write_capacity: write_capacity,
    read_capacity: read_capacity,
    range_key: range_key_hash,
    hash_key_type: PrimaryKeyTypeMapping.dynamodb_type(attributes[hash_key][:type], attributes[hash_key]),
    local_secondary_indexes: local_secondary_indexes.values,
    global_secondary_indexes: global_secondary_indexes.values
  }.merge(options)

  Dynamoid.adapter.create_table(options[:table_name], options[:id], options)
end

#delete_tableObject

Deletes the table for the model



61
62
63
# File 'lib/dynamoid/persistence.rb', line 61

def delete_table
  Dynamoid.adapter.delete_table(table_name)
end

#from_database(attrs = {}) ⇒ Object



65
66
67
68
69
# File 'lib/dynamoid/persistence.rb', line 65

def from_database(attrs = {})
  klass = choose_right_class(attrs)
  attrs_undumped = Undumping.undump_attributes(attrs, klass.attributes)
  klass.new(attrs_undumped).tap { |r| r.new_record = false }
end

#import(array_of_attributes) ⇒ Object

Create several models at once.

Neither callbacks nor validations run. It works efficiently because of using ‘BatchWriteItem` API call. Return array of models. Uses backoff specified by `Dynamoid::Config.backoff` config option

Examples:

User.import([{ name: 'a' }, { name: 'b' }])

Parameters:

  • array_of_attributes (Array<Hash>)


82
83
84
# File 'lib/dynamoid/persistence.rb', line 82

def import(array_of_attributes)
  Import.call(self, array_of_attributes)
end

#inc(hash_key_value, range_key_value = nil, counters) ⇒ Dynamoid::Document/nil

Increase numeric field by specified value.

Can update several fields at once. Uses efficient low-level ‘UpdateItem` API call.

Examples:

Update document

Post.inc(101, views_counter: 2, downloads: 10)

Parameters:

  • hash_key_value (Scalar value)

    partition key

  • range_key_value (Scalar value) (defaults to: nil)

    sort key (optional)

  • counters (Hash)

    value to increase by

Returns:



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/dynamoid/persistence.rb', line 228

def inc(hash_key_value, range_key_value = nil, counters)
  options = if range_key
              value_casted = TypeCasting.cast_field(range_key_value, attributes[range_key])
              value_dumped = Dumping.dump_field(value_casted, attributes[range_key])
              { range_key: value_dumped }
            else
              {}
            end

  Dynamoid.adapter.update_item(table_name, hash_key_value, options) do |t|
    counters.each do |k, v|
      value_casted = TypeCasting.cast_field(v, attributes[k])
      value_dumped = Dumping.dump_field(value_casted, attributes[k])

      t.add(k => value_dumped)
    end
  end
end

#table_nameObject



25
26
27
28
29
# File 'lib/dynamoid/persistence.rb', line 25

def table_name
  table_base_name = options[:name] || base_class.name.split('::').last.downcase.pluralize

  @table_name ||= [Dynamoid::Config.namespace.to_s, table_base_name].reject(&:empty?).join('_')
end

#update(hash_key, range_key_value = nil, attrs) ⇒ Dynamoid::Doument

Update document with provided attributes.

Instantiates document and saves changes. Runs validations and callbacks.

Examples:

Update document

Post.update(101, title: 'New title')

Parameters:

  • partition (Scalar value)

    key

  • sort (Scalar value)

    key, optional

  • attributes (Hash)

Returns:

  • (Dynamoid::Doument)

    updated document



137
138
139
140
141
# File 'lib/dynamoid/persistence.rb', line 137

def update(hash_key, range_key_value = nil, attrs)
  model = find(hash_key, range_key: range_key_value, consistent_read: true)
  model.update_attributes(attrs)
  model
end

#update_fields(hash_key_value, range_key_value = nil, attrs = {}, conditions = {}) ⇒ Dynamoid::Document|nil

Update document.

Uses efficient low-level ‘UpdateItem` API call. Changes attibutes and loads new document version with one API call. Doesn’t run validations and callbacks. Can make conditional update. If a document doesn’t exist or specified conditions failed - returns ‘nil`

Examples:

Update document

Post.update_fields(101, read: true)

Update document with condition

Post.update_fields(101, { title: 'New title' }, if: { version: 1 })

Parameters:

  • partition (Scalar value)

    key

  • sort (Scalar value)

    key (optional)

  • attributes (Hash)
  • conditions (Hash) (defaults to: {})

Returns:



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/dynamoid/persistence.rb', line 162

def update_fields(hash_key_value, range_key_value = nil, attrs = {}, conditions = {})
  optional_params = [range_key_value, attrs, conditions].compact
  if optional_params.first.is_a?(Hash)
    range_key_value = nil
    attrs, conditions = optional_params[0..1]
  else
    range_key_value = optional_params.first
    attrs, conditions = optional_params[1..2]
  end

  UpdateFields.call(self,
                    partition_key: hash_key_value,
                    sort_key: range_key_value,
                    attributes: attrs,
                    conditions: conditions)
end

#upsert(hash_key_value, range_key_value = nil, attrs = {}, conditions = {}) ⇒ Dynamoid::Document/nil

Update existing document or create new one.

Similar to ‘.update_fields`. The only diffirence is - it creates new document in case the document doesn’t exist.

Uses efficient low-level ‘UpdateItem` API call. Changes attibutes and loads new document version with one API call. Doesn’t run validations and callbacks. Can make conditional update. If specified conditions failed - returns ‘nil`.

Examples:

Update document

Post.upsert(101, title: 'New title')

Parameters:

  • partition (Scalar value)

    key

  • sort (Scalar value)

    key (optional)

  • attributes (Hash)
  • conditions (Hash) (defaults to: {})

Returns:



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/dynamoid/persistence.rb', line 198

def upsert(hash_key_value, range_key_value = nil, attrs = {}, conditions = {})
  optional_params = [range_key_value, attrs, conditions].compact
  if optional_params.first.is_a?(Hash)
    range_key_value = nil
    attrs, conditions = optional_params[0..1]
  else
    range_key_value = optional_params.first
    attrs, conditions = optional_params[1..2]
  end

  Upsert.call(self,
              partition_key: hash_key_value,
              sort_key: range_key_value,
              attributes: attrs,
              conditions: conditions)
end