Class: Dynamoid::AdapterPlugin::AwsSdkV2

Inherits:
Object
  • Object
show all
Defined in:
lib/dynamoid/adapter_plugin/aws_sdk_v2.rb

Overview

The AwsSdkV2 adapter provides support for the aws-sdk version 2 for ruby.

Defined Under Namespace

Classes: ItemUpdater, Table

Constant Summary collapse

EQ =
"EQ".freeze
RANGE_MAP =
{
  range_greater_than: 'GT',
  range_less_than:    'LT',
  range_gte:          'GE',
  range_lte:          'LE',
  range_begins_with:  'BEGINS_WITH',
  range_between:      'BETWEEN'
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#table_cacheObject (readonly)

Returns the value of attribute table_cache.



6
7
8
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 6

def table_cache
  @table_cache
end

Instance Method Details

#batch_delete_item(options) ⇒ Object

Delete many items at once from DynamoDB. More efficient than delete each item individually.

or

Dynamoid::Adapter::AwsSdkV2.batch_delete_item('table1' => [['hk1', 'rk2'], ['hk1', 'rk2']]]))

@todo: Provide support for passing options to underlying delete_item docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html#delete_item-instance_method

Examples:

Delete IDs 1 and 2 from the table testtable

Dynamoid::Adapter::AwsSdk.batch_delete_item('table1' => ['1', '2'])

Parameters:

  • options (Hash)

    the hash of tables and IDs to delete

Returns:

  • nil



88
89
90
91
92
93
94
95
96
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 88

def batch_delete_item(options)
  options.each_pair do |table_name, ids|
    table = describe_table(table_name)
    ids.each do |id|
      client.delete_item(table_name: table_name, key: key_stanza(table, *id))
    end
  end
  nil
end

#batch_get_item(table_ids, options = {}) ⇒ Hash

Get many items at once from DynamoDB. More efficient than getting each item individually.

@todo: Provide support for passing options to underlying batch_get_item docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html#batch_get_item-instance_method

Examples:

Retrieve IDs 1 and 2 from the table testtable

Dynamoid::Adapter::AwsSdkV2.batch_get_item({'table1' => ['1', '2']})

Parameters:

  • table_ids (Hash)

    the hash of tables and IDs to retrieve

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

    to be passed to underlying BatchGet call

Returns:

  • (Hash)

    a hash where keys are the table names and the values are the retrieved items

Since:

  • 1.0.0



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
66
67
68
69
70
71
72
73
74
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 40

def batch_get_item(table_ids, options = {})
  request_items = Hash.new{|h, k| h[k] = []}
  return request_items if table_ids.all?{|k, v| v.empty?}

  table_ids.each do |t, ids|
    next if ids.empty?
    tbl = describe_table(t)
    hk  = tbl.hash_key.to_s
    rng = tbl.range_key.to_s

    keys = if rng.present?
      Array(ids).map do |h,r|
        { hk => h, rng => r }
      end
    else
      Array(ids).map do |id|
        { hk => id }
      end
    end

    request_items[t] = {
      keys: keys
    }
  end

  results = client.batch_get_item(
    request_items: request_items
  )

  ret = Hash.new([].freeze) # Default for tables where no rows are returned
  results.data[:responses].each do |table, rows|
    ret[table] = rows.collect { |r| result_item_to_hash(r) }
  end
  ret
end

#clientObject

Return the client object.

Since:

  • 1.0.0



23
24
25
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 23

def client
  @client
end

#connect!Aws::DynamoDB::Client

Establish the connection to DynamoDB.

Returns:

  • (Aws::DynamoDB::Client)

    the DynamoDB connection



11
12
13
14
15
16
17
18
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 11

def connect!
  @client = if Dynamoid::Config.endpoint?
    Aws::DynamoDB::Client.new(endpoint: Dynamoid::Config.endpoint)
  else
    Aws::DynamoDB::Client.new
  end
  @table_cache = {}
end

#count(table_name) ⇒ Object



399
400
401
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 399

def count(table_name)
  describe_table(table_name, true).item_count
end

#create_table(table_name, key = :id, options = {}) ⇒ Object

Create a table on DynamoDB. This usually takes a long time to complete.

Parameters:

  • table_name (String)

    the name of the table to create

  • key (Symbol) (defaults to: :id)

    the table’s primary key (defaults to :id)

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

    provide a range key here if the table has a composite key

Since:

  • 1.0.0



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 105

