Class: AWS::SimpleDB::ItemCollection

Inherits:
Object
  • Object
show all
Includes:
Core::Collection::WithLimitAndNextToken
Defined in:
lib/aws/simple_db/item_collection.rb

Overview

Represents a collection of items in a SimpleDB domain.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Core::Collection

#enum, #first, #in_groups_of, #page

Constructor Details

#initialize(domain, options = {}) ⇒ ItemCollection

Parameters:

  • domain (Domain)

    The domain that you want an item collection for.



49
50
51
52
53
54
55
56
57
# File 'lib/aws/simple_db/item_collection.rb', line 49

def initialize domain, options = {}
  @domain = domain
  @output_list = options[:output_list] || 'itemName()'
  @conditions = options[:conditions] || []
  @sort_instructions = options[:sort_instructions]
  @not_null_attribute = options[:not_null_attribute]
  @limit = options[:limit]
  super
end

Instance Attribute Details

#domainDomain (readonly)

Returns The domain the items belong to.

Returns:

  • (Domain)

    The domain the items belong to.



36
37
38
# File 'lib/aws/simple_db/item_collection.rb', line 36

def domain
  @domain
end

Instance Method Details

#[](item_name) ⇒ Item

Note:

This does not make a request to SimpleDB.

Retuns an item with the given name.

You can ask for any item. The named item may or may not actually exist in SimpleDB.

Examples:

Get an item by symbol or string name


item = domain.items[:itemname]
item = domain.items['itemname']

Parameters:

  • item_name (String, Symbol)

    name of the item to get.

Returns:

  • (Item)

    Returns an item with the given name.



91
92
93
# File 'lib/aws/simple_db/item_collection.rb', line 91

def [] item_name
  Item.new(domain, item_name.to_s)
end

#count(options = {}, &block) ⇒ Integer Also known as: size

Counts the items in the collection.

domain.items.count

You can specify what items to count with #where:

domain.items.where(:color => "red").count

You can also limit the number of items to count:

# count up to 500 items and then stop
domain.items.limit(500).count

Parameters:

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

    Options for counting items.

Options Hash (options):

  • :consistent_read (Boolean) — default: false

    Causes this method to yield the most current data in the domain when true.

  • :where (Object)

    Restricts the item collection using #where before querying.

  • :limit (Integer)

    The maximum number of items to count in SimpleDB.

Returns:

  • (Integer)

    The number of items counted.



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/aws/simple_db/item_collection.rb', line 205

def count options = {}, &block

  handle_query_options(options) do |collection, opts|
    return collection.count(opts, &block)
  end

  options = options.merge(:output_list => "count(*)")

  count = 0
  next_token = nil

  begin

    response = select_request(options, next_token)

    if 
      domain_item = response.items.first and
      count_attribute = domain_item.attributes.first
    then
      count += count_attribute.value.to_i
    end

    break unless next_token = response[:next_token]

  end while limit.nil? || count < limit

  count

end

#create(item_name, attributes) ⇒ Item

Creates a new item in SimpleDB with the given attributes:

domain.items.create('shirt', {
  'colors' => ['red', 'blue'],  
  'category' => 'clearance'})

Returns a reference to the object that was created.

Parameters:

  • item_name (String)

    The name of the item as you want it stored in SimpleDB.

  • attributes (Hash)

    A hash of attribute names and values you want to store in SimpleDB.

Returns:

  • (Item)

    Returns a reference to the object that was created.



71
72
73
74
75
# File 'lib/aws/simple_db/item_collection.rb', line 71

def create item_name, *args
  item = self[item_name]
  item.attributes.replace(*args)
  item
end

#each(options = {}) {|item| ... } ⇒ String?

Yields to the block once for each item in the collection. This method can yield two type of objects:

  • AWS::SimpleDB::Item objects (only the item name is populated)

  • AWS::SimpleDB::ItemData objects (some or all attributes populated)

The default mode of an ItemCollection is to yield Item objects with no populated attributes.

# only receives item names from SimpleDB
domain.items.each do |item|
  puts item.name
  puts item.class.name # => AWS::SimpleDB::Item
end

You can switch a collection into yielded AWS::SimpleDB::ItemData objects by specifying what attributes to request:

