appoxy-aws 1.11.14 → 1.11.15

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