def create_table(table_name, key = :id, options = {})
  Dynamoid.logger.info "Creating #{table_name} table. This could take a while."
  read_capacity = options[:read_capacity] || Dynamoid::Config.read_capacity
  write_capacity = options[:write_capacity] || Dynamoid::Config.write_capacity
  range_key = options[:range_key]

  key_schema = [
    { attribute_name: key.to_s, key_type: HASH_KEY }
  ]
  key_schema << {
    attribute_name: range_key.keys.first.to_s, key_type: RANGE_KEY
  } if(range_key)

  #TODO: Provide support for number and binary hash key
  attribute_definitions = [
    { attribute_name: key.to_s, attribute_type: 'S' }
  ]
  attribute_definitions << {
    attribute_name: range_key.keys.first.to_s, attribute_type: api_type(range_key.values.first)
  } if(range_key)

  client.create_table(table_name: table_name,
    provisioned_throughput: {
      read_capacity_units: read_capacity,
      write_capacity_units: write_capacity
    },
    key_schema: key_schema,
    attribute_definitions: attribute_definitions
  )
rescue Aws::DynamoDB::Errors::ResourceInUseException => e
  Dynamoid.logger.error "Table #{table_name} cannot be created as it already exists"
end

#delete_item(table_name, key, options = {}) ⇒ Object

Removes an item from DynamoDB.

@todo: Provide support for various options docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html#delete_item-instance_method

Parameters:

  • table_name (String)

    the name of the table

  • key (String)

    the hash key of the item to delete

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

    provide a range key here if the table has a composite key

Since:

  • 1.0.0



147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 147

def delete_item(table_name, key, options = {})
  range_key = options[:range_key]
  conditions = options[:conditions]
  table = describe_table(table_name)
  client.delete_item(
    table_name: table_name,
    key: key_stanza(table, key, range_key),
    expected: expected_stanza(conditions)
  )
rescue Aws::DynamoDB::Errors::ConditionalCheckFailedException => e
  raise Dynamoid::Errors::ConditionalCheckFailedException, e
end

#delete_table(table_name) ⇒ Object

Deletes an entire table from DynamoDB.

Parameters:

  • table_name (String)

    the name of the table to destroy

Since:

  • 1.0.0



165
166
167
168
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 165

def delete_table(table_name)
  client.delete_table(table_name: table_name)
  table_cache.clear
end

#get_item(table_name, key, options = {}) ⇒ Hash

Fetches an item from DynamoDB.

Parameters:

  • table_name (String)

    the name of the table

  • key (String)

    the hash key of the item to find

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

    provide a range key here if the table has a composite key

Returns:

  • (Hash)

    a hash representing the raw item in DynamoDB

Since:

  • 1.0.0



183
184
185
186
187
188
189
190
191
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 183

def get_item(table_name, key, options = {})
  table    = describe_table(table_name)
  range_key = options.delete(:range_key)

  item = client.get_item(table_name: table_name,
    key: key_stanza(table, key, range_key)
  )[:item]
  item ? result_item_to_hash(item) : nil
end

#list_tablesObject

List all tables on DynamoDB.

Since:

  • 1.0.0



228
229
230
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 228

def list_tables
  client.list_tables[:table_names]
end

#put_item(table_name, object, options = nil) ⇒ Object

Persists an item on DynamoDB.

@todo: Provide support for various options docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html#put_item-instance_method

Parameters:

  • table_name (String)

    the name of the table

  • object (Object)

    a hash or Dynamoid object to persist

Since:

  • 1.0.0



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 240

def put_item(table_name, object, options = nil)
  item = {}

  object.each do |k, v|
    next if v.nil? || (v.respond_to?(:empty?) && v.empty?)
    item[k.to_s] = v
  end

  begin
    client.put_item(table_name: table_name,
      item: item,
      expected: expected_stanza(options)
    )
  rescue Aws::DynamoDB::Errors::ConditionalCheckFailedException => e
    raise Dynamoid::Errors::ConditionalCheckFailedException, e
  end
end

#query(table_name, opts = {}) ⇒ Enumerable

Query the DynamoDB table. This employs DynamoDB’s indexes so is generally faster than scanning, but is only really useful for range queries, since it can only find by one hash key at once. Only provide one range key to the hash.

Parameters:

  • table_name (String)

    the name of the table

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

    the options to query the table with

Options Hash (opts):

  • :hash_value (String)

    the value of the hash key to find

  • :range_between (Number, Number)

    find the range key within this range

  • :range_greater_than (Number)

    find range keys greater than this

  • :range_less_than (Number)

    find range keys less than this

  • :range_gte (Number)

    find range keys greater than or equal to this

  • :range_lte (Number)

    find range keys less than or equal to this