domain.items.select(:all).each do |item_data|
  puts item_data.class.name # => AWS::SimpleDB::ItemData
  puts item_data.attributes # => { 'attr-name' => 'attr-value', ... }
end

You can also pass the standard scope options to #each as well:

# output the item names of the 10 most expesive items
domain.items.each(:order => [:price, :desc], :limit => 10).each do |item|
  puts item.name
end

Parameters:

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

Options Hash (options):

  • :consistent_read (Boolean) — default: false

    Causes this method to yield the most current data in the domain.

  • :select (Mixed)

    If select is provided, then each will yield AWS::SimpleDB::ItemData objects instead of empty AWS::SimpleDB::Item. The :select option may be:

    • :all - Specifies that all attributes should requested.

    • A single or array of attribute names (as strings or symbols). This causes the named attribute(s) to be requested.

  • :where (Object)

    Restricts the item collection using #where before querying (see #where).

  • :order (Object)

    Changes the order in which the items will be yielded (see #order).

  • :limit (Integer)

    The maximum number of items to fetch from SimpleDB.

  • :batch_size (Object)

    Specifies a maximum number of records to fetch from SimpleDB in a single request. SimpleDB may return fewer items than :batch_size per request, but never more. Generally you should not need to specify this option.

Yields:

  • (item)

    Yields once for every item in the #domain.

Yield Parameters:

  • item (Item, ItemData)

    If the item collection has been scoped by chaining #select or by passing the :select option then AWS::SimpleDB::ItemData objects (that contain a hash of attrbiutes) are yielded. If no list of attributes has been provided, then# AWS::SimpleDB::Item objects (with no populated data) are yielded.

Returns:

  • (String, nil)

    Returns a next token that can be used with the exact same SimpleDB select expression to get more results. A next token is returned ONLY if there was a limit on the expression, otherwise all items will be enumerated and nil is returned.



167
168
169
# File 'lib/aws/simple_db/item_collection.rb', line 167

def each options = {}, &block
  super
end

#limitInteger #limit(value) ⇒ ItemCollection Also known as: _limit

Limits the number of items that are returned or yielded. For example, to get the 100 most popular item names:

domain.items.
  order(:popularity, :desc).
  limit(100).
  map(&:name)

Overloads:

  • #limitInteger

    Returns the current limit for the collection.

    Returns:

    • (Integer)

      Returns the current limit for the collection.

  • #limit(value) ⇒ ItemCollection

    Returns a collection with the given limit.

    Returns:



446
447
448
449
# File 'lib/aws/simple_db/item_collection.rb', line 446

def limit *args
  return @limit if args.empty?
  collection_with(:limit => Integer(args.first))
end

#order(attribute, order = nil) ⇒ ItemCollection

Changes the order in which results are returned or yielded. For example, to get item names in descending order of popularity, you can do:

domain.items.order(:popularity, :desc).map(&:name)

Parameters:

  • attribute (String or Symbol)

    The attribute name to order by.

  • order (String or Symbol) (defaults to: nil)

    The desired order, which may be:

    • asc or ascending (the default)

    • desc or descending

Returns:

  • (ItemCollection)

    Returns a new item collection with the given ordering logic.



424
425
426
427
428
429
430
# File 'lib/aws/simple_db/item_collection.rb', line 424

def order(attribute, order = nil)
  sort = coerce_attribute(attribute)
  sort += " DESC" if order.to_s =~ /^desc(ending)?$/
  sort += " ASC" if order.to_s =~ /^asc(ending)?$/
  collection_with(:sort_instructions => sort,
                  :not_null_attribute => attribute.to_s)
end

#select(*attributes, &block) ⇒ ItemCollection

Specifies a list of attributes select from SimpleDB.

domain.items.select('size', 'color').each do |item_data|
  puts item_data.attributes # => { 'size' => ..., :color => ... }
end

You can select all attributes by passing :all or ‘*’:

domain.items.select('*').each {|item_data| ... }

domain.items.select(:all).each {|item_data| ... }

Calling #select causes #each to yield AWS::SimpleDB::ItemData objects with #attribute hashes, instead of AWS::SimpleDB::Item objects with an item name.

Parameters:

  • attributes (Symbol, String, or Array)

    The attributes to retrieve. This can be:

    • :all or ‘*’ to request all attributes for each item

    • A list or array of attribute names as strinsg or symbols

      Attribute names may contain any characters that are valid in a SimpleDB attribute name; this method will handle escaping them for inclusion in the query. Note that you cannot use this method to select the number of items; use #count instead.

Returns:

  • (ItemCollection)

    Returns a new item collection with the specified list of attributes to select.



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
# File 'lib/aws/simple_db/item_collection.rb', line 282

def select *attributes, &block

  # Before select was morphed into a chainable method, it accepted
  # a hash of options (e.g. :where, :order, :limit) that no longer
  # make sense, but to maintain backwards compatability we still
  # consume those.
  #
  # TODO : it would be a good idea to add a deprecation warning for
  #        passing options to #select
  #
  handle_query_options(*attributes) do |collection, *args|
    return collection.select(*args, &block)
  end

  options = attributes.last.is_a?(Hash) ? attributes.pop : {}

  output_list = case attributes.flatten
  when []     then '*'
  when ['*']  then '*'
  when [:all] then '*'
  else attributes.flatten.map{|attr| coerce_attribute(attr) }.join(', ')
  end

  collection = collection_with(:output_list => output_list)

  if block_given?
    # previously select accepted a block and it would enumerate items
    # this is for backwards compatability
    collection.each(options, &block)
    nil
  else
    collection
  end

end

#where(conditions, *substitutions) ⇒ ItemCollection

Returns an item collection defined by the given conditions in addition to any conditions defined on this collection. For example:

items = domain.items.where(:color => 'blue').
  where('engine_type is not null')

# does SELECT itemName() FROM `mydomain`
#      WHERE color = "blue" AND engine_type is not null
items.each { |i| ... }

Hash Conditions

When conditions is a hash, each entry produces a condition on the attribute named in the hash key. For example:

# produces "WHERE `foo` = 'bar'"
domain.items.where(:foo => 'bar')

You can pass an array value to use an “IN” operator instead of “=”:

# produces "WHERE `foo` IN ('bar', 'baz')"
domain.items.where(:foo => ['bar', 'baz'])

You can also pass a range value to use a “BETWEEN” operator:

# produces "WHERE `foo` BETWEEN 'bar' AND 'baz'
domain.items.where(:foo => 'bar'..'baz')

# produces "WHERE (`foo` >= 'bar' AND `foo` < 'baz')"
domain.items.where(:foo => 'bar'...'baz')

Placeholders

If conditions is a string and “?” appears outside of any quoted part of the expression, placeholers is expected to contain a value for each of the “?” characters in the expression. For example:

# produces "WHERE foo like 'fred''s % value'"
domain.items.where("foo like ?", "fred's % value")

Array values are surrounded with parentheses when they are substituted for a placeholder:

# produces "WHERE foo in ('1', '2')"
domain.items.where("foo in ?", [1, 2])

Note that no substitutions are made within a quoted region of the query:

# produces "WHERE `foo?` = 'red'"
domain.items.where("`foo?` = ?", "red")

# produces "WHERE foo = 'fuzz?' AND bar = 'zap'"
domain.items.where("foo = 'fuzz?' AND bar = ?", "zap")

Also note that no attempt is made to correct for syntax:

# produces "WHERE 'foo' = 'bar'", which is invalid
domain.items.where("? = 'bar'", "foo")

Returns:

  • (ItemCollection)

    Returns a new item collection with the additional conditions.



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/aws/simple_db/item_collection.rb', line 384

def where conditions, *substitutions
  case conditions
  when String
    conditions = [replace_placeholders(conditions, *substitutions)]
  when Hash
    conditions = conditions.map do |name, value|
      name = coerce_attribute(name)
      case value
      when Array
        "#{name} IN " + coerce_substitution(value)
      when Range
        if value.exclude_end?
          "(#{name} >= #{coerce_substitution(value.begin)} AND " +
            "#{name} < #{coerce_substitution(value.end)})"
        else
          "#{name} BETWEEN #{coerce_substitution(value.begin)} AND " +
            coerce_substitution(value.end)
        end
      else
        "#{name} = " + coerce_substitution(value)
      end
    end
  end

  collection_with(:conditions => self.conditions + conditions)
end