hackerdude-aws 2.3.25

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,816 @@
1
+ #
2
+ # Copyright (c) 2008 RightScale Inc
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ #
23
+
24
+ require "aws"
25
+
26
+ module Aws
27
+
28
+ class SdbInterface < AwsBase
29
+
30
+ include AwsBaseInterface
31
+
32
+ DEFAULT_HOST = 'sdb.amazonaws.com'
33
+ DEFAULT_PORT = 443
34
+ DEFAULT_PROTOCOL = 'https'
35
+ DEFAULT_SERVICE = '/'
36
+ API_VERSION = '2009-04-15'
37
+ DEFAULT_NIL_REPRESENTATION = 'nil'
38
+
39
+ @@bench = AwsBenchmarkingBlock.new
40
+
41
+ def self.bench_xml;
42
+ @@bench.xml;
43
+ end
44
+
45
+ def self.bench_sdb;
46
+ @@bench.service;
47
+ end
48
+
49
+ attr_reader :last_query_expression
50
+
51
+ # Creates new RightSdb instance.
52
+ #
53
+ # Params:
54
+ # { :server => 'sdb.amazonaws.com' # Amazon service host: 'sdb.amazonaws.com'(default)
55
+ # :port => 443 # Amazon service port: 80(default) or 443
56
+ # :protocol => 'https' # Amazon service protocol: 'http'(default) or 'https'
57
+ # :signature_version => '2' # The signature version : '0', '1' or '2' (default)
58
+ # DEPRECATED :multi_thread => true|false # Multi-threaded (connection per each thread): true or false(default)
59
+ # :connection_mode => :default # options are :default (will use best known option, may change in the future)
60
+ # :per_request (opens and closes a connection on every request to SDB)
61
+ # :single - one connection shared across app (same as old multi_thread=>false)
62
+ # :per_thread - one connection per ruby thread (same as old multi_thread=>true)
63
+ # :pool (uses a connection pool with a maximum number of connections - NOT IMPLEMENTED YET)
64
+ # :logger => Logger Object # Logger instance: logs to STDOUT if omitted
65
+ # :nil_representation => 'mynil'} # interpret Ruby nil as this string value; i.e. use this string in SDB to represent Ruby nils (default is the string 'nil')
66
+ # :service => '/' # Set this to /mdb/request.mgwsi for usage with M/DB #
67
+ #
68
+ # Example:
69
+ #
70
+ # sdb = Aws::SdbInterface.new('1E3GDYEOGFJPIT7XXXXXX','hgTHt68JY07JKUY08ftHYtERkjgtfERn57XXXXXX', {:connection_mode => :per_request, :logger => Logger.new('/tmp/x.log')}) #=> #<RightSdb:0xa6b8c27c>
71
+ #
72
+ # see: http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/
73
+ #
74
+ def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
75
+ @nil_rep = params[:nil_representation] ? params[:nil_representation] : DEFAULT_NIL_REPRESENTATION
76
+ params.delete(:nil_representation)
77
+ init({ :name => 'SDB',
78
+ :default_host => ENV['SDB_URL'] ? URI.parse(ENV['SDB_URL']).host : DEFAULT_HOST,
79
+ :default_port => ENV['SDB_URL'] ? URI.parse(ENV['SDB_URL']).port : DEFAULT_PORT,
80
+ :default_protocol => ENV['SDB_URL'] ? URI.parse(ENV['SDB_URL']).scheme : DEFAULT_PROTOCOL,
81
+ :default_service => ENV['SDB_URL'] ? URI.parse(ENV['SDB_URL']).path : DEFAULT_SERVICE },
82
+ # :service_endpoint => ENV['SDB_URL'] ? URI.parse(ENV['SDB_URL']).path : DEFAULT_ENDPOINT },
83
+ aws_access_key_id || ENV['AWS_ACCESS_KEY_ID'],
84
+ aws_secret_access_key || ENV['AWS_SECRET_ACCESS_KEY'],
85
+ params)
86
+ end
87
+
88
+ #-----------------------------------------------------------------
89
+ # Requests
90
+ #-----------------------------------------------------------------
91
+ def generate_request(action, params={}) #:nodoc:
92
+ generate_request2(@aws_access_key_id, @aws_secret_access_key, action, API_VERSION, @params, params)
93
+ end
94
+
95
+
96
+ # Sends request to Amazon and parses the response
97
+ # Raises AwsError if any banana happened
98
+ def request_info(request, parser) #:nodoc:
99
+ # request_info2(request, parser, :sdb_connection)
100
+ request_info2(request, parser, @params, :sdb_connection, @logger, @@bench)
101
+
102
+ end
103
+
104
+ def close_connection
105
+ close_conn(:sdb_connection)
106
+ end
107
+
108
+ # Prepare attributes for putting.
109
+ # (used by put_attributes)
110
+ def pack_attributes(attributes, replace = false, key_prefix = "") #:nodoc:
111
+ result = {}
112
+ if attributes
113
+ idx = 0
114
+ skip_values = attributes.is_a?(Array)
115
+ attributes.each do |attribute, values|
116
+ # set replacement attribute
117
+ result["#{key_prefix}Attribute.#{idx}.Replace"] = 'true' if replace
118
+ # pack Name/Value
119
+ unless values.nil?
120
+ Array(values).each do |value|
121
+ result["#{key_prefix}Attribute.#{idx}.Name"] = attribute
122
+ result["#{key_prefix}Attribute.#{idx}.Value"] = ruby_to_sdb(value) unless skip_values
123
+ idx += 1
124
+ end
125
+ else
126
+ result["#{key_prefix}Attribute.#{idx}.Name"] = attribute
127
+ result["#{key_prefix}Attribute.#{idx}.Value"] = ruby_to_sdb(nil) unless skip_values
128
+ idx += 1
129
+ end
130
+ end
131
+ end
132
+ result
133
+ end
134
+
135
+
136
+ # Use this helper to manually escape the fields in the query expressions.
137
+ # To escape the single quotes and backslashes and to wrap the string into the single quotes.
138
+ #
139
+ # see: http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/SDB_API.html
140
+ #
141
+ def escape(value)
142
+ %Q{'#{value.to_s.gsub(/(['\\])/){ "\\#{$1}" }}'} if value
143
+ end
144
+
145
+ # Convert a Ruby language value to a SDB value by replacing Ruby nil with the user's chosen string representation of nil.
146
+ # Non-nil values are unaffected by this filter.
147
+ def ruby_to_sdb(value)
148
+ # puts "value #{value} is frozen? #{value.frozen?}"
149
+ # value.nil? ? @nil_rep : ((value.frozen? || !value.is_a?(String)) ? value : value.force_encoding("UTF-8"))
150
+ value.nil? ? @nil_rep : value
151
+ end
152
+
153
+ # Convert a SDB value to a Ruby language value by replacing the user's chosen string representation of nil with Ruby nil.
154
+ # Values are unaffected by this filter unless they match the nil representation exactly.
155
+ def sdb_to_ruby(value)
156
+ value.eql?(@nil_rep) ? nil : value
157
+ end
158
+
159
+ # Convert select and query_with_attributes responses to a Ruby language values by replacing the user's chosen string representation of nil with Ruby nil.
160
+ # (This method affects on a passed response value)
161
+ def select_response_to_ruby(response) #:nodoc:
162
+ response[:items].each_with_index do |item, idx|
163
+ item.each do |key, attributes|
164
+ attributes.each do |name, values|
165
+ values.collect! { |value| sdb_to_ruby(value) }
166
+ end
167
+ end
168
+ end
169
+ response
170
+ end
171
+
172
+ # Create query expression from an array.
173
+ # (similar to ActiveRecord::Base#find using :conditions => ['query', param1, .., paramN])
174
+ #
175
+ def query_expression_from_array(params) #:nodoc:
176
+ return '' if params.blank?
177
+ query = params[0].to_s
178
+ i = 1
179
+ query.gsub(/(\\)?(\?)/) do
180
+ if $1 # if escaped '\?' is found - replace it by '?' without backslash
181
+ "?"
182
+ else # well, if no backslash precedes '?' then replace it by next param from the list
183
+ ret = escape(params[i])
184
+ i+=1
185
+ ret
186
+ end
187
+ end
188
+ end
189
+
190
+ def query_expression_from_hash(hash)
191
+ return '' if hash.blank?
192
+ expression = []
193
+ hash.each do |key, value|
194
+ expression << "#{key}=#{escape(value)}"
195
+ end
196
+ expression.join(' AND ')
197
+ end
198
+
199
+ # Retrieve a list of SDB domains from Amazon.
200
+ #
201
+ # Returns a hash:
202
+ # { :domains => [domain1, ..., domainN],
203
+ # :next_token => string || nil,
204
+ # :box_usage => string,
205
+ # :request_id => string }
206
+ #
207
+ # Example:
208
+ #
209
+ # sdb = Aws::SdbInterface.new
210
+ # sdb.list_domains #=> { :box_usage => "0.0000071759",
211
+ # :request_id => "976709f9-0111-2345-92cb-9ce90acd0982",
212
+ # :domains => ["toys", "dolls"]}
213
+ #
214
+ # If a block is given, this method yields to it. If the block returns true, list_domains will continue looping the request. If the block returns false,
215
+ # list_domains will end.
216
+ #
217
+ # sdb.list_domains(10) do |result| # list by 10 domains per iteration
218
+ # puts result.inspect
219
+ # true
220
+ # end
221
+ #
222
+ # see: http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/SDB_API_ListDomains.html
223
+ #
224
+ def list_domains(max_number_of_domains = nil, next_token = nil )
225
+ request_params = { 'MaxNumberOfDomains' => max_number_of_domains,
226
+ 'NextToken' => next_token }
227
+ link = generate_request("ListDomains", request_params)
228
+ result = request_info(link, QSdbListDomainParser.new)
229
+ # return result if no block given
230
+ return result unless block_given?
231
+ # loop if block if given
232
+ begin
233
+ # the block must return true if it wanna continue
234
+ break unless yield(result) && result[:next_token]
235
+ # make new request
236
+ request_params['NextToken'] = result[:next_token]
237
+ link = generate_request("ListDomains", request_params)
238
+ result = request_info(link, QSdbListDomainParser.new)
239
+ end while true
240
+ rescue Exception
241
+ on_exception
242
+ end
243
+
244
+ # Retrieve a list of SDB domains from Amazon.
245
+ #
246
+ # Returns a hash:
247
+ # { :domains => [domain1, ..., domainN],
248
+ # :next_token => string || nil,
249
+ # :box_usage => string,
250
+ # :request_id => string }
251
+ #
252
+ # Example:
253
+ #
254
+ # sdb = Aws::SdbInterface.new
255
+ # sdb.list_domains #=> { :box_usage => "0.0000071759",
256
+ # :request_id => "976709f9-0111-2345-92cb-9ce90acd0982",
257
+ # :domains => ["toys", "dolls"]}
258
+ #
259
+ # If a block is given, this method yields to it. If the block returns true, list_domains will continue looping the request. If the block returns false,
260
+ # list_domains will end.
261
+ #
262
+ # sdb.list_domains(10) do |result| # list by 10 domains per iteration
263
+ # puts result.inspect
264
+ # true
265
+ # end
266
+ #
267
+ # see: http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/SDB_API_ListDomains.html
268
+ #
269
+ def domain_metadata(domain_name)
270
+ link = generate_request("DomainMetadata", 'DomainName' => domain_name)
271
+ result = request_info(link, QSdbDomainMetadataParser.new)
272
+ return result
273
+ rescue Exception
274
+ on_exception
275
+ end
276
+
277
+
278
+ # Create new SDB domain at Amazon.
279
+ #
280
+ # Returns a hash: { :box_usage, :request_id } on success or an exception on error.
281
+ # (Amazon raises no errors if the domain already exists).
282
+ #
283
+ # Example:
284
+ #
285
+ # sdb = Aws::SdbInterface.new
286
+ # sdb.create_domain('toys') # => { :box_usage => "0.0000071759",
287
+ # :request_id => "976709f9-0111-2345-92cb-9ce90acd0982" }
288
+ #
289
+ # see: http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/SDB_API_CreateDomain.html
290
+ def create_domain(domain_name)
291
+ link = generate_request("CreateDomain",
292
+ 'DomainName' => domain_name)
293
+ request_info(link, QSdbSimpleParser.new)
294
+ rescue Exception
295
+ on_exception
296
+ end
297
+
298
+ # Delete SDB domain at Amazon.
299
+ #
300
+ # Returns a hash: { :box_usage, :request_id } on success or an exception on error.
301
+ # (Amazon raises no errors if the domain does not exist).
302
+ #
303
+ # Example:
304
+ #
305
+ # sdb = Aws::SdbInterface.new
306
+ # sdb.delete_domain('toys') # => { :box_usage => "0.0000071759",
307
+ # :request_id => "976709f9-0111-2345-92cb-9ce90acd0982" }
308
+ #
309
+ # see: http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/SDB_API_DeleteDomain.html
310
+ #
311
+ def delete_domain(domain_name)
312
+ link = generate_request("DeleteDomain",
313
+ 'DomainName' => domain_name)
314
+ request_info(link, QSdbSimpleParser.new)
315
+ rescue Exception
316
+ on_exception
317
+ end
318
+
319
+ # Add/Replace item attributes.
320
+ #
321
+ # Params:
322
+ # domain_name = DomainName
323
+ # item_name = ItemName
324
+ # attributes = {
325
+ # 'nameA' => [valueA1,..., valueAN],
326
+ # ...
327
+ # 'nameZ' => [valueZ1,..., valueZN]
328
+ # }
329
+ # replace = :replace | any other value to skip replacement
330
+ #
331
+ # Returns a hash: { :box_usage, :request_id } on success or an exception on error.
332
+ # (Amazon raises no errors if the attribute was not overridden, as when the :replace param is unset).
333
+ #
334
+ # Example:
335
+ #
336
+ # sdb = Aws::SdbInterface.new
337
+ # sdb.create_domain 'family'
338
+ #
339
+ # attributes = {}
340
+ # # create attributes for Jon and Silvia
341
+ # attributes['Jon'] = %w{ car beer }
342
+ # attributes['Silvia'] = %w{ beetle rolling_pin kids }
343
+ # sdb.put_attributes 'family', 'toys', attributes #=> ok
344
+ # # now: Jon=>[car, beer], Silvia=>[beetle, rolling_pin, kids]
345
+ #
346
+ # # add attributes to Jon
347
+ # attributes.delete('Silvia')
348
+ # attributes['Jon'] = %w{ girls pub }
349
+ # sdb.put_attributes 'family', 'toys', attributes #=> ok
350
+ # # now: Jon=>[car, beer, girls, pub], Silvia=>[beetle, rolling_pin, kids]
351
+ #
352
+ # # replace attributes for Jon and add to a cat (the cat had no attributes before)
353
+ # attributes['Jon'] = %w{ vacuum_cleaner hammer spade }
354
+ # attributes['cat'] = %w{ mouse clew Jons_socks }
355
+ # sdb.put_attributes 'family', 'toys', attributes, :replace #=> ok
356
+ # # now: Jon=>[vacuum_cleaner, hammer, spade], Silvia=>[beetle, rolling_pin, kids], cat=>[mouse, clew, Jons_socks]
357
+ #
358
+ # see: http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/SDB_API_PutAttributes.html
359
+ #
360
+ def put_attributes(domain_name, item_name, attributes, replace = false)
361
+ params = { 'DomainName' => domain_name,
362
+ 'ItemName' => item_name }.merge(pack_attributes(attributes, replace))
363
+ link = generate_request("PutAttributes", params)
364
+ request_info( link, QSdbSimpleParser.new )
365
+ rescue Exception
366
+ on_exception
367
+ end
368
+
369
+ #
370
+ # items is an array of Aws::SdbInterface::Item.new(o.id, o.attributes, true)
371
+ def batch_put_attributes(domain_name, items)
372
+ params = { 'DomainName' => domain_name }
373
+ i = 0
374
+ items.each do |item|
375
+ prefix = "Item." + i.to_s + "."
376
+ params[prefix + "ItemName"] = item.item_name
377
+ params.merge!(pack_attributes(item.attributes, item.replace, prefix))
378
+ i += 1
379
+ end
380
+ link = generate_request("BatchPutAttributes", params)
381
+ request_info( link, QSdbSimpleParser.new )
382
+ rescue Exception
383
+ on_exception
384
+ end
385
+
386
+ # Retrieve SDB item's attribute(s).
387
+ #
388
+ # Returns a hash:
389
+ # { :box_usage => string,
390
+ # :request_id => string,
391
+ # :attributes => { 'nameA' => [valueA1,..., valueAN],
392
+ # ... ,
393
+ # 'nameZ' => [valueZ1,..., valueZN] } }
394
+ #
395
+ # Example:
396
+ # # request all attributes
397
+ # sdb.get_attributes('family', 'toys') # => { :attributes => {"cat" => ["clew", "Jons_socks", "mouse"] },
398
+ # "Silvia" => ["beetle", "rolling_pin", "kids"],
399
+ # "Jon" => ["vacuum_cleaner", "hammer", "spade"]},
400
+ # :box_usage => "0.0000093222",
401
+ # :request_id => "81273d21-000-1111-b3f9-512d91d29ac8" }
402
+ #
403
+ # # request cat's attributes only
404
+ # sdb.get_attributes('family', 'toys', 'cat') # => { :attributes => {"cat" => ["clew", "Jons_socks", "mouse"] },
405
+ # :box_usage => "0.0000093222",
406
+ # :request_id => "81273d21-001-1111-b3f9-512d91d29ac8" }
407
+ #
408
+ # see: http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/SDB_API_GetAttributes.html
409
+ #
410
+ def get_attributes(domain_name, item_name, attribute_name=nil, consistent_read = nil)
411
+ link = generate_request("GetAttributes", 'DomainName' => domain_name,
412
+ 'ItemName' => item_name,
413
+ 'AttributeName' => attribute_name,
414
+ 'ConsistentRead' => consistent_read )
415
+ res = request_info(link, QSdbGetAttributesParser.new)
416
+ res[:attributes].each_value do |values|
417
+ values.collect! { |e| sdb_to_ruby(e) }
418
+ end
419
+ res
420
+ rescue Exception
421
+ on_exception
422
+ end
423
+
424
+ # Delete value, attribute or item.
425
+ #
426
+ # Example:
427
+ # # delete 'vodka' and 'girls' from 'Jon' and 'mice' from 'cat'.
428
+ # sdb.delete_attributes 'family', 'toys', { 'Jon' => ['vodka', 'girls'], 'cat' => ['mice'] }
429
+ #
430
+ # # delete the all the values from attributes (i.e. delete the attributes)
431
+ # sdb.delete_attributes 'family', 'toys', { 'Jon' => [], 'cat' => [] }
432
+ # # or
433
+ # sdb.delete_attributes 'family', 'toys', [ 'Jon', 'cat' ]
434
+ #
435
+ # # delete all the attributes from item 'toys' (i.e. delete the item)
436
+ # sdb.delete_attributes 'family', 'toys'
437
+ #
438
+ # see http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/SDB_API_DeleteAttributes.html
439
+ #
440
+ def delete_attributes(domain_name, item_name, attributes = nil)
441
+ params = { 'DomainName' => domain_name,
442
+ 'ItemName' => item_name }.merge(pack_attributes(attributes))
443
+ link = generate_request("DeleteAttributes", params)
444
+ request_info( link, QSdbSimpleParser.new )
445
+ rescue Exception
446
+ on_exception
447
+ end
448
+
449
+
450
+ # QUERY:
451
+
452
+ # Perform a query on SDB.
453
+ #
454
+ # Returns a hash:
455
+ # { :box_usage => string,
456
+ # :request_id => string,
457
+ # :next_token => string,
458
+ # :items => [ItemName1,..., ItemNameN] }
459
+ #
460
+ # Example:
461
+ #
462
+ # query = "['cat' = 'clew']"
463
+ # sdb.query('family', query) #=> hash of data
464
+ # sdb.query('family', query, 10) #=> hash of data with max of 10 items
465
+ #
466
+ # If a block is given, query will iteratively yield results to it as long as the block continues to return true.
467
+ #
468
+ # # List 10 items per iteration. Don't
469
+ # # forget to escape single quotes and backslashes and wrap all the items in single quotes.
470
+ # query = "['cat'='clew'] union ['dog'='Jon\\'s boot']"
471
+ # sdb.query('family', query, 10) do |result|
472
+ # puts result.inspect
473
+ # true
474
+ # end
475
+ #
476
+ # # Same query using automatic escaping...to use the auto escape, pass the query and its params as an array:
477
+ # query = [ "['cat'=?] union ['dog'=?]", "clew", "Jon's boot" ]
478
+ # sdb.query('family', query)
479
+ #
480
+ # query = [ "['cat'=?] union ['dog'=?] sort 'cat' desc", "clew", "Jon's boot" ]
481
+ # sdb.query('family', query)
482
+ #
483
+ # see: http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/SDB_API_Query.html
484
+ # http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/index.html?SortingData.html
485
+ #
486
+ def query(domain_name, query_expression = nil, max_number_of_items = nil, next_token = nil, consistent_read = nil)
487
+ query_expression = query_expression_from_array(query_expression) if query_expression.is_a?(Array)
488
+ @last_query_expression = query_expression
489
+ #
490
+ request_params = { 'DomainName' => domain_name,
491
+ 'QueryExpression' => query_expression,
492
+ 'MaxNumberOfItems' => max_number_of_items,
493
+ 'NextToken' => next_token,
494
+ 'ConsistentRead' => consistent_read }
495
+ link = generate_request("Query", request_params)
496
+ result = request_info( link, QSdbQueryParser.new )
497
+ # return result if no block given
498
+ return result unless block_given?
499
+ # loop if block if given
500
+ begin
501
+ # the block must return true if it wanna continue
502
+ break unless yield(result) && result[:next_token]
503
+ # make new request
504
+ request_params['NextToken'] = result[:next_token]
505
+ link = generate_request("Query", request_params)
506
+ result = request_info( link, QSdbQueryParser.new )
507
+ end while true
508
+ rescue Exception
509
+ on_exception
510
+ end
511
+
512
+ # Perform a query and fetch specified attributes.
513
+ # If attributes are not specified then fetches the whole list of attributes.
514
+ #
515
+ #
516
+ # Returns a hash:
517
+ # { :box_usage => string,
518
+ # :request_id => string,
519
+ # :next_token => string,
520
+ # :items => [ { ItemName1 => { attribute1 => value1, ... attributeM => valueM } },
521
+ # { ItemName2 => {...}}, ... ]
522
+ #
523
+ # Example:
524
+ #
525
+ # sdb.query_with_attributes(domain, ['hobby', 'country'], "['gender'='female'] intersection ['name' starts-with ''] sort 'name'") #=>
526
+ # { :request_id => "06057228-70d0-4487-89fb-fd9c028580d3",
527
+ # :items =>
528
+ # [ { "035f1ba8-dbd8-11dd-80bd-001bfc466dd7"=>
529
+ # { "hobby" => ["cooking", "flowers", "cats"],
530
+ # "country" => ["Russia"]}},
531
+ # { "0327614a-dbd8-11dd-80bd-001bfc466dd7"=>
532
+ # { "hobby" => ["patchwork", "bundle jumping"],
533
+ # "country" => ["USA"]}}, ... ],
534
+ # :box_usage=>"0.0000504786"}
535
+ #
536
+ # sdb.query_with_attributes(domain, [], "['gender'='female'] intersection ['name' starts-with ''] sort 'name'") #=>
537
+ # { :request_id => "75bb19db-a529-4f69-b86f-5e3800f79a45",
538
+ # :items =>
539
+ # [ { "035f1ba8-dbd8-11dd-80bd-001bfc466dd7"=>
540
+ # { "hobby" => ["cooking", "flowers", "cats"],
541
+ # "name" => ["Mary"],
542
+ # "country" => ["Russia"],
543
+ # "gender" => ["female"],
544
+ # "id" => ["035f1ba8-dbd8-11dd-80bd-001bfc466dd7"]}},
545
+ # { "0327614a-dbd8-11dd-80bd-001bfc466dd7"=>
546
+ # { "hobby" => ["patchwork", "bundle jumping"],
547
+ # "name" => ["Mary"],
548
+ # "country" => ["USA"],
549
+ # "gender" => ["female"],
550
+ # "id" => ["0327614a-dbd8-11dd-80bd-001bfc466dd7"]}}, ... ],
551
+ # :box_usage=>"0.0000506668"}
552
+ #
553
+ # see: http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/index.html?SDB_API_QueryWithAttributes.html
554
+ #
555
+ def query_with_attributes(domain_name, attributes=[], query_expression = nil, max_number_of_items = nil, next_token = nil, consistent_read = nil)
556
+ attributes = attributes.to_a
557
+ query_expression = query_expression_from_array(query_expression) if query_expression.is_a?(Array)
558
+ @last_query_expression = query_expression
559
+ #
560
+ request_params = { 'DomainName' => domain_name,
561
+ 'QueryExpression' => query_expression,
562
+ 'MaxNumberOfItems' => max_number_of_items,
563
+ 'NextToken' => next_token,
564
+ 'ConsistentRead' => consistent_read }
565
+ attributes.each_with_index do |attribute, idx|
566
+ request_params["AttributeName.#{idx+1}"] = attribute
567
+ end
568
+ link = generate_request("QueryWithAttributes", request_params)
569
+ result = select_response_to_ruby(request_info( link, QSdbQueryWithAttributesParser.new ))
570
+ # return result if no block given
571
+ return result unless block_given?
572
+ # loop if block if given
573
+ begin
574
+ # the block must return true if it wanna continue
575
+ break unless yield(result) && result[:next_token]
576
+ # make new request
577
+ request_params['NextToken'] = result[:next_token]
578
+ link = generate_request("QueryWithAttributes", request_params)
579
+ result = select_response_to_ruby(request_info( link, QSdbQueryWithAttributesParser.new ))
580
+ end while true
581
+ rescue Exception
582
+ on_exception
583
+ end
584
+
585
+ # Perform SQL-like select and fetch attributes.
586
+ # Attribute values must be quoted with a single or double quote. If a quote appears within the attribute value, it must be escaped with the same quote symbol as shown in the following example.
587
+ # (Use array to pass select_expression params to avoid manual escaping).
588
+ #
589
+ # sdb.select(["select * from my_domain where gender=?", 'female']) #=>
590
+ # {:request_id =>"8241b843-0fb9-4d66-9100-effae12249ec",
591
+ # :items =>
592
+ # [ { "035f1ba8-dbd8-11dd-80bd-001bfc466dd7"=>
593
+ # {"hobby" => ["cooking", "flowers", "cats"],
594
+ # "name" => ["Mary"],
595
+ # "country" => ["Russia"],
596
+ # "gender" => ["female"],
597
+ # "id" => ["035f1ba8-dbd8-11dd-80bd-001bfc466dd7"]}},
598
+ # { "0327614a-dbd8-11dd-80bd-001bfc466dd7"=>
599
+ # {"hobby" => ["patchwork", "bundle jumping"],
600
+ # "name" => ["Mary"],
601
+ # "country" => ["USA"],
602
+ # "gender" => ["female"],
603
+ # "id" => ["0327614a-dbd8-11dd-80bd-001bfc466dd7"]}}, ... ]
604
+ # :box_usage =>"0.0000506197"}
605
+ #
606
+ # sdb.select('select country, name from my_domain') #=>
607
+ # {:request_id=>"b1600198-c317-413f-a8dc-4e7f864a940a",
608
+ # :items=>
609
+ # [ { "035f1ba8-dbd8-11dd-80bd-001bfc466dd7"=> {"name"=>["Mary"], "country"=>["Russia"]} },
610
+ # { "376d2e00-75b0-11dd-9557-001bfc466dd7"=> {"name"=>["Putin"], "country"=>["Russia"]} },
611
+ # { "0327614a-dbd8-11dd-80bd-001bfc466dd7"=> {"name"=>["Mary"], "country"=>["USA"]} },
612
+ # { "372ebbd4-75b0-11dd-9557-001bfc466dd7"=> {"name"=>["Bush"], "country"=>["USA"]} },
613
+ # { "37a4e552-75b0-11dd-9557-001bfc466dd7"=> {"name"=>["Medvedev"], "country"=>["Russia"]} },
614
+ # { "38278dfe-75b0-11dd-9557-001bfc466dd7"=> {"name"=>["Mary"], "country"=>["Russia"]} },
615
+ # { "37df6c36-75b0-11dd-9557-001bfc466dd7"=> {"name"=>["Mary"], "country"=>["USA"]} } ],
616
+ # :box_usage=>"0.0000777663"}
617
+ #
618
+ # see: http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/index.html?SDB_API_Select.html
619
+ # http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/index.html?UsingSelect.html
620
+ # http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/index.html?SDBLimits.html
621
+ #
622
+ def select(select_expression, next_token = nil, consistent_read = nil)
623
+ select_expression = query_expression_from_array(select_expression) if select_expression.is_a?(Array)
624
+ @last_query_expression = select_expression
625
+ #
626
+ request_params = { 'SelectExpression' => select_expression,
627
+ 'NextToken' => next_token,
628
+ 'ConsistentRead' => consistent_read }
629
+ link = generate_request("Select", request_params)
630
+ result = select_response_to_ruby(request_info( link, QSdbSelectParser.new ))
631
+ return result unless block_given?
632
+ # loop if block if given
633
+ begin
634
+ # the block must return true if it wanna continue
635
+ break unless yield(result) && result[:next_token]
636
+ # make new request
637
+ request_params['NextToken'] = result[:next_token]
638
+ link = generate_request("Select", request_params)
639
+ result = select_response_to_ruby(request_info( link, QSdbSelectParser.new ))
640
+ end while true
641
+ rescue Exception
642
+ on_exception
643
+ end
644
+
645
+ class Item
646
+ attr_accessor :item_name, :attributes, :replace
647
+
648
+ def initialize(item_name, attributes, replace = false)
649
+ @item_name = item_name
650
+ @attributes = attributes
651
+ @replace = replace
652
+ end
653
+ end
654
+
655
+ #-----------------------------------------------------------------
656
+ # PARSERS:
657
+ #-----------------------------------------------------------------
658
+ class QSdbListDomainParser < AwsParser #:nodoc:
659
+ def reset
660
+ @result = { :domains => [] }
661
+ end
662
+
663
+ def tagend(name)
664
+ case name
665
+ when 'NextToken' then
666
+ @result[:next_token] = @text
667
+ when 'DomainName' then
668
+ @result[:domains] << @text
669
+ when 'BoxUsage' then
670
+ @result[:box_usage] = @text
671
+ when 'RequestId' then
672
+ @result[:request_id] = @text
673
+ end
674
+ end
675
+ end
676
+
677
+ class QSdbDomainMetadataParser < AwsParser #:nodoc:
678
+ def reset
679
+ @result = {}
680
+ end
681
+
682
+ def tagend(name)
683
+ case name
684
+ when 'Timestamp' then
685
+ @result[:timestamp] = @text
686
+ when 'ItemCount' then
687
+ @result[:item_count] = @text.to_i
688
+ when 'AttributeValueCount' then
689
+ @result[:attribute_value_count] = @text.to_i
690
+ when 'AttributeNameCount' then
691
+ @result[:attribute_name_acount] = @text.to_i
692
+ when 'ItemNamesSizeBytes' then
693
+ @result[:item_names_size_bytes] = @text.to_i
694
+ when 'AttributeValuesSizeBytes' then
695
+ @result[:attributes_values_size_bytes] = @text.to_i
696
+ when 'AttributeNamesSizeBytes' then
697
+ @result[:attributes_names_size_bytes] = @text.to_i
698
+
699
+ end
700
+ end
701
+ end
702
+
703
+
704
+ class QSdbSimpleParser < AwsParser #:nodoc:
705
+ def reset
706
+ @result = {}
707
+ end
708
+
709
+ def tagend(name)
710
+ case name
711
+ when 'BoxUsage' then
712
+ @result[:box_usage] = @text
713
+ when 'RequestId' then
714
+ @result[:request_id] = @text
715
+ end
716
+ end
717
+ end
718
+
719
+ class QSdbGetAttributesParser < AwsParser #:nodoc:
720
+ def reset
721
+ @last_attribute_name = nil
722
+ @result = { :attributes => {} }
723
+ end
724
+
725
+ def tagend(name)
726
+ case name
727
+ when 'Name' then
728
+ @last_attribute_name = @text
729
+ when 'Value' then
730
+ (@result[:attributes][@last_attribute_name] ||= []) << @text
731
+ when 'BoxUsage' then
732
+ @result[:box_usage] = @text
733
+ when 'RequestId' then
734
+ @result[:request_id] = @text
735
+ end
736
+ end
737
+ end
738
+
739
+ class QSdbQueryParser < AwsParser #:nodoc:
740
+ def reset
741
+ @result = { :items => [] }
742
+ end
743
+
744
+ def tagend(name)
745
+ case name
746
+ when 'ItemName' then
747
+ @result[:items] << @text
748
+ when 'BoxUsage' then
749
+ @result[:box_usage] = @text
750
+ when 'RequestId' then
751
+ @result[:request_id] = @text
752
+ when 'NextToken' then
753
+ @result[:next_token] = @text
754
+ end
755
+ end
756
+ end
757
+
758
+ class QSdbQueryWithAttributesParser < AwsParser #:nodoc:
759
+ def reset
760
+ @result = { :items => [] }
761
+ end
762
+
763
+ def tagend(name)
764
+ case name
765
+ when 'Name'
766
+ case @xmlpath
767
+ when 'QueryWithAttributesResponse/QueryWithAttributesResult/Item'
768
+ @item = @text
769
+ @result[:items] << { @item => {} }
770
+ when 'QueryWithAttributesResponse/QueryWithAttributesResult/Item/Attribute'
771
+ @attribute = @text
772
+ @result[:items].last[@item][@attribute] ||= []
773
+ end
774
+ when 'RequestId' then
775
+ @result[:request_id] = @text
776
+ when 'BoxUsage' then
777
+ @result[:box_usage] = @text
778
+ when 'NextToken' then
779
+ @result[:next_token] = @text
780
+ when 'Value' then
781
+ @result[:items].last[@item][@attribute] << @text
782
+ end
783
+ end
784
+ end
785
+
786
+ class QSdbSelectParser < AwsParser #:nodoc:
787
+ def reset
788
+ @result = { :items => [] }
789
+ end
790
+
791
+ def tagend(name)
792
+ case name
793
+ when 'Name'
794
+ case @xmlpath
795
+ when 'SelectResponse/SelectResult/Item'
796
+ @item = @text
797
+ @result[:items] << { @item => {} }
798
+ when 'SelectResponse/SelectResult/Item/Attribute'
799
+ @attribute = @text
800
+ @result[:items].last[@item][@attribute] ||= []
801
+ end
802
+ when 'RequestId' then
803
+ @result[:request_id] = @text
804
+ when 'BoxUsage' then
805
+ @result[:box_usage] = @text
806
+ when 'NextToken' then
807
+ @result[:next_token] = @text
808
+ when 'Value' then
809
+ @result[:items].last[@item][@attribute] << @text
810
+ end
811
+ end
812
+ end
813
+
814
+ end
815
+
816
+ end