mongo 0.15.1 → 0.16

Sign up to get free protection for your applications and to get access to all the features.
Files changed (63) hide show
  1. data/LICENSE.txt +202 -0
  2. data/README.rdoc +15 -2
  3. data/Rakefile +17 -3
  4. data/bin/autoreconnect.rb +26 -0
  5. data/bin/fail_if_no_c.rb +11 -0
  6. data/lib/mongo.rb +9 -2
  7. data/lib/mongo/admin.rb +1 -1
  8. data/lib/mongo/collection.rb +86 -25
  9. data/lib/mongo/connection.rb +11 -0
  10. data/lib/mongo/constants.rb +15 -0
  11. data/lib/mongo/cursor.rb +176 -36
  12. data/lib/mongo/db.rb +84 -97
  13. data/lib/mongo/errors.rb +7 -1
  14. data/lib/mongo/types/objectid.rb +5 -0
  15. data/lib/mongo/util/byte_buffer.rb +12 -0
  16. data/lib/mongo/util/server_version.rb +69 -0
  17. data/lib/mongo/{message.rb → util/support.rb} +7 -4
  18. data/mongo-ruby-driver.gemspec +9 -86
  19. data/test/test_admin.rb +2 -2
  20. data/test/test_bson.rb +14 -0
  21. data/test/test_byte_buffer.rb +14 -0
  22. data/test/test_chunk.rb +4 -4
  23. data/test/test_collection.rb +107 -17
  24. data/test/test_connection.rb +13 -4
  25. data/test/test_cursor.rb +17 -14
  26. data/test/test_db.rb +7 -7
  27. data/test/test_db_api.rb +31 -19
  28. data/test/test_db_connection.rb +1 -1
  29. data/test/test_grid_store.rb +8 -8
  30. data/test/test_helper.rb +25 -0
  31. data/test/test_objectid.rb +11 -1
  32. data/test/test_slave_connection.rb +37 -0
  33. data/test/test_threading.rb +1 -1
  34. data/test/unit/cursor_test.rb +122 -0
  35. metadata +26 -46
  36. data/bin/mongo_console +0 -21
  37. data/bin/run_test_script +0 -19
  38. data/bin/standard_benchmark +0 -109
  39. data/lib/mongo/message/get_more_message.rb +0 -32
  40. data/lib/mongo/message/insert_message.rb +0 -37
  41. data/lib/mongo/message/kill_cursors_message.rb +0 -31
  42. data/lib/mongo/message/message.rb +0 -80
  43. data/lib/mongo/message/message_header.rb +0 -45
  44. data/lib/mongo/message/msg_message.rb +0 -29
  45. data/lib/mongo/message/opcodes.rb +0 -27
  46. data/lib/mongo/message/query_message.rb +0 -69
  47. data/lib/mongo/message/remove_message.rb +0 -37
  48. data/lib/mongo/message/update_message.rb +0 -38
  49. data/lib/mongo/query.rb +0 -118
  50. data/test/mongo-qa/admin +0 -26
  51. data/test/mongo-qa/capped +0 -22
  52. data/test/mongo-qa/count1 +0 -18
  53. data/test/mongo-qa/dbs +0 -22
  54. data/test/mongo-qa/find +0 -10
  55. data/test/mongo-qa/find1 +0 -15
  56. data/test/mongo-qa/gridfs_in +0 -16
  57. data/test/mongo-qa/gridfs_out +0 -17
  58. data/test/mongo-qa/indices +0 -49
  59. data/test/mongo-qa/remove +0 -25
  60. data/test/mongo-qa/stress1 +0 -35
  61. data/test/mongo-qa/test1 +0 -11
  62. data/test/mongo-qa/update +0 -18
  63. data/test/test_message.rb +0 -35
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -12,7 +12,7 @@ many more.
12
12
  db = Connection.new('localhost').db('sample-db')
13
13
  coll = db.collection('test')
14
14
 
15
- coll.clear
15
+ coll.remove
16
16
  3.times { |i| coll.insert({'a' => i+1}) }
17
17
  puts "There are #{coll.count()} records. Here they are:"
18
18
  coll.find().each { |doc| puts doc.inspect }
@@ -82,7 +82,7 @@ Here is some simple example code:
82
82
  db = Connection.new.db('my-db-name')
83
83
  things = db.collection('things')
84
84
 
85
- things.clear
85
+ things.remove
86
86
  things.insert('a' => 42)
87
87
  things.insert('a' => 99, 'b' => Time.now)
88
88
  puts things.count # => 2
@@ -118,6 +118,10 @@ Example code:
118
118
 
119
119
  = Notes
120
120
 