Returns:

  • (Enumerable)

    matching items

Since:

  • 1.0.0



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 276

def query(table_name, opts = {})
  table = describe_table(table_name)
  hk    = table.hash_key.to_s
  rng   = table.range_key.to_s
  q     = opts.slice(:consistent_read, :scan_index_forward, :limit, :select)

  opts.delete(:consistent_read)
  opts.delete(:scan_index_forward)
  opts.delete(:limit)
  opts.delete(:select)

  opts.delete(:next_token).tap do |token|
    break unless token
    q[:exclusive_start_key] = {
      hk  => token[:hash_key_element],
      rng => token[:range_key_element]
    }
  end

  key_conditions = {
    hk => {
      # TODO: Provide option for other operators like NE, IN, LE, etc
      comparison_operator: EQ,
      attribute_value_list: [
        opts.delete(:hash_value).freeze
      ]
    }
  }

  opts.each_pair do |k, v|
    # TODO: ATM, only few comparison operators are supported, provide support for all operators
    next unless(op = RANGE_MAP[k])
    key_conditions[rng] = {
      comparison_operator: op,
      attribute_value_list: [
        opts.delete(k).freeze
      ].flatten # Flatten as BETWEEN operator specifies array of two elements
    }
  end

  q[:table_name]     = table_name
  q[:key_conditions] = key_conditions

  Enumerator.new { |y|
    result = client.query(q)

    result.items.each { |r|
      y << result_item_to_hash(r)
    }
  }
end

#scan(table_name, scan_hash, select_opts = {}) ⇒ Enumerable

Scan the DynamoDB table. This is usually a very slow operation as it naively filters all data on the DynamoDB servers.

@todo: Provide support for various options docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html#scan-instance_method

Parameters:

  • table_name (String)

    the name of the table

  • scan_hash (Hash)

    a hash of attributes: matching records will be returned by the scan

Returns:

  • (Enumerable)

    matching items

Since:

  • 1.0.0



350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 350

def scan(table_name, scan_hash, select_opts = {})
  limit = select_opts.delete(:limit)
  batch = select_opts.delete(:batch_size)

  request = { table_name: table_name }
  request[:limit] = batch || limit if batch || limit
  request[:scan_filter] = scan_hash.reduce({}) do |memo, kvp|
    memo[kvp[0].to_s] = {
      attribute_value_list: [kvp[1]],
      # TODO: Provide support for all comparison operators
      comparison_operator: EQ
    }
    memo
  end if scan_hash.present?

  Enumerator.new do |y|
    # Batch loop, pulls multiple requests until done using the start_key
    loop do
      results = client.scan(request)

      results.data[:items].each { |row| y << result_item_to_hash(row) }

      if((lk = results[:last_evaluated_key]) && batch)
        request[:exclusive_start_key] = lk
      else
        break
      end
    end
  end
end

#truncate(table_name) ⇒ Object

Truncates all records in the given table

Parameters:

  • table_name (String)

    the name of the table

Since:

  • 1.0.0



388
389
390
391
392
393
394
395
396
397
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 388

def truncate(table_name)
  table = describe_table(table_name)
  hk    = table.hash_key
  rk    = table.range_key

  scan(table_name, {}, {}).each do |attributes|
    opts = {range_key: attributes[rk.to_sym] } if rk
    delete_item(table_name, attributes[hk], opts)
  end
end

#update_item(table_name, key, options = {}) {|iu = ItemUpdater.new(table, key, range_key)| ... } ⇒ Object

Edits an existing item’s attributes, or adds a new item to the table if it does not already exist. You can put, delete, or add attribute values

Parameters:

  • table_name (String)

    the name of the table

  • key (String)

    the hash key of the item to find

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

    provide a range key here if the table has a composite key

Yields:

Returns:

  • new attributes for the record



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/dynamoid/adapter_plugin/aws_sdk_v2.rb', line 202

def update_item(table_name, key, options = {})
  range_key = options.delete(:range_key)
  conditions = options.delete(:conditions)
  table = describe_table(table_name)

  yield(iu = ItemUpdater.new(table, key, range_key))

  raise "non-empty options: #{options}" unless options.empty?
  begin
    result = client.update_item(table_name: table_name,
      key: key_stanza(table, key, range_key),
      attribute_updates: iu.to_h,
      expected: expected_stanza(conditions),
      return_values: "ALL_NEW"
    )
    result_item_to_hash(result[:attributes])
  rescue Aws::DynamoDB::Errors::ConditionalCheckFailedException => e
    raise Dynamoid::Errors::ConditionalCheckFailedException, e
  end
end