dm-appengine 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.rdoc ADDED
@@ -0,0 +1,14 @@
1
+ == dm-appengine
2
+
3
+ A DataMapper adapter for the Google App Engine Datastore.
4
+
5
+ Currently this is pretty basic. There's no support for Parent entities,
6
+ transactions, Blobs, or Links, for example. Any query supported by the
7
+ Datastore should work. That means the like, regexp, and not operators are not
8
+ supported. Or is only supported for fetching several entities by the Key.
9
+
10
+ == Bugs
11
+
12
+ - DataMapper likes to lazily load properties. The Datastore always sets and
13
+ returns all properties on an entity. If you have lazily loaded properties
14
+ strange things will happen (like properties potentially disappearing).
data/Rakefile ADDED
@@ -0,0 +1,57 @@
1
+ require 'rubygems'
2
+ require 'rake/gempackagetask'
3
+ require 'rubygems/specification'
4
+ require 'date'
5
+ require 'spec/rake/spectask'
6
+
7
+ GEM = "dm-appengine"
8
+ GEM_VERSION = "0.0.1"
9
+ AUTHOR = "Ryan Brown"
10
+ EMAIL = "ribrdb@gmail.com"
11
+ HOMEPAGE = "http://code.google.com/p/appengine-jruby"
12
+ SUMMARY = "A DataMapper adapter for Google App Engine"
13
+
14
+ spec = Gem::Specification.new do |s|
15
+ s.name = GEM
16
+ s.version = GEM_VERSION
17
+ s.platform = Gem::Platform::RUBY
18
+ s.has_rdoc = true
19
+ s.extra_rdoc_files = ["README.rdoc", "LICENSE"]
20
+ s.summary = SUMMARY
21
+ s.description = s.summary
22
+ s.author = AUTHOR
23
+ s.email = EMAIL
24
+ s.homepage = HOMEPAGE
25
+
26
+ s.add_dependency("appengine-apis", ["~> 0.0.3"])
27
+ s.add_dependency(%q<dm-core>, ["~> 0.10.0"])
28
+
29
+ s.require_path = 'lib'
30
+ s.autorequire = GEM
31
+ s.files = %w(LICENSE README.rdoc Rakefile) + Dir.glob("{lib,spec}/**/*")
32
+ end
33
+
34
+ task :default => :spec
35
+
36
+ desc "Run specs"
37
+ Spec::Rake::SpecTask.new do |t|
38
+ t.spec_files = FileList['spec/**/*_spec.rb']
39
+ t.spec_opts = %w(-fs --color)
40
+ end
41
+
42
+
43
+ Rake::GemPackageTask.new(spec) do |pkg|
44
+ pkg.gem_spec = spec
45
+ end
46
+
47
+ desc "install the gem locally"
48
+ task :install => [:package] do
49
+ sh %{sudo gem install pkg/#{GEM}-#{GEM_VERSION}}
50
+ end
51
+
52
+ desc "create a gemspec file"
53
+ task :make_spec do
54
+ File.open("#{GEM}.gemspec", "w") do |file|
55
+ file.puts spec.to_ruby
56
+ end
57
+ end
@@ -0,0 +1,367 @@
1
+ #!/usr/bin/ruby1.8 -w
2
+ #
3
+ # Copyright:: Copyright 2009 Google Inc.
4
+ # Original Author:: Ryan Brown (mailto:ribrdb@google.com)
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+ # Datamapper adapter for Google App Engine
19
+
20
+ require 'rubygems'
21
+ gem 'appengine-apis', '~> 0.0.3'
22
+
23
+ require 'appengine-apis/local_boot'
24
+ require 'appengine-apis/datastore'
25
+ require 'dm-core'
26
+
27
+ module DataMapper
28
+ module Adapters
29
+ class AppEngineAdapter < AbstractAdapter
30
+ Datastore = AppEngine::Datastore
31
+
32
+ def initialize(name, uri_or_options)
33
+ super
34
+ if uri_or_options.kind_of? Hash
35
+ options = uri_or_options
36
+ if options['host'] == 'memory'
37
+ require 'appengine-apis/testing'
38
+ begin
39
+ AppEngine::ApiProxy.get_app_id
40
+ rescue NoMethodError
41
+ AppEngine::Testing::install_test_env
42
+ end
43
+ AppEngine::Testing::install_test_datastore
44
+ end
45
+ end
46
+ @resource_naming_convention = lambda do |value|
47
+ Extlib::Inflection.pluralize(Extlib::Inflection.camelize(value))
48
+ end
49
+ end
50
+
51
+ def kind(model)
52
+ model.storage_name(name)
53
+ end
54
+
55
+ def create(resources)
56
+ created = 0
57
+ entities = []
58
+ resources.each do |resource|
59
+ repository = resource.repository
60
+ model = resource.model
61
+ attributes = resource.attributes
62
+ properties = model.properties(repository.name)
63
+
64
+ kind = self.kind(model)
65
+ keys = model.key(repository.name)
66
+ raise "Multiple keys in #{resource.inspect}" if keys.size > 1
67
+ if keys.size == 1
68
+ key = attributes.delete(keys[0].name)
69
+ key = key.to_s if key
70
+ end
71
+ if key && !(key == 0 || keys[0].serial?)
72
+ entity = Datastore::Entity.new(kind, key)
73
+ else
74
+ entity = Datastore::Entity.new(kind)
75
+ end
76
+
77
+ attributes.each do |name, value|
78
+ property = properties[name]
79
+ value = convert_value(property, value)
80
+ entity.set_property(property.field, value)
81
+ end
82
+ entities << entity
83
+ created += 1
84
+ end
85
+ Datastore.put(entities)
86
+ resources.zip(entities) do |resource, entity|
87
+ key = entity.key
88
+ if identity_field = resource.model.identity_field(name)
89
+ identity_field.set!(resource, key.get_name || key.get_id)
90
+ end
91
+ resource.instance_variable_set :@__entity__, entity
92
+ end
93
+ return created
94
+ end
95
+
96
+ def read(query)
97
+ query = QueryBuilder.new(query, kind(query.model), self)
98
+ query.run
99
+ end
100
+
101
+ def update(attributes, collection)
102
+ attributes = attributes.map do |property, value|
103
+ [property.field, convert_value(property, value)]
104
+ end
105
+ entities = collection.collect do |resource|
106
+ entity = resource.instance_variable_get :@__entity__
107
+ entity.update(attributes)
108
+ end
109
+
110
+ Datastore.put(entities)
111
+ entities.size
112
+ end
113
+
114
+ def convert_value(property, value)
115
+ if property.type == DataMapper::Types::Text && value
116
+ AppEngine::Datastore::Text.new(value)
117
+ else
118
+ value
119
+ end
120
+ end
121
+
122
+ def delete(collection)
123
+ keys = collection.collect do |resource|
124
+ entity = resource.instance_variable_get :@__entity__
125
+ entity.key
126
+ end
127
+ Datastore.delete(keys)
128
+ end
129
+
130
+ class QueryBuilder
131
+ import Datastore::JavaDatastore::FetchOptions
132
+ include Datastore::Query::Constants
133
+ @@OPERATORS = {
134
+ Conditions::EqualToComparison => EQUAL,
135
+ Conditions::GreaterThanComparison => GREATER_THAN,
136
+ Conditions::GreaterThanOrEqualToComparison => GREATER_THAN_OR_EQUAL,
137
+ Conditions::LessThanComparison => LESS_THAN,
138
+ Conditions::LessThanOrEqualToComparison => LESS_THAN_OR_EQUAL,
139
+ }.freeze
140
+
141
+ def initialize(query, kind, adapter)
142
+ @model = query.model
143
+ @kind = kind
144
+ @limit = query.limit
145
+ @offset = query.offset
146
+ @maybe_get = true
147
+ @must_be_get = false
148
+ @keys = []
149
+ @dm_query = query
150
+ @adapter_name = adapter.name
151
+
152
+ @query = Datastore::Query.new(kind)
153
+ parse_order(query.order)
154
+ parse_conditions(query.conditions)
155
+ raise NotImplementedError if @must_be_get && !@maybe_get
156
+ end
157
+
158
+ def property_name(property)
159
+ if property.key?
160
+ '__key__'
161
+ else
162
+ property.field
163
+ end
164
+ end
165
+
166
+ def property_value(property, value)
167
+ if property.key?
168
+ parse_key(property, value)
169
+ else
170
+ value
171
+ end
172
+ end
173
+
174
+ def parse_order(order)
175
+ if order.size == 1 && order[0].direction != :desc
176
+ if order[0].property.key?
177
+ # omit the default key ordering.
178
+ # This lets inequality filters work
179
+ return
180
+ end
181
+ end
182
+ debugger
183
+ order.map do |order|
184
+ if order.direction == :desc
185
+ direction = DESCENDING
186
+ else
187
+ direction = ASCENDING
188
+ end
189
+ name = if order.property.key?
190
+ '__key__'
191
+ else
192
+ property_name(order.property)
193
+ end
194
+ @query.sort(name, direction)
195
+ end
196
+ end
197
+
198
+ def parse_conditions(conditions)
199
+ case conditions
200
+ when Conditions::NotOperation then
201
+ raise NotImplementedError, "NOT operator is not supported"
202
+ when Conditions::AbstractComparison then
203
+ parse_comparison(conditions)
204
+ when Conditions::OrOperation then
205
+ parse_or(conditions)
206
+ when Conditions::AndOperation then
207
+ parse_and(conditions)
208
+ else
209
+ raise ArgumentError, "invalid conditions #{conditions.class}: #{conditions.inspect}"
210
+ end
211
+ end
212
+
213
+ def parse_key(property, value)
214
+ unless property.key?
215
+ raise ArgumentError, "#{property_name(property, true)} is not the key"
216
+ end
217
+ case value
218
+ when Integer, String
219
+ Datastore::Key.from_path(@kind, value)
220
+ when Symbol
221
+ Datastore::Key.from_path(@kind, value.to_s)
222
+ else
223
+ raise ArgumentError "Unsupported key value #{value.inspect} (a #{value.class})"
224
+ end
225
+ end
226
+
227
+ def parse_or(or_op)
228
+ if !@maybe_get
229
+ raise NotImplementedError, "OR only supported with key equality comparisons"
230
+ end
231
+ @must_be_get = true
232
+ or_op.operands.each do |op|
233
+ case op
234
+ when Conditions::OrOperation then
235
+ parse_or(op)
236
+ when Conditions::EqualToComparison then
237
+ key = parse_key(op.property, op.value)
238
+ @keys << key
239
+ when Conditions::InclusionComparison then
240
+ parse_key_inclusion(op)
241
+ else
242
+ raise NotImplementedError, "Unsupported condition #{op.class} inside OR"
243
+ end
244
+ end
245
+ end
246
+
247
+ def parse_key_inclusion(op)
248
+ raise NotImplementedError unless op.value.kind_of? Array
249
+ op.value.each do |value|
250
+ @keys << parse_key(op.property, value)
251
+ end
252
+ end
253
+
254
+ def parse_and(op)
255
+ if @maybe_get && (@found_and || op.operands.size > 1)
256
+ @maybe_get = false
257
+ end
258
+ @found_and = true
259
+ op.operands.each do |conditions|
260
+ parse_conditions(conditions)
261
+ end
262
+ end
263
+
264
+ def parse_comparison(op)
265
+ property = op.property
266
+ value = op.value
267
+ if @maybe_get
268
+ if property.key?
269
+ case op
270
+ when Conditions::EqualToComparison
271
+ @keys << parse_key(property, value)
272
+ when Conditions::InclusionComparison
273
+ parse_key_inclusion(op)
274
+ @must_be_get = true
275
+ return
276
+ else
277
+ @maybe_get = false
278
+ end
279
+ else
280
+ @maybe_get = false
281
+ end
282
+ end
283
+
284
+ if op.kind_of? Conditions::InclusionComparison
285
+ parse_range(op)
286
+ else
287
+ filter_op = @@OPERATORS[op.class]
288
+ if filter_op.nil?
289
+ raise ArgumentError, "#{op.class} is not a supported comparison"
290
+ end
291
+ name = property_name(op.property)
292
+ value = property_value(op.property, op.value)
293
+ @query.filter(name, filter_op, value)
294
+ end
295
+ end
296
+
297
+ def parse_range(op)
298
+ range = op.value
299
+ raise NotImplementedError unless range.is_a? Range
300
+ name = property_name(op.property)
301
+ begin_op = GREATER_THAN_OR_EQUAL
302
+ end_op = if range.exclude_end?
303
+ LESS_THAN
304
+ else
305
+ LESS_THAN_OR_EQUAL
306
+ end
307
+ @query.filter(name, begin_op, range.begin)
308
+ @query.filter(name, end_op, range.end)
309
+ end
310
+
311
+ def is_get?
312
+ @maybe_get && @keys.size > 0
313
+ end
314
+
315
+ def get_entities
316
+ if is_get?
317
+ Datastore.get(@keys)
318
+ else
319
+ begin
320
+ chunk_size = FetchOptions::DEFAULT_CHUNK_SIZE
321
+ options = FetchOptions::Builder.with_chunk_size(
322
+ chunk_size)
323
+ options.limit(@limit) if @limit
324
+ options.offset(@offset) if @offset
325
+ @query.iterator(options).collect {|e| e}
326
+ rescue java.lang.IllegalArgumentException => ex
327
+ raise ArgumentError, ex.message
328
+ end
329
+ end
330
+ end
331
+
332
+ def run
333
+ key_prop = @model.key(@adapter_name)[0].field
334
+ entities = get_entities
335
+ hashes = entities.map do |entity|
336
+ entity_to_hash(key_prop, entity)
337
+ end
338
+ resources = @model.load(hashes, @dm_query)
339
+ resources.zip(entities) do |resource, entity|
340
+ resource.instance_variable_set :@__entity__, entity
341
+ end
342
+ resources
343
+ end
344
+
345
+ def entity_to_hash(key_prop, entity)
346
+ # TODO: This is broken. We should be setting all properties
347
+ return if entity.nil?
348
+ key = entity.get_key
349
+ hash = entity.to_hash
350
+ @dm_query.fields.each do |property|
351
+ if property.key?
352
+ hash[property.field] = key.get_name || key.get_id
353
+ end
354
+ end
355
+ hash
356
+ end
357
+
358
+ def keys
359
+ @keys
360
+ end
361
+ end
362
+ end
363
+
364
+ # required naming scheme
365
+ AppengineAdapter = AppEngineAdapter
366
+ end
367
+ end
@@ -0,0 +1,365 @@
1
+ #!/usr/bin/ruby1.8 -w
2
+ #
3
+ # Copyright:: Copyright 2009 Google Inc.
4
+ # Original Author:: Ryan Brown (mailto:ribrdb@google.com)
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+ # Datamapper adapter for Google App Engine
19
+
20
+ $:.unshift(File.dirname(__FILE__)) unless
21
+ $:.include?(File.dirname(__FILE__)) ||
22
+ $:.include?(File.expand_path(File.dirname(__FILE__)))
23
+
24
+ require 'rubygems'
25
+ gem 'appengine-apis', '~> 0.0.3'
26
+
27
+ require 'appengine-apis/datastore'
28
+ require 'dm-core'
29
+ require 'dm-appengine/appengine_resource'
30
+
31
+ module DataMapper
32
+ module Adapters
33
+ class AppEngineAdapter < AbstractAdapter
34
+ Datastore = AppEngine::Datastore
35
+
36
+ def initialize(name, uri_or_options)
37
+ super
38
+ if uri_or_options.kind_of? Hash
39
+ options = uri_or_options
40
+ if options['host'] == 'memory'
41
+ require 'appengine-apis/testing'
42
+ begin
43
+ AppEngine::ApiProxy.get_app_id
44
+ rescue NoMethodError
45
+ AppEngine::Testing::install_test_env
46
+ end
47
+ AppEngine::Testing::install_test_datastore
48
+ end
49
+ end
50
+ @resource_naming_convention = lambda do |value|
51
+ Extlib::Inflection.pluralize(Extlib::Inflection.camelize(value))
52
+ end
53
+ end
54
+
55
+ def kind(model)
56
+ model.storage_name(name)
57
+ end
58
+
59
+ def create(resources)
60
+ created = 0
61
+ entities = []
62
+ resources.each do |resource|
63
+ attributes = resource.attributes
64
+
65
+ entity = create_entity(resource)
66
+
67
+ attributes.each do |name, value|
68
+ unless name =~ /^__.+__$/
69
+ entity.set_property(name.to_s, value)
70
+ end
71
+ end
72
+ entities << entity
73
+ created += 1
74
+ end
75
+ Datastore.put(entities)
76
+ resources.zip(entities) do |resource, entity|
77
+ key = entity.key
78
+ if identity_field = resource.model.identity_field(name)
79
+ identity_field.set!(resource, key.get_name || key.get_id)
80
+ end
81
+ resource.instance_variable_set :@__entity__, entity
82
+ end
83
+ return created
84
+ end
85
+
86
+ def read(query)
87
+ query = QueryBuilder.new(query, kind(query.model), self)
88
+ query.run
89
+ end
90
+
91
+ def update(attributes, collection)
92
+ attributes = attributes_as_fields(attributes)
93
+ entities = collection.collect do |resource|
94
+ entity = resource.instance_variable_get :@__entity__
95
+ entity.update(attributes)
96
+ end
97
+
98
+ Datastore.put(entities)
99
+ entities.size
100
+ end
101
+
102
+ def delete(collection)
103
+ keys = collection.collect do |resource|
104
+ entity = resource.instance_variable_get :@__entity__
105
+ entity.key
106
+ end
107
+ Datastore.delete(keys)
108
+ end
109
+
110
+ private
111
+
112
+ def create_entity(resource)
113
+ kind = self.kind(resource.model)
114
+ parent, name = resource.appengine_key_components(resource.repository)
115
+ if name.kind_of? Integer
116
+ if name == 0
117
+ name = nil
118
+ else
119
+ raise ArgumentError, 'Numeric ids must be assigned by the Datastore'
120
+ end
121
+ end
122
+ if name
123
+ Datastore::Entity.new(kind, name, parent)
124
+ elsif parent
125
+ Datastore::Entity.new(kind, parent)
126
+ else
127
+ Datastore::Entity.new(kind)
128
+ end
129
+ end
130
+
131
+ class QueryBuilder
132
+ import Datastore::JavaDatastore::FetchOptions
133
+ include Datastore::Query::Constants
134
+ @@OPERATORS = {
135
+ Conditions::EqualToComparison => EQUAL,
136
+ Conditions::GreaterThanComparison => GREATER_THAN,
137
+ Conditions::GreaterThanOrEqualToComparison => GREATER_THAN_OR_EQUAL,
138
+ Conditions::LessThanComparison => LESS_THAN,
139
+ Conditions::LessThanOrEqualToComparison => LESS_THAN_OR_EQUAL,
140
+ }.freeze
141
+
142
+ def initialize(query, kind, adapter)
143
+ @model = query.model
144
+ @kind = kind
145
+ @limit = query.limit
146
+ @offset = query.offset
147
+ @maybe_get = true
148
+ @must_be_get = false
149
+ @keys = []
150
+ @dm_query = query
151
+ @adapter_name = adapter.name
152
+
153
+ @query = Datastore::Query.new(kind)
154
+ parse_order(query.order)
155
+ parse_conditions(query.conditions)
156
+ raise NotImplementedError if @must_be_get && !@maybe_get
157
+ end
158
+
159
+ def property_name(property, qualify=false)
160
+ if qualify
161
+ table_name = property.model.storage_name(name)
162
+ "#{table_name}.#{property.field}"
163
+ else
164
+ property.field
165
+ end
166
+ end
167
+
168
+ def parse_order(order)
169
+ if order.size == 1 && order[0].direction != :desc
170
+ if order[0].property.key?
171
+ # omit the default key ordering.
172
+ # This lets inequality filters work
173
+ return
174
+ end
175
+ end
176
+ order.map do |order|
177
+ if order.direction == :desc
178
+ direction = DESCENDING
179
+ else
180
+ direction = ASCENDING
181
+ end
182
+ name = if order.property.key?
183
+ '__key__'
184
+ else
185
+ property_name(order.property)
186
+ end
187
+ @query.sort(name, direction)
188
+ end
189
+ end
190
+
191
+ def parse_conditions(conditions)
192
+ case conditions
193
+ when Conditions::NotOperation then
194
+ raise NotImplementedError, "NOT operator is not supported"
195
+ when Conditions::AbstractComparison then
196
+ parse_comparison(conditions)
197
+ when Conditions::OrOperation then
198
+ parse_or(conditions)
199
+ when Conditions::AndOperation then
200
+ parse_and(conditions)
201
+ else
202
+ raise ArgumentError, "invalid conditions #{conditions.class}: #{conditions.inspect}"
203
+ end
204
+ end
205
+
206
+ def parse_key(property, value)
207
+ unless property.key?
208
+ raise ArgumentError, "#{property_name(property, true)} is not the key"
209
+ end
210
+ case value
211
+ when Integer, String
212
+ Datastore::Key.from_path(@kind, value)
213
+ when Symbol
214
+ Datastore::Key.from_path(@kind, value.to_s)
215
+ else
216
+ raise ArgumentError "Unsupported key value #{value.inspect} (a #{value.class})"
217
+ end
218
+ end
219
+
220
+ def parse_or(or_op)
221
+ if !@maybe_get
222
+ raise NotImplementedError, "OR only supported with key equality comparisons"
223
+ end
224
+ @must_be_get = true
225
+ or_op.operands.each do |op|
226
+ case op
227
+ when Conditions::OrOperation then
228
+ parse_or(op)
229
+ when Conditions::EqualToComparison then
230
+ key = parse_key(op.property, op.value)
231
+ @keys << key
232
+ when Conditions::InclusionComparison then
233
+ parse_key_inclusion(op)
234
+ else
235
+ raise NotImplementedError, "Unsupported condition #{op.class} inside OR"
236
+ end
237
+ end
238
+ end
239
+
240
+ def parse_key_inclusion(op)
241
+ raise NotImplementedError unless op.value.kind_of? Array
242
+ op.value.each do |value|
243
+ @keys << parse_key(op.property, value)
244
+ end
245
+ end
246
+
247
+ def parse_and(op)
248
+ if @maybe_get && (@found_and || op.operands.size > 1)
249
+ @maybe_get = false
250
+ end
251
+ @found_and = true
252
+ op.operands.each do |conditions|
253
+ parse_conditions(conditions)
254
+ end
255
+ end
256
+
257
+ def parse_comparison(op)
258
+ property = op.property
259
+ value = op.value
260
+ if @maybe_get
261
+ if property.key?
262
+ case op
263
+ when Conditions::EqualToComparison
264
+ @keys << parse_key(property, value)
265
+ when Conditions::InclusionComparison
266
+ parse_key_inclusion(op)
267
+ @must_be_get = true
268
+ return
269
+ else
270
+ @maybe_get = false
271
+ end
272
+ elsif ['__ancestor__', '__parent__'].include? property.field
273
+ if value.java_kind_of? AppEngine::Datastore::Key
274
+ query.ancestor = value
275
+ else
276
+ query.ancestor = value.entity.key
277
+ end
278
+ return
279
+ else
280
+ @maybe_get = false
281
+ end
282
+ end
283
+
284
+ if op.kind_of? Conditions::InclusionComparison
285
+ parse_range(op)
286
+ else
287
+ filter_op = @@OPERATORS[op.class]
288
+ if filter_op.nil?
289
+ raise ArgumentError, "#{op.class} is not a supported comparison"
290
+ end
291
+ @query.filter(property_name(op.property), filter_op, op.value)
292
+ end
293
+ end
294
+
295
+ def parse_range(op)
296
+ range = op.value
297
+ raise NotImplementedError unless range.is_a? Range
298
+ name = property_name(op.property)
299
+ begin_op = GREATER_THAN_OR_EQUAL
300
+ end_op = if range.exclude_end?
301
+ LESS_THAN
302
+ else
303
+ LESS_THAN_OR_EQUAL
304
+ end
305
+ @query.filter(name, begin_op, range.begin)
306
+ @query.filter(name, end_op, range.end)
307
+ end
308
+
309
+ def is_get?
310
+ @maybe_get && @keys.size > 0
311
+ end
312
+
313
+ def get_entities
314
+ if is_get?
315
+ Datastore.get(@keys)
316
+ else
317
+ begin
318
+ chunk_size = FetchOptions::DEFAULT_CHUNK_SIZE
319
+ options = FetchOptions::Builder.with_chunk_size(
320
+ chunk_size)
321
+ options.limit(@limit) if @limit
322
+ options.offset(@offset) if @offset
323
+ @query.iterator(options).collect {|e| e}
324
+ rescue java.lang.IllegalArgumentException => ex
325
+ raise ArgumentError, ex.message
326
+ end
327
+ end
328
+ end
329
+
330
+ def run
331
+ key_prop = @model.key(@adapter_name)[0].field
332
+ get_entities.map do |entity|
333
+ entity_to_model(key_prop, entity)
334
+ end
335
+ end
336
+
337
+ def entity_to_model(key_prop, entity)
338
+ # TODO: This is broken. We should be setting all properties
339
+ return if entity.nil?
340
+ props = entity.to_hash
341
+ props['__entity__'] = entity
342
+ props['__parent__'] = entity.key.parent
343
+
344
+ key = entity.get_key
345
+ id_or_name = key.get_name || key.get_id
346
+
347
+ @dm_query.fields.map do |property|
348
+ if property.key? && property.type == id_or_name.class
349
+ props[property.field] = id_or_name
350
+ break
351
+ end
352
+ end
353
+ props
354
+ end
355
+
356
+ def keys
357
+ @keys
358
+ end
359
+ end
360
+ end
361
+
362
+ # required naming scheme
363
+ AppengineAdapter = AppEngineAdapter
364
+ end
365
+ end
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/ruby1.8 -w
2
+ #
3
+ # Copyright:: Copyright 2009 Google Inc.
4
+ # Original Author:: Ryan Brown (mailto:ribrdb@google.com)
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+ # Custom Resource class for App Engine. Adds optimistic transaction support.
19
+
20
+ module DataMapper
21
+ module AppEngineResource
22
+
23
+ def self.included(mod)
24
+ mod.class_eval do
25
+ include DataMapper::Resource
26
+
27
+ def transaction(retries=3, &block)
28
+ AppEngine::Datastore.transaction(retries, &block)
29
+ end
30
+ end
31
+ end
32
+
33
+ end
34
+ end
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/ruby1.8 -w
2
+ #
3
+ # Copyright:: Copyright 2009 Google Inc.
4
+ # Original Author:: Ryan Brown (mailto:ribrdb@google.com)
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+ # Datamapper adapter for Google App Engine
19
+
20
+ require 'appengine-apis/datastore'
21
+
22
+ module AppEngine::Datastore
23
+ class DMTransaction
24
+
25
+ end
26
+ end
@@ -0,0 +1,100 @@
1
+ #!/usr/bin/ruby1.8 -w
2
+ #
3
+ # Copyright:: Copyright 2009 Google Inc.
4
+ # Original Author:: Ryan Brown (mailto:ribrdb@google.com)
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ require File.dirname(__FILE__) + '/spec_helper'
19
+ require 'dm-core/spec/adapter_shared_spec'
20
+
21
+ class TextTest
22
+ include DataMapper::Resource
23
+
24
+ property :id, Serial
25
+ property :text, Text
26
+ end
27
+
28
+ class FooBar
29
+ include DataMapper::Resource
30
+
31
+ property :id, Serial
32
+ property :string, String
33
+ end
34
+
35
+ describe DataMapper::Adapters::AppEngineAdapter do
36
+ before :all do
37
+ AppEngine::Testing.install_test_env
38
+ AppEngine::Testing.install_test_datastore
39
+ end
40
+
41
+ before :all do
42
+ @adapter = DataMapper.setup(:default, "app_engine://memory")
43
+ @repository = DataMapper.repository(@adapter.name)
44
+
45
+ AppEngine::Testing.install_test_datastore
46
+ end
47
+
48
+ def pending_if(message, boolean = true)
49
+ if boolean
50
+ pending(message) { yield }
51
+ else
52
+ yield
53
+ end
54
+ end
55
+
56
+ it_should_behave_like 'An Adapter'
57
+
58
+ describe 'create' do
59
+ it 'should support Text' do
60
+ a = TextTest.new(:text => "a" * 1024)
61
+ a.save
62
+ end
63
+ end
64
+
65
+ describe 'update' do
66
+ it 'should support Text' do
67
+ a = TextTest.new(:text => "a" * 1024)
68
+ a.save
69
+ a.text = "A" * 1024
70
+ a.save
71
+ a.reload
72
+ a.text.should be_a(AppEngine::Datastore::Text)
73
+ a.text.should be_a(String)
74
+ end
75
+ end
76
+
77
+ describe 'read' do
78
+ it 'should support sorting by id' do
79
+ FooBar.create(:string => 'a')
80
+ FooBar.create(:string => 'c')
81
+ FooBar.create(:string => 'b')
82
+ foobars = FooBar.all(:order => [:id.desc])
83
+ strings = foobars.map {|fb| fb.string}
84
+ strings.should == ['b', 'c', 'a']
85
+ end
86
+
87
+ it 'should support sorting by property' do
88
+ foobars = FooBar.all(:order => [:string])
89
+ strings = foobars.map {|fb| fb.string}
90
+ strings.should == ['a', 'b', 'c']
91
+ end
92
+
93
+ it 'should support filtering by id' do
94
+ a = FooBar.first
95
+ a.string.should == 'a'
96
+ b = FooBar.first(:id.gt => a.id)
97
+ b.string.should == 'c'
98
+ end
99
+ end
100
+ end
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/ruby1.8 -w
2
+ #
3
+ # Copyright:: Copyright 2009 Google Inc.
4
+ # Original Author:: Ryan Brown (mailto:ribrdb@google.com)
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ $TESTING=true
19
+ $:.push File.join(File.dirname(__FILE__), '..', 'lib')
20
+
21
+ require 'rubygems'
22
+ require 'dm-appengine'
23
+
24
+ ADAPTERS = ['default']
25
+ PRIMARY = {'default' => "appengine://memory"}
26
+
27
+ DataMapper::Logger.new(nil, :debug)
28
+ DataMapper.setup(:default, 'appengine://memory')
metadata ADDED
@@ -0,0 +1,82 @@
1
+ --- !ruby/object:Gem::Specification
2
+ required_ruby_version: !ruby/object:Gem::Requirement
3
+ requirements:
4
+ - - '>='
5
+ - !ruby/object:Gem::Version
6
+ version: "0"
7
+ version:
8
+ email: ribrdb@gmail.com
9
+ cert_chain: []
10
+
11
+ summary: A DataMapper adapter for Google App Engine
12
+ post_install_message:
13
+ extra_rdoc_files:
14
+ - README.rdoc
15
+ - LICENSE
16
+ homepage: http://code.google.com/p/appengine-jruby
17
+ signing_key:
18
+ name: dm-appengine
19
+ rdoc_options: []
20
+
21
+ autorequire: dm-appengine
22
+ rubyforge_project:
23
+ executables: []
24
+
25
+ description: A DataMapper adapter for Google App Engine
26
+ specification_version: 2
27
+ default_executable:
28
+ files:
29
+ - LICENSE
30
+ - README.rdoc
31
+ - Rakefile
32
+ - lib/dm-appengine
33
+ - lib/dm-appengine.rb
34
+ - lib/dm-appengine.rb-custom_resource
35
+ - lib/dm-appengine/appengine_resource.rb
36
+ - lib/dm-appengine/transactions.rb
37
+ - spec/dm-appengine_spec.rb
38
+ - spec/spec_helper.rb
39
+ required_rubygems_version: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - '>='
42
+ - !ruby/object:Gem::Version
43
+ version: "0"
44
+ version:
45
+ extensions: []
46
+
47
+ rubygems_version: 1.3.1
48
+ requirements: []
49
+
50
+ authors:
51
+ - Ryan Brown
52
+ date: 2009-05-06 07:00:00 +00:00
53
+ platform: ruby
54
+ test_files: []
55
+
56
+ version: !ruby/object:Gem::Version
57
+ version: 0.0.1
58
+ require_paths:
59
+ - lib
60
+ dependencies:
61
+ - !ruby/object:Gem::Dependency
62
+ version_requirements: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ~>
65
+ - !ruby/object:Gem::Version
66
+ version: 0.0.3
67
+ version:
68
+ type: :runtime
69
+ version_requirement:
70
+ name: appengine-apis
71
+ - !ruby/object:Gem::Dependency
72
+ version_requirements: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ~>
75
+ - !ruby/object:Gem::Version
76
+ version: 0.10.0
77
+ version:
78
+ type: :runtime
79
+ version_requirement:
80
+ name: dm-core
81
+ bindir: bin
82
+ has_rdoc: true