121
+ == Thread Safety
122
+
123
+ mongo-ruby-driver is thread safe.
124
+
121
125
  == Using with Phusion Passenger
122
126
 
123
127
  When passenger is in smart spawning mode you need to be sure that child
@@ -254,6 +258,12 @@ If you have the source code, you can run the tests.
254
258
 
255
259
  $ rake test
256
260
 
261
+ The tests now require shoulda and mocha. You can install these gems as
262
+ follows:
263
+
264
+ $ gem install shoulda
265
+ $ gem install mocha
266
+
257
267
  The tests assume that the Mongo database is running on the default port. You
258
268
  can override the default host (localhost) and port (Connection::DEFAULT_PORT) by
259
269
  using the environment variables MONGO_RUBY_DRIVER_HOST and
@@ -326,6 +336,7 @@ Durran Jordan, durran@gmail.com
326
336
 
327
337
  Cyril Mougel, cyril.mougel@gmail.com
328
338
  * Initial logging support
339
+ * Test case
329
340
 
330
341
  Jack Chen, chendo on github
331
342
  * Test case + fix for deserializing pre-epoch Time instances
@@ -342,6 +353,8 @@ Paulo Ahahgon, pahagon on github
342
353
  Les Hill, leshill on github
343
354
  * OrderedHash#each returns self
344
355
 
356
+ Sean Cribbs, seancribbs on github
357
+ * Modify standard_benchmark to allow profiling
345
358
 
346
359
  = License
347
360
 
data/Rakefile CHANGED
@@ -14,9 +14,23 @@ include Config
14
14
  gem_command = "gem"
15
15
  gem_command = "gem1.9" if $0.match(/1\.9$/) # use gem1.9 if we used rake1.9
16
16
 
17
- # NOTE: some of the tests assume Mongo is running
18
- Rake::TestTask.new do |t|
19
- t.test_files = FileList['test/test*.rb']
17
+ # NOTE: the functional tests assume MongoDB is running.
18
+ desc "Test the MongoDB Ruby driver."
19
+ task :test do
20
+ Rake::Task['test:unit'].invoke
21
+ Rake::Task['test:functional'].invoke
22
+ end
23
+
24
+ namespace :test do
25
+ Rake::TestTask.new(:unit) do |t|
26
+ t.test_files = FileList['test/unit/*_test.rb']
27
+ t.verbose = true
28
+ end
29
+
30
+ Rake::TestTask.new(:functional) do |t|
31
+ t.test_files = FileList['test/test*.rb']
32
+ t.verbose = true
33
+ end
20
34
  end
21
35
 
22
36
  desc "Generate documentation"
@@ -0,0 +1,26 @@
1
+ $LOAD_PATH[0,0] = File.join(File.dirname(__FILE__), '..', 'lib')
2
+ require 'mongo'
3
+
4
+ db = Mongo::Connection.new({:left => ["localhost", 27017], :right => ["localhost", 27018]}, nil, :auto_reconnect => true).db("ruby_test")
5
+
6
+ db['test'].clear
7
+ 10.times do |i|
8
+ db['test'].save("x" => i)
9
+ end
10
+
11
+ while true do
12
+ begin
13
+ exit() if not db['test'].count() == 10
14
+
15
+ x = 0
16
+ db['test'].find().each do |doc|
17
+ x += doc['x']
18
+ end
19
+ exit() if not x == 45
20
+ print "."
21
+ STDOUT.flush
22
+ sleep 1
23
+ rescue
24
+ sleep 1
25
+ end
26
+ end
@@ -0,0 +1,11 @@
1
+ # Fail if the C extension module isn't installed.
2
+ #
3
+ # Only really intended to be used by internal build scripts.
4
+
5
+ require 'rubygems'
6
+ require 'mongo'
7
+ begin
8
+ require 'mongo_ext/cbson'
9
+ rescue LoadError
10
+ Process.exit 1
11
+ end
@@ -1,11 +1,18 @@
1
+ $LOAD_PATH << File.join(File.dirname(__FILE__), '..', 'lib')
2
+
1
3
  require 'mongo/types/binary'
4
+ require 'mongo/types/code'
2
5
  require 'mongo/types/dbref'
3
6
  require 'mongo/types/objectid'
4
7
  require 'mongo/types/regexp_of_holding'
5
8
 
9
+ require 'mongo/util/support'
10
+ require 'mongo/util/conversions'
11
+ require 'mongo/util/server_version'
12
+
6
13
  require 'mongo/errors'
14
+ require 'mongo/constants'
7
15
  require 'mongo/connection'
8
- require 'mongo/message'
9
16
  require 'mongo/db'
10
17
  require 'mongo/cursor'
11
18
  require 'mongo/collection'
@@ -15,5 +22,5 @@ module Mongo
15
22
  ASCENDING = 1
16
23
  DESCENDING = -1
17
24
 
18
- VERSION = "0.15.1"
25
+ VERSION = "0.16"
19
26
  end
@@ -64,7 +64,7 @@ module Mongo
64
64
  # Return an array contining current profiling information from the
65
65
  # database.
66
66
  def profiling_info
67
- @db.query(Collection.new(@db, DB::SYSTEM_PROFILE_COLLECTION), Query.new({})).to_a
67
+ Cursor.new(Collection.new(@db, DB::SYSTEM_PROFILE_COLLECTION), :selector => {}).to_a
68
68
  end
69
69
 
70
70
  # Validate a named collection by raising an exception if there is a
@@ -14,16 +14,14 @@
14
14
  # limitations under the License.
15
15
  # ++
16
16
 
17
- require 'mongo/query'
18
-
19
17
  module Mongo
20
18
 
21
19
  # A named collection of records in a database.
22
20
  class Collection
23
21
 
24
- attr_reader :db, :name, :hint
22
+ attr_reader :db, :name, :pk_factory, :hint
25
23
 
26
- def initialize(db, name)
24
+ def initialize(db, name, pk_factory=nil)
27
25
  case name
28
26
  when Symbol, String
29
27
  else
@@ -42,7 +40,8 @@ module Mongo
42
40
  raise InvalidName, "collection names must not start or end with '.'"
43
41
  end
44
42
 
45
- @db, @name = db, name
43
+ @db, @name = db, name
44
+ @pk_factory = pk_factory || ObjectID
46
45
  @hint = nil
47
46
  end
48
47
 
@@ -100,6 +99,13 @@ module Mongo
100
99
  # objects missed, which were preset at both the start and
101
100
  # end of the query's execution. For details see
102
101
  # http://www.mongodb.org/display/DOCS/How+to+do+Snapshotting+in+the+Mongo+Database
102
+ # :timeout :: When +true+ (default), the returned cursor will be subject to
103
+ # the normal cursor timeout behavior of the mongod process.
104
+ # When +false+, the returned cursor will never timeout. Note
105
+ # that disabling timeout will only work when #find is invoked
106
+ # with a block. This is to prevent any inadvertant failure to
107
+ # close the cursor, as the cursor is explicitly closed when
108
+ # block code finishes.
103
109
  def find(selector={}, options={})
104
110
  fields = options.delete(:fields)
105
111
  fields = ["_id"] if fields && fields.empty?
@@ -112,6 +118,10 @@ module Mongo
112
118
  sort = options.delete(:sort)
113
119
  hint = options.delete(:hint)
114
120
  snapshot = options.delete(:snapshot)
121
+ if options[:timeout] == false && !block_given?
122
+ raise ArgumentError, "Timeout can be set to false only when #find is invoked with a block."
123
+ end
124
+ timeout = block_given? ? (options.delete(:timeout) || true) : true
115
125
  if hint
116
126
  hint = normalize_hint_fields(hint)
117
127
  else
@@ -119,7 +129,8 @@ module Mongo
119
129
  end
120
130
  raise RuntimeError, "Unknown options [#{options.inspect}]" unless options.empty?
121
131
 
122
- cursor = @db.query(self, Query.new(selector, fields, skip, limit, sort, hint, snapshot))
132
+ cursor = Cursor.new(self, :selector => selector, :fields => fields, :skip => skip, :limit => limit,
133
+ :order => sort, :hint => hint, :snapshot => snapshot, :timeout => timeout)
123
134
  if block_given?
124
135
  yield cursor
125
136
  cursor.close()
@@ -189,25 +200,41 @@ module Mongo
189
200
  # will be raised on an error. Checking for safety requires an extra
190
201
  # round-trip to the database
191
202
  def insert(doc_or_docs, options={})
192
- doc_or_docs = [doc_or_docs] if !doc_or_docs.is_a?(Array)
193
- res = @db.insert_into_db(@name, doc_or_docs)
203
+ doc_or_docs = [doc_or_docs] unless doc_or_docs.is_a?(Array)
204
+ doc_or_docs.collect! { |doc| @pk_factory.create_pk(doc) }
205
+ result = insert_documents(doc_or_docs)
194
206
  if options.delete(:safe)
195
207
  error = @db.error
196
208
  if error
197
209
  raise OperationFailure, error
198
210
  end
199
211
  end
200
- res.size > 1 ? res : res.first
212
+ result.size > 1 ? result : result.first
201
213
  end
202
214
  alias_method :<<, :insert
203
215
 
204
- # Remove the records that match +selector+.
216
+ # Remove all records from this collection.
217
+ # If +selector+ is specified, only matching documents will be removed.
218
+ #
219
+ # Remove all records from the collection:
220
+ # @collection.remove
221
+ # @collection.remove({})
222
+ #
223
+ # Remove only records that have expired:
224
+ # @collection.remove({:expire => {'$lte' => Time.now}})
205
225
  def remove(selector={})
206
- @db.remove_from_db(@name, selector)
226
+ message = ByteBuffer.new
227
+ message.put_int(0)
228
+ BSON.serialize_cstr(message, "#{@db.name}.#{@name}")
229
+ message.put_int(0)
230
+ message.put_array(BSON.new.serialize(selector, false).to_a)
231
+ @db.send_message_with_operation(Mongo::Constants::OP_DELETE, message)
207
232
  end
208
233
 
209
234
  # Remove all records.
235
+ # DEPRECATED: please use Collection#remove instead.
210
236
  def clear
237
+ warn "Collection#clear is deprecated. Please use Collection#remove instead."
211
238
  remove({})
212
239
  end
213
240
 
@@ -225,19 +252,16 @@ module Mongo
225
252
  # will be raised on an error. Checking for safety requires an extra
226
253
  # round-trip to the database
227
254
  def update(spec, document, options={})
228
- upsert = options.delete(:upsert)
229
- safe = options.delete(:safe)
230
-
231
- if upsert
232
- @db.repsert_in_db(@name, spec, document)
233
- else
234
- @db.replace_in_db(@name, spec, document)
235
- end
236
- if safe
237
- error = @db.error
238
- if error
239
- raise OperationFailure, error
240
- end
255
+ message = ByteBuffer.new
256
+ message.put_int(0)
257
+ BSON.serialize_cstr(message, "#{@db.name}.#{@name}")
258
+ message.put_int(options[:upsert] ? 1 : 0) # 1 if a repsert operation (upsert)
259
+ message.put_array(BSON.new.serialize(spec, false).to_a)
260
+ message.put_array(BSON.new.serialize(document, false).to_a)
261
+ @db.send_message_with_operation(Mongo::Constants::OP_UPDATE, message)
262
+
263
+ if options[:safe] && error=@db.error
264
+ raise OperationFailure, error
241
265
  end
242
266
  end
243
267
 
@@ -248,7 +272,20 @@ module Mongo
248
272
  # +unique+ is an optional boolean indicating whether this index
249
273
  # should enforce a uniqueness constraint.
250
274
  def create_index(field_or_spec, unique=false)
251
- @db.create_index(@name, field_or_spec, unique)
275
+ field_h = OrderedHash.new
276
+ if field_or_spec.is_a?(String) || field_or_spec.is_a?(Symbol)
277
+ field_h[field_or_spec.to_s] = 1
278
+ else
279
+ field_or_spec.each { |f| field_h[f[0].to_s] = f[1] }
280
+ end
281
+ name = generate_index_names(field_h)
282
+ sel = {
283
+ :name => name,
284
+ :ns => "#{@db.name}.#{@name}",
285
+ :key => field_h,
286
+ :unique => unique }
287
+ insert_documents([sel], Mongo::DB::SYSTEM_INDEX_COLLECTION, false)
288
+ name
252
289
  end
253
290
 
254
291
  # Drop index +name+.
@@ -395,6 +432,8 @@ EOS
395
432
  find().count()
396
433
  end
397
434
 
435
+ alias :size :count
436
+
398
437
  protected
399
438
 
400
439
  def normalize_hint_fields(hint)
@@ -411,5 +450,27 @@ EOS
411
450
  h
412
451
  end
413
452
  end
453
+
454
+ private
455
+
456
+ # Sends an Mongo::Constants::OP_INSERT message to the database.
457
+ # Takes an array of +documents+, an optional +collection_name+, and a
458
+ # +check_keys+ setting.
459
+ def insert_documents(documents, collection_name=@name, check_keys=true)
460
+ message = ByteBuffer.new
461
+ message.put_int(0)
462
+ BSON.serialize_cstr(message, "#{@db.name}.#{collection_name}")
463
+ documents.each { |doc| message.put_array(BSON.new.serialize(doc, check_keys).to_a) }
464
+ @db.send_message_with_operation(Mongo::Constants::OP_INSERT, message)
465
+ documents.collect { |o| o[:_id] || o['_id'] }
466
+ end
467
+
468
+ def generate_index_names(spec)
469
+ indexes = []
470
+ spec.each_pair do |field, direction|
471
+ indexes.push("#{field}_#{direction}")
472
+ end
473
+ indexes.join("_")
474
+ end
414
475
  end
415
476
  end