Skip to content
Browse files

RUBY-494 cleaning up all references to Connection, ReplSetConnection,…

… and ShardedConnection
  • Loading branch information...
1 parent ec4d139 commit 1aa753e4c0d26dff3ff81b1011cdb369964f21ec @brandonblack brandonblack committed Nov 1, 2012
Showing with 989 additions and 1,018 deletions.
  1. +12 −12 README.md
  2. +4 −4 Rakefile
  3. +2 −3 bench/batch_size_benchmark
  4. +6 −6 bench/exp_series.rb
  5. +1 −1 bench/gridstore_benchmark
  6. +2 −3 bench/profile_array.rb
  7. +2 −2 bench/standard_benchmark
  8. +2 −2 bin/mongo_console
  9. +4 −4 examples/admin.rb
  10. +2 −2 examples/capped.rb
  11. +2 −2 examples/cursor.rb
  12. +2 −2 examples/gridfs.rb
  13. +2 −2 examples/index_test.rb
  14. +2 −2 examples/info.rb
  15. +2 −2 examples/queries.rb
  16. +1 −1 examples/replica_set.rb
  17. +2 −2 examples/simple.rb
  18. +2 −2 examples/strict.rb
  19. +2 −2 examples/types.rb
  20. +1 −1 examples/web/thin/load.rb
  21. +2 −2 examples/web/unicorn/load.rb
  22. +3 −3 examples/web/unicorn/unicorn.rb.template
  23. +27 −27 lib/mongo/client.rb
  24. +46 −49 lib/mongo/collection.rb
  25. +2 −6 lib/mongo/cursor.rb
  26. +9 −9 lib/mongo/db.rb
  27. +2 −2 lib/mongo/gridfs/grid.rb
  28. +2 −2 lib/mongo/gridfs/grid_file_system.rb
  29. +4 −4 lib/mongo/networking.rb
  30. +19 −19 lib/mongo/repl_set_client.rb
  31. +5 −5 lib/mongo/sharded_client.rb
  32. +15 −15 lib/mongo/util/node.rb
  33. +9 −9 lib/mongo/util/pool.rb
  34. +18 −17 lib/mongo/util/pool_manager.rb
  35. +12 −12 lib/mongo/util/uri_parser.rb
  36. +2 −2 test/auxillary/{1.4_features.rb → 1.4_feature_test.rb}
  37. +6 −6 test/auxillary/authentication_test.rb
  38. +2 −2 test/auxillary/autoreconnect_test.rb
  39. +4 −4 test/auxillary/fork_test.rb
  40. +11 −11 test/auxillary/repl_set_auth_test.rb
  41. +6 −6 test/auxillary/slave_connection_test.rb
  42. +6 −6 test/auxillary/threaded_authentication_test.rb
  43. +7 −7 test/functional/collection_test.rb
  44. +71 −85 test/functional/connection_test.rb
  45. +3 −3 test/functional/db_api_test.rb
  46. +2 −2 test/functional/db_connection_test.rb
  47. +12 −12 test/functional/db_test.rb
  48. +58 −58 test/replica_set/basic_test.rb
  49. +8 −8 test/replica_set/complex_connect_test.rb
  50. +78 −78 test/replica_set/connect_test.rb
  51. +5 −5 test/replica_set/count_test.rb
  52. +12 −12 test/replica_set/cursor_test.rb
  53. +3 −3 test/replica_set/insert_test.rb
  54. +28 −28 test/replica_set/old/basic_test.rb
  55. +8 −8 test/replica_set/old/complex_connect_test.rb
  56. +2 −2 test/replica_set/old/complex_read_preference_test.rb
  57. +76 −76 test/replica_set/old/connect_test.rb
  58. +5 −5 test/replica_set/old/count_test.rb
  59. +13 −13 test/replica_set/old/cursor_test.rb
  60. +3 −3 test/replica_set/old/insert_test.rb
  61. +3 −3 test/replica_set/old/pooled_insert_test.rb
  62. +3 −3 test/replica_set/old/query_test.rb
  63. +11 −11 test/replica_set/old/read_preference_test.rb
  64. +51 −51 test/replica_set/old/refresh_test.rb
  65. +8 −8 test/replica_set/old/refresh_with_threads_test.rb
  66. +5 −5 test/replica_set/old/replication_ack_test.rb
  67. +3 −3 test/replica_set/query_test.rb
  68. +52 −52 test/replica_set/refresh_test.rb
  69. +5 −5 test/replica_set/replication_ack_test.rb
  70. +24 −26 test/sharded_cluster/basic_test.rb
  71. +2 −2 test/test_helper.rb
  72. +9 −9 test/tools/mongo_config.rb
  73. +2 −2 test/tools/mongo_config_test.rb
  74. +29 −29 test/unit/collection_test.rb
  75. +52 −52 test/unit/connection_test.rb
  76. +5 −5 test/unit/cursor_test.rb
  77. +7 −7 test/unit/db_test.rb
  78. +10 −10 test/unit/grid_test.rb
  79. +7 −7 test/unit/node_test.rb
  80. +1 −1 test/unit/pool_manager_test.rb
  81. +20 −25 test/unit/read_test.rb
  82. +19 −19 test/unit/{safe_test.rb → write_concern_test.rb}
View
24 README.md
@@ -44,9 +44,9 @@ Here's a quick code sample. Again, see the [MongoDB Ruby Tutorial](https://githu
require 'rubygems'
require 'mongo'
- @conn = Mongo::Connection.new('localhost', 27017, :safe => true)
- @db = @conn['sample-db']
- @coll = @db['test']
+ @client = Mongo::Client.new('localhost', 27017, :safe => true)
+ @db = @client['sample-db']
+ @coll = @db['test']
@coll.remove
3.times do |i|
@@ -164,7 +164,7 @@ timeout for waiting for old connections to be released to the pool.
To set up a pooled connection to a single MongoDB instance:
- @conn = Connection.new("localhost", 27017, :safe => true, :pool_size => 5, :timeout => 5)
+ @client = Client.new("localhost", 27017, :safe => true, :pool_size => 5, :timeout => 5)
Though the pooling architecture will undoubtedly evolve, it currently owes much credit
to the connection pooling implementations in ActiveRecord and PyMongo.
@@ -177,13 +177,13 @@ of v1.3.0, the Ruby driver detects forking and reconnects automatically.
## Environment variable `MONGODB_URI`
-`Mongo::Connection.from_uri`, `Mongo::Connection.new` and `Mongo::ReplSetConnection.new` will use <code>ENV["MONGODB_URI"]</code> if no other args are provided.
+`Mongo::Client.from_uri`, `Mongo::Client.new` and `Mongo::ReplSetClient.new` will use <code>ENV["MONGODB_URI"]</code> if no other args are provided.
The URI must fit this specification:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
-If the type of connection (direct or replica set) should be determined entirely from <code>ENV["MONGODB_URI"]</code>, you may want to use `Mongo::Connection.from_uri` because it will return either `Mongo::Connection` or a `Mongo::ReplSetConnection` depending on how many hosts are specified. Trying to use `Mongo::Connection.new` with multiple hosts in <code>ENV["MONGODB_URI"]</code> will raise an exception.
+If the type of connection (direct or replica set) should be determined entirely from <code>ENV["MONGODB_URI"]</code>, you may want to use `Mongo::Client.from_uri` because it will return either `Mongo::Client` or a `Mongo::ReplSetClient` depending on how many hosts are specified. Trying to use `Mongo::Client.new` with multiple hosts in <code>ENV["MONGODB_URI"]</code> will raise an exception.
## String Encoding
@@ -213,9 +213,9 @@ generate _id values. If you want to control _id values or even their types,
using a PK factory lets you do so.
You can tell the Ruby Mongo driver how to create primary keys by passing in
-the :pk option to the Connection#db method.
+the :pk option to the Client#db method.
- db = Mongo::Connection.new('localhost', 27017, :safe => true).db('dbname', :pk => MyPKFactory.new)
+ db = Mongo::Client.new('localhost', 27017, :safe => true).db('dbname', :pk => MyPKFactory.new)
A primary key factory object must respond to :create_pk, which should
take a hash and return a hash which merges the original hash with any
@@ -268,7 +268,7 @@ completely harmless; strict mode is a programmer convenience only.
To turn on strict mode, either pass in :strict => true when obtaining a DB
object or call the `:strict=` method:
- db = Connection.new('localhost', 27017, :safe => true).db('dbname', :strict => true)
+ db = Client.new('localhost', 27017, :safe => true).db('dbname', :strict => true)
# I'm feeling lax
db.strict = false
# No, I'm not!
@@ -291,10 +291,10 @@ Notes:
## Socket timeouts
The Ruby driver support timeouts on socket read operations. To enable them, set the
-`:op_timeout` option when you create a `Mongo::Connection` object.
+`:op_timeout` option when you create a `Mongo::Client` object.
If implementing higher-level timeouts, using tools like `Rack::Timeout`, it's very important
-to call `Mongo::Connection#close` to prevent the subsequent operation from receiving the previous
+to call `Mongo::Client#close` to prevent the subsequent operation from receiving the previous
request.
### Test-Unit, Shoulda, and Mocha
@@ -306,7 +306,7 @@ Running the test suite requires test-unit, shoulda, and mocha. You can install
$ gem install mocha
The tests assume that the Mongo database is running on the default port. You
-can override the default host (localhost) and port (Connection::DEFAULT_PORT) by
+can override the default host (localhost) and port (Client::DEFAULT_PORT) by
using the environment variables MONGO_RUBY_DRIVER_HOST and
MONGO_RUBY_DRIVER_PORT.
View
8 Rakefile
@@ -150,10 +150,10 @@ namespace :test do
task :drop_databases => :path do |t|
puts "Dropping test databases..."
require 'mongo'
- con = Mongo::Connection.new(ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost',
- ENV['MONGO_RUBY_DRIVER_PORT'] || Mongo::Connection::DEFAULT_PORT, :safe => true)
- con.database_names.each do |name|
- con.drop_database(name) if name =~ /^ruby-test/
+ client = Mongo::Client.new(ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost',
+ ENV['MONGO_RUBY_DRIVER_PORT'] || Mongo::Client::DEFAULT_PORT, :safe => true)
+ client.database_names.each do |name|
+ client.drop_database(name) if name =~ /^ruby-test/
end
end
end
View
5 bench/batch_size_benchmark
@@ -28,9 +28,8 @@ large = {
}
-con = Mongo::Connection.new
-
-db = con['benchmark']
+client = Mongo::Client.new
+db = client['benchmark']
col = db['bigdocs']
col.remove()
View
12 bench/exp_series.rb
@@ -178,9 +178,9 @@ def test_multi_doc
### Mac OS X - sysctl -a hw
def setup_test_set
- @conn = Mongo::Connection.new
- @conn.drop_database($db_name)
- @db = @conn.db($db_name)
+ @client = Mongo::Client.new
+ @client.drop_database($db_name)
+ @db = @client.db($db_name)
@coll = @db.collection($collection_name)
@coll.remove
@results = []
@@ -195,7 +195,7 @@ def teardown_test_set
File.open($file_name, 'a'){|f|
f.puts(@results.to_json.gsub(/\[/, "").gsub(/}[\],]/, "},\n")) if @results != []
}
- @conn.drop_database($db_name)
+ @client.drop_database($db_name)
end
def estimate_iterations(db, coll, doc, setup, teardown)
@@ -225,9 +225,9 @@ def measure_iterations(db, coll, doc, setup, teardown, iterations)
end
def valuate(db, coll, doc, setup, teardown)
- @conn.drop_database($db_name) # hack to reduce paging
+ @client.drop_database($db_name) # hack to reduce paging
iterations, etime = estimate_iterations(db, coll, doc, setup, teardown) { yield }
- @conn.drop_database($db_name) # hack to reduce paging
+ @client.drop_database($db_name) # hack to reduce paging
utime, rtime = measure_iterations(db, coll, doc, setup, teardown, iterations) { yield }
return [iterations, utime, rtime, etime]
end
View
2 bench/gridstore_benchmark
@@ -4,7 +4,7 @@ require 'mongo'
include Mongo
-db = Connection.new['benchmark-gridfs']
+db = Client.new['benchmark-gridfs']
sample_data = File.open(File.join(File.dirname(__FILE__), 'sample_file.pdf'), 'r').read
db['fs.files'].remove
db['fs.chunks'].remove
View
5 bench/profile_array.rb
@@ -73,9 +73,8 @@ def ruby_prof(iterations)
# system(cmd)
#end
-conn = Mongo::Connection.new
-
-db = conn['benchmark']
+client = Mongo::Client.new
+db = client['benchmark']
coll = db['profile']
coll.remove
View
4 bench/standard_benchmark
@@ -84,9 +84,9 @@ def benchmark(str, n, coll_name, data, create_index=false, verbosity=true)
end
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
-port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
+port = ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
-connection = Connection.new(host, port)
+connection = Client.new(host, port)
connection.drop_database("benchmark")
@db = connection.db('benchmark')
View
4 bin/mongo_console
@@ -10,11 +10,11 @@ require 'mongo'
include Mongo
host = org_argv[0] || ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
-port = org_argv[1] || ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
+port = org_argv[1] || ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
dbnm = org_argv[2] || ENV['MONGO_RUBY_DRIVER_DB'] || 'ruby-mongo-console'
puts "Connecting to #{host}:#{port} (CONN) on with database #{dbnm} (DB)"
-CONN = Connection.new(host, port, :safe => true)
+CONN = Client.new(host, port, :safe => true)
DB = CONN.db(dbnm)
puts "Starting IRB session..."
View
8 examples/admin.rb
@@ -6,17 +6,17 @@
include Mongo
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
-port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
+port = ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
puts "Connecting to #{host}:#{port}"
-con = Mongo::Connection.new(host, port, :safe => true)
-db = con.db('ruby-mongo-examples')
+client = Mongo::Client.new(host, port, :safe => true)
+db = client.db('ruby-mongo-examples')
coll = db.create_collection('test')
# Erase all records from collection, if any
coll.remove
-admin = con['admin']
+admin = client['admin']
# Profiling level set/get
puts "Profiling level: #{admin.profiling_level}"
View
4 examples/capped.rb
@@ -4,10 +4,10 @@
include Mongo
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
-port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
+port = ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
puts "Connecting to #{host}:#{port}"
-db = Connection.new(host, port, :safe => true).db('ruby-mongo-examples')
+db = Client.new(host, port, :safe => true).db('ruby-mongo-examples')
db.drop_collection('test')
# A capped collection has a max size and, optionally, a max number of records.
View
4 examples/cursor.rb
@@ -6,10 +6,10 @@
include Mongo
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
-port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
+port = ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
puts "Connecting to #{host}:#{port}"
-db = Connection.new(host, port, :safe => true).db('ruby-mongo-examples')
+db = Client.new(host, port, :safe => true).db('ruby-mongo-examples')
coll = db.collection('test')
# Erase all records from collection, if any
View
4 examples/gridfs.rb
@@ -7,10 +7,10 @@ def assert
include Mongo
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
-port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
+port = ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
puts "Connecting to #{host}:#{port}"
-db = Connection.new(host, port, :safe => true).db('ruby-mongo-examples')
+db = Client.new(host, port, :safe => true).db('ruby-mongo-examples')
data = "hello, world!"
View
4 examples/index_test.rb
@@ -5,10 +5,10 @@
include Mongo
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
-port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
+port = ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
puts ">> Connecting to #{host}:#{port}"
-db = Connection.new(host, port, :safe => true).db('ruby-mongo-index_test')
+db = Client.new(host, port, :safe => true).db('ruby-mongo-index_test')
class Exception
def errmsg
View
4 examples/info.rb
@@ -5,10 +5,10 @@
include Mongo
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
-port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
+port = ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
puts "Connecting to #{host}:#{port}"
-db = Connection.new(host, port, :safe => true).db('ruby-mongo-examples')
+db = Client.new(host, port, :safe => true).db('ruby-mongo-examples')
coll = db.collection('test')
# Erase all records from collection, if any
View
4 examples/queries.rb
@@ -6,10 +6,10 @@
include Mongo
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
-port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
+port = ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
puts "Connecting to #{host}:#{port}"
-db = Connection.new(host, port, :safe => true).db('ruby-mongo-examples')
+db = Client.new(host, port, :safe => true).db('ruby-mongo-examples')
coll = db.collection('test')
# Remove all records, if any
View
2 examples/replica_set.rb
@@ -4,7 +4,7 @@
cons = []
10.times do
- cons << Mongo::ReplSetConnection(['localhost:27017'], :read => :secondary)
+ cons << Mongo::ReplSetClient(['localhost:27017'], :read => :secondary)
end
ports = cons.map do |con|
View
4 examples/simple.rb
@@ -6,10 +6,10 @@
include Mongo
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
-port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
+port = ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
puts "Connecting to #{host}:#{port}"
-db = Connection.new(host, port, :safe => true).db('ruby-mongo-examples')
+db = Client.new(host, port, :safe => true).db('ruby-mongo-examples')
coll = db.collection('test')
# Erase all records from collection, if any
View
4 examples/strict.rb
@@ -5,10 +5,10 @@
include Mongo
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
-port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
+port = ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
puts "Connecting to #{host}:#{port}"
-db = Connection.new(host, port, :safe => true).db('ruby-mongo-examples')
+db = Client.new(host, port, :safe => true).db('ruby-mongo-examples')
db.drop_collection('does-not-exist')
db.create_collection('test')
View
4 examples/types.rb
@@ -6,10 +6,10 @@
include Mongo
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
-port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
+port = ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
puts "Connecting to #{host}:#{port}"
-db = Connection.new(host, port, :safe => true).db('ruby-mongo-examples')
+db = Client.new(host, port, :safe => true).db('ruby-mongo-examples')
coll = db.collection('test')
# Remove all records, if any
View
2 examples/web/thin/load.rb
@@ -1,7 +1,7 @@
require File.join(File.dirname(__FILE__), '..', '..', '..', 'lib', 'mongo')
require 'logger'
-$con = Mongo::ReplSetConnection.new(['localhost:30000', 'localhost:30001'], :safe => true, :read => :secondary, :refresh_mode => :sync, :refresh_interval => 30)
+$con = Mongo::ReplSetClient.new(['localhost:30000', 'localhost:30001'], :safe => true, :read => :secondary, :refresh_mode => :sync, :refresh_interval => 30)
$db = $con['foo']
class Load < Sinatra::Base
View
4 examples/web/unicorn/load.rb
@@ -1,7 +1,7 @@
require File.join(File.dirname(__FILE__), '..', '..', 'lib', 'mongo')
-$con = Mongo::Connection.new('localhost', 27017, :safe => true)
-$db = $con['foo']
+$client = Mongo::Client.new('localhost', 27017, :safe => true)
+$db = $client['foo']
class Load < Sinatra::Base
View
6 examples/web/unicorn/unicorn.rb.template
@@ -22,8 +22,8 @@ stdout_path "#{@dir}log/unicorn.stdout.log"
# NOTE: You need this when using forking web servers!
after_fork do |server, worker|
- $con.close if $con
- $con = Mongo::Connection.new('localhost', 27017, :safe => true)
- $db = $con['foo']
+ $client.close if $client
+ $client = Mongo::Client.new('localhost', 27017, :safe => true)
+ $db = $client['foo']
STDERR << "FORKED #{server} #{worker}"
end
View
54 lib/mongo/client.rb
@@ -51,18 +51,18 @@ class Client
# You may specify whether connection to slave is permitted.
# In all cases, the default host is "localhost" and the default port is 27017.
#
- # If you're connecting to a replica set, you'll need to use ReplSetConnection.new instead.
+ # If you're connecting to a replica set, you'll need to use ReplSetClient.new instead.
#
# Once connected to a replica set, you can find out which nodes are primary, secondary, and
- # arbiters with the corresponding accessors: Connection#primary, Connection#secondaries, and
- # Connection#arbiters. This is useful if your application needs to connect manually to nodes other
+ # arbiters with the corresponding accessors: Client#primary, Client#secondaries, and
+ # Client#arbiters. This is useful if your application needs to connect manually to nodes other
# than the primary.
#
# @param [String, Hash] host
# @param [Integer] port specify a port number here if only one host is being specified.
#
# @option opts [Boolean, Hash] :safe (false) Set the default safe-mode options
- # propagated to DB objects instantiated off of this Connection. This
+ # propagated to DB objects instantiated off of this Client. This
# default can be overridden upon instantiation of any DB by explicitly setting a :safe value
# on initialization.
# @option opts [Boolean] :slave_ok (false) Must be set to +true+ when connecting
@@ -81,16 +81,16 @@ class Client
# @option opts [Boolean] :ssl (false) If true, create the connection to the server using SSL.
#
# @example localhost, 27017 (or <code>ENV["MONGODB_URI"]</code> if available)
- # Mongo::Connection.new
+ # Mongo::Client.new
#
# @example localhost, 27017
- # Mongo::Connection.new("localhost")
+ # Mongo::Client.new("localhost")
#
# @example localhost, 3000, max 5 self.connections, with max 5 seconds of wait time.
- # Mongo::Connection.new("localhost", 3000, :pool_size => 5, :timeout => 5)
+ # Mongo::Client.new("localhost", 3000, :pool_size => 5, :timeout => 5)
#
# @example localhost, 3000, where this node may be a slave
- # Mongo::Connection.new("localhost", 3000, :slave_ok => true)
+ # Mongo::Client.new("localhost", 3000, :slave_ok => true)
#
# @see http://api.mongodb.org/ruby/current/file.REPLICA_SETS.html Replica sets in Ruby
#
@@ -104,27 +104,27 @@ def initialize(host=nil, port=nil, opts={})
if host.nil? and ENV.has_key?('MONGODB_URI')
parser = URIParser.new ENV['MONGODB_URI']
if parser.replicaset?
- raise MongoArgumentError, "Mongo::Connection.new called with no arguments, but ENV['MONGODB_URI'] implies a replica set."
+ raise MongoArgumentError, "Mongo::Client.new called with no arguments, but ENV['MONGODB_URI'] implies a replica set."
end
opts = parser.connection_options.merge! opts
@host_to_try = [parser.host, parser.port]
elsif host.is_a?(String) && (port || DEFAULT_PORT).respond_to?(:to_i)
@host_to_try = [host, (port || DEFAULT_PORT).to_i]
elsif host || port
- raise MongoArgumentError, "Mongo::Connection.new host or port argument error, host:#{host.inspect}, port:#{port.inspect}"
+ raise MongoArgumentError, "Mongo::Client.new host or port argument error, host:#{host.inspect}, port:#{port.inspect}"
else
@host_to_try = [DEFAULT_HOST, DEFAULT_PORT]
end
# Host and port of current master.
@host = @port = nil
-
+
# Default maximum BSON object size
@max_bson_size = Mongo::DEFAULT_MAX_BSON_SIZE
-
+
# Lock for request ids.
@id_lock = Mutex.new
-
+
# Connection pool for primay node
@primary = nil
@primary_pool = nil
@@ -146,39 +146,39 @@ def initialize(host=nil, port=nil, opts={})
# is_master command on the replica set.
#
# @param nodes [Array] An array of arrays, each of which specifies a host and port.
- # @param opts [Hash] Any of the available options that can be passed to Connection.new.
+ # @param opts [Hash] Any of the available options that can be passed to Client.new.
#
# @option opts [String] :rs_name (nil) The name of the replica set to connect to. An exception will be
# raised if unable to connect to a replica set with this name.
# @option opts [Boolean] :read_secondary (false) When true, this connection object will pick a random slave
# to send reads to.
#
# @example
- # Mongo::Connection.multi([["db1.example.com", 27017], ["db2.example.com", 27017]])
+ # Mongo::Client.multi([["db1.example.com", 27017], ["db2.example.com", 27017]])
#
# @example This connection will read from a random secondary node.
- # Mongo::Connection.multi([["db1.example.com", 27017], ["db2.example.com", 27017], ["db3.example.com", 27017]],
+ # Mongo::Client.multi([["db1.example.com", 27017], ["db2.example.com", 27017], ["db3.example.com", 27017]],
# :read_secondary => true)
#
- # @return [Mongo::Connection]
+ # @return [Mongo::Client]
#
# @deprecated
def self.multi(nodes, opts={})
- warn "Connection.multi is now deprecated and will be removed in v2.0. Please use ReplSetConnection.new instead."
+ warn "Client.multi is now deprecated and will be removed in v2.0. Please use ReplSetClient.new instead."
- ReplSetConnection.new(*(nodes+[opts]))
+ ReplSetClient.new(*(nodes+[opts]))
end
# Initialize a connection to MongoDB using the MongoDB URI spec.
#
- # Since Connection.new cannot be used with any <code>ENV["MONGODB_URI"]</code> that has multiple hosts (implying a replicaset), you may use this when the type of your connection varies by environment and should be determined solely from <code>ENV["MONGODB_URI"]</code>.
+ # Since Client.new cannot be used with any <code>ENV["MONGODB_URI"]</code> that has multiple hosts (implying a replicaset), you may use this when the type of your connection varies by environment and should be determined solely from <code>ENV["MONGODB_URI"]</code>.
#
# @param uri [String]
# A string of the format mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/database]
#
- # @param opts Any of the options available for Connection.new
+ # @param opts Any of the options available for Client.new
#
- # @return [Mongo::Connection, Mongo::ReplSetConnection]
+ # @return [Mongo::Client, Mongo::ReplSetClient]
def self.from_uri(uri = ENV['MONGODB_URI'], extra_opts={})
parser = URIParser.new uri
parser.connection(extra_opts)
@@ -245,7 +245,7 @@ def apply_saved_authentication(opts={})
# by DB#authenticate.
#
# Note: this method will not actually issue an authentication command. To do that,
- # either run Connection#apply_saved_authentication or DB#authenticate.
+ # either run Client#apply_saved_authentication or DB#authenticate.
#
# @param [String] db_name
# @param [String] username
@@ -508,21 +508,21 @@ def max_bson_size
end
# Checkout a socket for reading (i.e., a secondary node).
- # Note: this is overridden in ReplSetConnection.
+ # Note: this is overridden in ReplSetClient.
def checkout_reader(mode=:primary, tag_sets={}, acceptable_latency=15)
connect unless connected?
@primary_pool.checkout
end
# Checkout a socket for writing (i.e., a primary node).
- # Note: this is overridden in ReplSetConnection.
+ # Note: this is overridden in ReplSetClient.
def checkout_writer
connect unless connected?
@primary_pool.checkout
end
# Check a socket back into its pool.
- # Note: this is overridden in ReplSetConnection.
+ # Note: this is overridden in ReplSetClient.
def checkin(socket)
if @primary_pool && socket && socket.pool
socket.pool.checkin(socket)
@@ -547,7 +547,7 @@ def check_opts(opts)
def setup(opts)
# slave_ok can be true only if one node is specified
@slave_ok = opts[:slave_ok]
-
+
# Determine whether to use SSL.
@ssl = opts.fetch(:ssl, false)
if @ssl
View
95 lib/mongo/collection.rb
@@ -91,16 +91,16 @@ def initialize(name, db, opts={})
@connection = @db.connection
@logger = @connection.logger
@cache_time = @db.cache_time
- @cache = Hash.new(0)
+ @cache = Hash.new(0)
unless pk_factory
@safe = opts.fetch(:safe, @db.safe)
if value = opts[:read]
Mongo::Support.validate_read_preference(value)
else
value = @db.read_preference
end
- @read_preference = value.is_a?(Hash) ? value.dup : value
- @tag_sets = opts.fetch(:tag_sets, @db.tag_sets)
+ @read_preference = value.is_a?(Hash) ? value.dup : value
+ @tag_sets = opts.fetch(:tag_sets, @db.tag_sets)
@acceptable_latency = opts.fetch(:acceptable_latency, @db.acceptable_latency)
end
@pk_factory = pk_factory || opts[:pk] || BSON::ObjectId
@@ -211,23 +211,23 @@ def hint=(hint=nil)
#
# @core find find-instance_method
def find(selector={}, opts={})
- opts = opts.dup
- fields = opts.delete(:fields)
- fields = ["_id"] if fields && fields.empty?
- skip = opts.delete(:skip) || skip || 0
- limit = opts.delete(:limit) || 0
- sort = opts.delete(:sort)
- hint = opts.delete(:hint)
- snapshot = opts.delete(:snapshot)
- batch_size = opts.delete(:batch_size)
- timeout = (opts.delete(:timeout) == false) ? false : true
- max_scan = opts.delete(:max_scan)
- return_key = opts.delete(:return_key)
- transformer = opts.delete(:transformer)
- show_disk_loc = opts.delete(:show_disk_loc)
- comment = opts.delete(:comment)
- read = opts.delete(:read) || @read_preference
- tag_sets = opts.delete(:tag_sets) || @tag_sets
+ opts = opts.dup
+ fields = opts.delete(:fields)
+ fields = ["_id"] if fields && fields.empty?
+ skip = opts.delete(:skip) || skip || 0
+ limit = opts.delete(:limit) || 0
+ sort = opts.delete(:sort)
+ hint = opts.delete(:hint)
+ snapshot = opts.delete(:snapshot)
+ batch_size = opts.delete(:batch_size)
+ timeout = (opts.delete(:timeout) == false) ? false : true
+ max_scan = opts.delete(:max_scan)
+ return_key = opts.delete(:return_key)
+ transformer = opts.delete(:transformer)
+ show_disk_loc = opts.delete(:show_disk_loc)
+ comment = opts.delete(:comment)
+ read = opts.delete(:read) || @read_preference
+ tag_sets = opts.delete(:tag_sets) || @tag_sets
acceptable_latency = opts.delete(:acceptable_latency) || @acceptable_latency
if timeout == false && !block_given?
@@ -243,22 +243,22 @@ def find(selector={}, opts={})
raise RuntimeError, "Unknown options [#{opts.inspect}]" unless opts.empty?
cursor = Cursor.new(self, {
- :selector => selector,
- :fields => fields,
- :skip => skip,
- :limit => limit,
- :order => sort,
- :hint => hint,
- :snapshot => snapshot,
- :timeout => timeout,
- :batch_size => batch_size,
- :transformer => transformer,
- :max_scan => max_scan,
- :show_disk_loc => show_disk_loc,
- :return_key => return_key,
- :read => read,
- :tag_sets => tag_sets,
- :comment => comment,
+ :selector => selector,
+ :fields => fields,
+ :skip => skip,
+ :limit => limit,
+ :order => sort,
+ :hint => hint,
+ :snapshot => snapshot,
+ :timeout => timeout,
+ :batch_size => batch_size,
+ :transformer => transformer,
+ :max_scan => max_scan,
+ :show_disk_loc => show_disk_loc,
+ :return_key => return_key,
+ :read => read,
+ :tag_sets => tag_sets,
+ :comment => comment,
:acceptable_latency => acceptable_latency
})
@@ -515,11 +515,10 @@ def update(selector, document, opts={})
# @core indexes create_index-instance_method
def create_index(spec, opts={})
opts[:dropDups] = opts[:drop_dups] if opts[:drop_dups]
- field_spec = parse_index_spec(spec)
- opts = opts.dup
- name = opts.delete(:name) || generate_index_name(field_spec)
- name = name.to_s if name
-
+ field_spec = parse_index_spec(spec)
+ opts = opts.dup
+ name = opts.delete(:name) || generate_index_name(field_spec)
+ name = name.to_s if name
generate_indexes(field_spec, name, opts)
name
end
@@ -541,12 +540,11 @@ def create_index(spec, opts={})
#
# @return [String] the name of the index.
def ensure_index(spec, opts={})
- now = Time.now.utc.to_i
+ now = Time.now.utc.to_i
opts[:dropDups] = opts[:drop_dups] if opts[:drop_dups]
- field_spec = parse_index_spec(spec)
-
- name = opts[:name] || generate_index_name(field_spec)
- name = name.to_s if name
+ field_spec = parse_index_spec(spec)
+ name = opts[:name] || generate_index_name(field_spec)
+ name = name.to_s if name
if !@cache[name] || @cache[name] <= now
generate_indexes(field_spec, name, opts)
@@ -616,7 +614,7 @@ def find_and_modify(opts={})
# coll.aggregate([ {"$project" => {"last_name" => 1, "first_name" => 1 }}, {"$match" => {"last_name" => "Jones"}} ])
#
# @param [Array] pipeline Should be a single array of pipeline operator hashes.
- #
+ #
# '$project' Reshapes a document stream by including fields, excluding fields, inserting computed fields,
# renaming fields,or creating/populating fields that hold sub-documents.
#
@@ -854,11 +852,10 @@ def new_group(opts={})
# @return [Array] an array of distinct values.
def distinct(key, query=nil)
raise MongoArgumentError unless [String, Symbol].include?(key.class)
- command = BSON::OrderedHash.new
+ command = BSON::OrderedHash.new
command[:distinct] = @name
command[:key] = key.to_s
command[:query] = query
-
@db.command(command)["values"]
end
View
8 lib/mongo/cursor.rb
@@ -39,7 +39,6 @@ class Cursor
# @core cursors constructor_details
def initialize(collection, opts={})
@cursor_id = nil
-
@db = collection.db
@collection = collection
@connection = @db.connection
@@ -211,9 +210,7 @@ def count(skip_and_limit = false)
# @raise [InvalidSortValueError] if the specified order is invalid.
def sort(order, direction=nil)
check_modifiable
-
order = [[order, direction]] unless direction.nil?
-
@order = order
self
end
@@ -231,7 +228,6 @@ def sort(order, direction=nil)
def limit(number_to_return=nil)
return @limit unless number_to_return
check_modifiable
-
@limit = number_to_return
self
end
@@ -257,7 +253,7 @@ def skip(number_to_skip=nil)
#
# Note that the batch size will take effect only on queries
# where the number to be returned is greater than 100.
- #
+ #
# This can not override MongoDB's limit on the amount of data it will
# return to the client. Depending on server version this can be 4-16mb.
#
@@ -538,7 +534,7 @@ def send_get_more
ensure
checkin_socket(sock) unless @socket
end
-
+
@returned += @n_received
@cache += results
close_cursor_if_query_complete
View
18 lib/mongo/db.rb
@@ -47,7 +47,7 @@ def strict?; @strict; end
# The name of the database and the local safe option.
attr_reader :name, :safe
- # The Mongo::Connection instance connecting to the MongoDB server.
+ # The Mongo::Client instance connecting to the MongoDB server.
attr_reader :connection
# The length of time that Collection.ensure_index should cache index calls
@@ -59,8 +59,8 @@ def strict?; @strict; end
# Instances of DB are normally obtained by calling Mongo#db.
#
# @param [String] name the database name.
- # @param [Mongo::Connection] connection a connection object pointing to MongoDB. Note
- # that databases are usually instantiated via the Connection class. See the examples below.
+ # @param [Mongo::Client] client a connection object pointing to MongoDB. Note
+ # that databases are usually instantiated via the Client class. See the examples below.
#
# @option opts [Boolean] :strict (False) If true, collections must exist to be accessed and must
# not exist to be created. See DB#collection and DB#create_collection.
@@ -72,16 +72,16 @@ def strict?; @strict; end
#
# @option opts [Boolean, Hash] :safe (false) Set the default safe-mode options
# propagated to Collection objects instantiated off of this DB. If no
- # value is provided, the default value set on this instance's Connection object will be used. This
+ # value is provided, the default value set on this instance's Client object will be used. This
# default can be overridden upon instantiation of any collection by explicitly setting a :safe value
# on initialization
#
# @option opts [Integer] :cache_time (300) Set the time that all ensure_index calls should cache the command.
#
# @core databases constructor_details
- def initialize(name, connection, opts={})
+ def initialize(name, client, opts={})
@name = Mongo::Support.validate_db_name(name)
- @connection = connection
+ @connection = client
@strict = opts[:strict]
@pk_factory = opts[:pk]
@safe = opts.fetch(:safe, @connection.safe)
@@ -102,7 +102,7 @@ def initialize(name, connection, opts={})
# @param [String] username
# @param [String] password
# @param [Boolean] save_auth
- # Save this authentication to the connection object using Connection#add_auth. This
+ # Save this authentication to the client object using Client#add_auth. This
# will ensure that the authentication will be applied on database reconnect. Note
# that this value must be true when using connection pooling.
#
@@ -211,8 +211,8 @@ def remove_user(username)
end
end
- # Deauthorizes use for this database for this connection. Also removes
- # any saved authentication in the connection class associated with this
+ # Deauthorizes use for this database for this client connection. Also removes
+ # any saved authentication in the Client class associated with this
# database.
#
# @raise [MongoDBError] if logging out fails.
View
4 lib/mongo/gridfs/grid.rb
@@ -40,8 +40,8 @@ def initialize(db, fs_name=DEFAULT_FS_NAME)
# Create indexes only if we're connected to a primary node.
connection = @db.connection
- if (connection.class == Connection && connection.read_primary?) ||
- (connection.class == ReplSetConnection && connection.primary)
+ if (connection.class == Client && connection.read_primary?) ||
+ (connection.class == ReplSetClient && connection.primary)
@chunks.create_index([['files_id', Mongo::ASCENDING], ['n', Mongo::ASCENDING]], :unique => true)
end
end
View
4 lib/mongo/gridfs/grid_file_system.rb
@@ -41,8 +41,8 @@ def initialize(db, fs_name=Grid::DEFAULT_FS_NAME)
# Create indexes only if we're connected to a primary node.
connection = @db.connection
- if (connection.class == Connection && connection.read_primary?) ||
- (connection.class == ReplSetConnection && connection.primary)
+ if (connection.class == Client && connection.read_primary?) ||
+ (connection.class == ReplSetClient && connection.primary)
@files.create_index([['filename', 1], ['uploadDate', -1]])
@chunks.create_index([['files_id', Mongo::ASCENDING], ['n', Mongo::ASCENDING]], :unique => true)
end
View
8 lib/mongo/networking.rb
@@ -18,7 +18,7 @@ module Networking
# @return [Integer] number of bytes sent
def send_message(operation, message, opts={})
if opts.is_a?(String)
- warn "Connection#send_message no longer takes a string log message. " +
+ warn "Client#send_message no longer takes a string log message. " +
"Logging is now handled within the Collection and Cursor classes."
opts = {}
end
@@ -181,7 +181,7 @@ def receive_response_header(sock)
# unpacks to flags, cursor_id_a, cursor_id_b, starting_from, number_remaining
flags, cursor_id_a, cursor_id_b, _, number_remaining = header_buf.unpack('VVVVV')
-
+
check_response_flags(flags)
cursor_id = (cursor_id_b << 32) + cursor_id_a
[number_remaining, cursor_id]
@@ -210,7 +210,7 @@ def read_documents(number_received, sock)
end
# Constructs a getlasterror message. This method is used exclusively by
- # Connection#send_message_with_safe_check.
+ # Client#send_message_with_safe_check.
#
# Because it modifies message by reference, we don't need to return it.
def build_last_error_message(message, db_name, opts)
@@ -306,7 +306,7 @@ def receive_message_on_socket(length, socket)
def receive_data(length, socket)
message = new_binary_string
socket.read(length, message)
-
+
raise ConnectionFailure, "connection closed" unless message && message.length > 0
if message.length < length
chunk = new_binary_string
View
38 lib/mongo/repl_set_client.rb
@@ -32,15 +32,15 @@ class ReplSetClient < Client
# If no args are provided, it will check <code>ENV["MONGODB_URI"]</code>.
#
# Once connected to a replica set, you can find out which nodes are primary, secondary, and
- # arbiters with the corresponding accessors: Connection#primary, Connection#secondaries, and
- # Connection#arbiters. This is useful if your application needs to connect manually to nodes other
+ # arbiters with the corresponding accessors: Client#primary, Client#secondaries, and
+ # Client#arbiters. This is useful if your application needs to connect manually to nodes other
# than the primary.
#
# @overload initialize(seeds=ENV["MONGODB_URI"], opts={})
# @param [Array<String>, Array<Array(String, Integer)>] seeds
#
# @option opts [Boolean, Hash] :safe (false) Set the default safe-mode options
- # propagated to DB objects instantiated off of this Connection. This
+ # propagated to DB objects instantiated off of this Client. This
# default can be overridden upon instantiation of any DB by explicitly setting a :safe value
# on initialization.
# @option opts [:primary, :primary_preferred, :secondary, :secondary_preferred, :nearest] :read_preference (:primary)
@@ -75,18 +75,18 @@ class ReplSetClient < Client
# will always trigger a complete refresh. This option is useful when you want to add new nodes
# or remove replica set nodes not currently in use by the driver.
# @option opts [Integer] :refresh_interval (90) If :refresh_mode is enabled, this is the number of seconds
- # between calls to check the replica set's state.
+ # between calls to check the replica set's state.
# @note the number of seed nodes does not have to be equal to the number of replica set members.
# The purpose of seed nodes is to permit the driver to find at least one replica set member even if a member is down.
#
# @example Connect to a replica set and provide two seed nodes.
- # Mongo::ReplSetConnection.new(['localhost:30000', 'localhost:30001'])
+ # Mongo::ReplSetClient.new(['localhost:30000', 'localhost:30001'])
#
# @example Connect to a replica set providing two seed nodes and ensuring a connection to the replica set named 'prod':
- # Mongo::ReplSetConnection.new(['localhost:30000', 'localhost:30001'], :name => 'prod')
+ # Mongo::ReplSetClient.new(['localhost:30000', 'localhost:30001'], :name => 'prod')
#
# @example Connect to a replica set providing two seed nodes and allowing reads from a secondary node:
- # Mongo::ReplSetConnection.new(['localhost:30000', 'localhost:30001'], :read => :secondary)
+ # Mongo::ReplSetClient.new(['localhost:30000', 'localhost:30001'], :read => :secondary)
#
# @see http://api.mongodb.org/ruby/current/file.REPLICA_SETS.html Replica sets in Ruby
#
@@ -101,19 +101,19 @@ def initialize(*args)
if nodes.empty? and ENV.has_key?('MONGODB_URI')
parser = URIParser.new ENV['MONGODB_URI']
if parser.direct?
- raise MongoArgumentError, "Mongo::ReplSetConnection.new called with no arguments, but ENV['MONGODB_URI'] implies a direct connection."
+ raise MongoArgumentError, "Mongo::ReplSetClient.new called with no arguments, but ENV['MONGODB_URI'] implies a direct connection."
end
opts = parser.connection_options.merge! opts
nodes = [parser.nodes]
end
unless nodes.length > 0
- raise MongoArgumentError, "A ReplSetConnection requires at least one seed node."
+ raise MongoArgumentError, "A ReplSetClient requires at least one seed node."
end
# This is temporary until support for the old format is dropped
if nodes.first.last.is_a?(Integer)
- warn "Initiating a ReplSetConnection with seeds passed as individual [host, port] array arguments is deprecated."
+ warn "Initiating a ReplSetClient with seeds passed as individual [host, port] array arguments is deprecated."
warn "Please specify hosts as an array of 'host:port' strings; the old format will be removed in v2.0"
@seeds = nodes
else
@@ -154,7 +154,7 @@ def valid_opts
end
def inspect
- "<Mongo::ReplSetConnection:0x#{self.object_id.to_s(16)} @seeds=#{@seeds.inspect} " +
+ "<Mongo::ReplSetClient:0x#{self.object_id.to_s(16)} @seeds=#{@seeds.inspect} " +
"@connected=#{@connected}>"
end
@@ -185,7 +185,7 @@ def connect
# Determine whether a replica set refresh is
# required. If so, run a hard refresh. You can
# force a hard refresh by running
- # ReplSetConnection#hard_refresh!
+ # ReplSetClient#hard_refresh!
#
# @return [Boolean] +true+ unless a hard refresh
# is run and the refresh lock can't be acquired.
@@ -234,7 +234,7 @@ def connected?
# @deprecated
def connecting?
- warn "ReplSetConnection#connecting? is deprecated and will be removed in v2.0."
+ warn "ReplSetClient#connecting? is deprecated and will be removed in v2.0."
false
end
@@ -253,8 +253,8 @@ def port
end
def nodes
- warn "ReplSetConnection#nodes is DEPRECATED and will be removed in v2.0. " +
- "Please use ReplSetConnection#seeds instead."
+ warn "ReplSetClient#nodes is DEPRECATED and will be removed in v2.0. " +
+ "Please use ReplSetClient#seeds instead."
@seeds
end
@@ -292,8 +292,8 @@ def close(opts={})
# @deprecated
def reset_connection
close
- warn "ReplSetConnection#reset_connection is now deprecated and will be removed in v2.0. " +
- "Use ReplSetConnection#close instead."
+ warn "ReplSetClient#reset_connection is now deprecated and will be removed in v2.0. " +
+ "Use ReplSetClient#close instead."
end
# Returns +true+ if it's okay to read from a secondary node.
@@ -336,7 +336,7 @@ def checkout
end
socket
end
-
+
def checkout_reader(mode=@read, tag_sets=@tag_sets, acceptable_latency=@acceptable_latency)
checkout do
pool = read_pool(mode, tag_sets, acceptable_latency)
@@ -479,7 +479,7 @@ def setup(opts)
super opts
end
-
+
def prune_managers
@old_managers.each do |manager|
if manager != @manager
View
10 lib/mongo/sharded_client.rb
@@ -35,7 +35,7 @@ class ShardedClient < ReplSetClient
# @option opts [String] :name (nil) The name of the sharded cluster to connect to. You
# can use this option to verify that you're connecting to the right sharded cluster.
# @option opts [Boolean, Hash] :safe (false) Set the default safe-mode options
- # propagated to DB objects instantiated off of this Connection. This
+ # propagated to DB objects instantiated off of this Client. This
# default can be overridden upon instantiation of any DB by explicitly setting a :safe value
# on initialization.
# @option opts [Logger] :logger (nil) Logger instance to receive driver operation log.
@@ -58,7 +58,7 @@ class ShardedClient < ReplSetClient
# The purpose of seed nodes is to permit the driver to find at least one sharded cluster member even if a member is down.
#
# @example Connect to a sharded cluster and provide two seed nodes.
- # Mongo::ShardedConnection.new(['localhost:30000', 'localhost:30001'])
+ # Mongo::ShardedClient.new(['localhost:30000', 'localhost:30001'])
#
# @raise [MongoArgumentError] This is raised for usage errors.
#
@@ -71,14 +71,14 @@ def initialize(*args)
if nodes.empty? and ENV.has_key?('MONGODB_URI')
parser = URIParser.new ENV['MONGODB_URI']
if parser.direct?
- raise MongoArgumentError, "Mongo::ShardedConnection.new called with no arguments, but ENV['MONGODB_URI'] implies a direct connection."
+ raise MongoArgumentError, "Mongo::ShardedClient.new called with no arguments, but ENV['MONGODB_URI'] implies a direct connection."
end
opts = parser.connection_options.merge! opts
nodes = [parser.nodes]
end
unless nodes.length > 0
- raise MongoArgumentError, "A ShardedConnection requires at least one seed node."
+ raise MongoArgumentError, "A ShardedClient requires at least one seed node."
end
@seeds = nodes.map do |host_port|
@@ -118,7 +118,7 @@ def valid_opts
end
def inspect
- "<Mongo::ShardedConnection:0x#{self.object_id.to_s(16)} @seeds=#{@seeds.inspect} " +
+ "<Mongo::ShardedClient:0x#{self.object_id.to_s(16)} @seeds=#{@seeds.inspect} " +
"@connected=#{@connected}>"
end
View
30 lib/mongo/util/node.rb
@@ -1,10 +1,10 @@
module Mongo
class Node
- attr_accessor :host, :port, :address, :config, :connection, :socket, :last_state
+ attr_accessor :host, :port, :address, :config, :client, :socket, :last_state
- def initialize(connection, host_port)
- @connection = connection
+ def initialize(client, host_port)
+ @client = client
@host, @port = split_node(host_port)
@address = "#{@host}:#{@port}"
@config = nil
@@ -29,11 +29,11 @@ def inspect
# return nil.
def connect
begin
- socket = @connection.socket_class.new(@host, @port,
- @connection.op_timeout, @connection.connect_timeout
+ socket = @client.socket_class.new(@host, @port,
+ @client.op_timeout, @client.connect_timeout
)
rescue OperationTimeout, ConnectionFailure, OperationFailure, SocketError, SystemCallError, IOError => ex
- @connection.log(:debug, "Failed connection to #{host_string} with #{ex.class}, #{ex.message}.")
+ @client.log(:debug, "Failed connection to #{host_string} with #{ex.class}, #{ex.message}.")
socket.close if socket
end
@@ -54,7 +54,7 @@ def connected?
def active?
begin
- result = @connection['admin'].command({:ping => 1}, :socket => @socket)
+ result = @client['admin'].command({:ping => 1}, :socket => @socket)
rescue OperationFailure, SocketError, SystemCallError, IOError
return nil
end
@@ -66,16 +66,16 @@ def active?
# matches with the name provided.
def set_config
begin
- @config = @connection['admin'].command({:ismaster => 1}, :socket => @socket)
+ @config = @client['admin'].command({:ismaster => 1}, :socket => @socket)
if @config['msg']
- @connection.log(:warn, "#{config['msg']}")
+ @client.log(:warn, "#{config['msg']}")
end
check_set_membership(config)
check_set_name(config)
rescue ConnectionFailure, OperationFailure, OperationTimeout, SocketError, SystemCallError, IOError => ex
- @connection.log(:warn, "Attempted connection to node #{host_string} raised " +
+ @client.log(:warn, "Attempted connection to node #{host_string} raised " +
"#{ex.class}: #{ex.message}")
# Socket may already be nil from issuing command
@@ -145,7 +145,7 @@ def split_node(host_port)
end
host = host_port[0]
- port = host_port[1].nil? ? Connection::DEFAULT_PORT : host_port[1].to_i
+ port = host_port[1].nil? ? Client::DEFAULT_PORT : host_port[1].to_i
[host, port]
end
@@ -165,13 +165,13 @@ def check_set_membership(config)
# Ensure that this node is part of a replica set of the expected name.
def check_set_name(config)
- if @connection.replica_set_name
+ if @client.replica_set_name
if !config['setName']
- @connection.log(:warn, "Could not verify replica set name for member #{host_string} " +
+ @client.log(:warn, "Could not verify replica set name for member #{host_string} " +
"because ismaster does not return name in this version of MongoDB")
- elsif @connection.replica_set_name != config['setName']
+ elsif @client.replica_set_name != config['setName']
message = "Attempting to connect to replica set '#{config['setName']}' on member #{host_string} " +
- "but expected '#{@connection.replica_set_name}'"
+ "but expected '#{@client.replica_set_name}'"
raise ReplicaSetConnectionError, message
end
end
View
18 lib/mongo/util/pool.rb
@@ -25,8 +25,8 @@ class Pool
:size, :timeout, :safe, :checked_out, :connection
# Create a new pool of connections.
- def initialize(connection, host, port, opts={})
- @connection = connection
+ def initialize(client, host, port, opts={})
+ @connection = client
@host, @port = host, port
@@ -52,12 +52,12 @@ def initialize(connection, host, port, opts={})
# Operations to perform on a socket
@socket_ops = Hash.new { |h, k| h[k] = [] }
- @sockets = []
- @pids = {}
- @checked_out = []
- @ping_time = nil
- @last_ping = nil
- @closed = false
+ @sockets = []
+ @pids = {}
+ @checked_out = []
+ @ping_time = nil
+ @last_ping = nil
+ @closed = false
@threads_to_sockets = {}
@checkout_counter = 0
end
@@ -321,7 +321,7 @@ def checkout
socket = checkout_new_socket
end
-
+
return socket
else
# Otherwise, wait
View
35 lib/mongo/util/pool_manager.rb
@@ -14,10 +14,10 @@ class PoolManager
# the user may pass an additional list of seeds nodes discovered in real
# time. The union of these lists will be used when attempting to connect,
# with the newly-discovered nodes being used first.
- def initialize(connection, seeds=[])
- @pinned_pools = {}
- @connection = connection
- @seeds = seeds
+ def initialize(client, seeds=[])
+ @pinned_pools = {}
+ @connection = client
+ @seeds = seeds
@previously_connected = false
end
@@ -99,8 +99,9 @@ def read
read_pool.host_port
end
- def read_pool(mode=@connection.read_preference, tags=@connection.tag_sets,
- acceptable_latency=@connection.acceptable_latency)
+ def read_pool(mode=@connection.read_preference,
+ tags=@connection.tag_sets,
+ acceptable_latency=@connection.acceptable_latency)
if mode == :primary && !tags.empty?
raise MongoArgumentError, "Read preferecy :primary cannot be combined with tags"
@@ -159,18 +160,18 @@ def validate_existing_member(member)
end
def initialize_data
- @primary = nil
- @primary_pool = nil
- @read = nil
- @read_pool = nil
- @arbiters = []
- @secondaries = []
- @secondary_pool = nil
- @secondary_pools = []
- @hosts = Set.new
- @members = Set.new
+ @primary = nil
+ @primary_pool = nil
+ @read = nil
+ @read_pool = nil
+ @arbiters = []
+ @secondaries = []
+ @secondary_pool = nil
+ @secondary_pools = []
+ @hosts = Set.new
+ @members = Set.new
@refresh_required = false
- @pinned_pools = {}
+ @pinned_pools = {}
end
# Connect to each member of the replica set
View
24 lib/mongo/util/uri_parser.rb
@@ -78,7 +78,7 @@ class URIParser
attr_reader :auths, :connect, :replicaset, :slaveok, :safe, :w, :wtimeout, :fsync, :journal, :connecttimeoutms, :sockettimeoutms, :wtimeoutms
- # Parse a MongoDB URI. This method is used by Connection.from_uri.
+ # Parse a MongoDB URI. This method is used by Client.from_uri.
# Returns an array of nodes and an array of db authorizations, if applicable.
#
# @note Passwords can contain any character except for ','
@@ -100,17 +100,17 @@ def initialize(uri)
validate_connect
end
- # Create a Mongo::Connection or a Mongo::ReplSetConnection based on the URI.
+ # Create a Mongo::Client or a Mongo::ReplSetClient based on the URI.
#
# @note Don't confuse this with attribute getter method #connect.
#
- # @return [Connection,ReplSetConnection]
+ # @return [Client,ReplSetClient]
def connection(extra_opts)
opts = connection_options.merge! extra_opts
if replicaset?
- ReplSetConnection.new(nodes, opts)
+ ReplSetClient.new(nodes, opts)
else
- Connection.new(host, port, opts)
+ Client.new(host, port, opts)
end
end
@@ -147,7 +147,7 @@ def port
nodes[0][1].to_i
end
- # Options that can be passed to Mongo::Connection.new or Mongo::ReplSetConnection.new
+ # Options that can be passed to Mongo::Client.new or Mongo::ReplSetClient.new
# @return [Hash]
def connection_options
opts = {}
@@ -161,28 +161,28 @@ def connection_options
safe_opts = {}
safe_opts[:w] = @w if @w
safe_opts[:j] = @journal if @journal
-
+
if @wtimeout
warn "Using wtimeout in a URI is deprecated, please use wtimeoutMS. It will be removed in v2.0."
safe_opts[:wtimeout] = @wtimeout
end
-
+
if @wtimeoutms
safe_opts[:wtimeout] = @wtimeoutms
end
-
+
safe_opts[:fsync] = @fsync if @fsync
else
safe_opts = true
end
opts[:safe] = safe_opts
end
-
+
if @connecttimeoutms
opts[:connect_timeout] = @connecttimeoutms
end
-
+
if @sockettimeoutms
opts[:op_timeout] = @sockettimeoutms
end
@@ -235,7 +235,7 @@ def parse_hosts(uri_without_proto)
hosturis.each do |hosturi|
# If port is present, use it, otherwise use default port
- host, port = hosturi.split(':') + [Connection::DEFAULT_PORT]
+ host, port = hosturi.split(':') + [Client::DEFAULT_PORT]
if !(port.to_s =~ /^\d+$/)
raise MongoArgumentError, "Invalid port #{port}; port must be specified as digits."
View
4 test/auxillary/1.4_features.rb → test/auxillary/1.4_feature_test.rb
@@ -7,8 +7,8 @@ class Features14Test < Test::Unit::TestCase
context "MongoDB 1.4" do
setup do
- @con = Mongo::Connection.new
- @db = @con['mongo-ruby-test']
+ @client = Mongo::Client.new
+ @db = @client['mongo-ruby-test']
@col = @db['new-features']
end
View
12 test/auxillary/authentication_test.rb
@@ -7,17 +7,17 @@ class AuthenticationTest < Test::Unit::TestCase
include Mongo
def setup
- @conn = Mongo::Connection.new
- @db1 = @conn.db('mongo-ruby-test-auth1')
- @db2 = @conn.db('mongo-ruby-test-auth2')
- @admin = @conn.db('admin')
+ @client = Mongo::Client.new
+ @db1 = @client.db('mongo-ruby-test-auth1')
+ @db2 = @client.db('mongo-ruby-test-auth2')
+ @admin = @client.db('admin')
end
def teardown
@db1.authenticate('user1', 'secret')
@db2.authenticate('user2', 'secret')
- @conn.drop_database('mongo-ruby-test-auth1')
- @conn.drop_database('mongo-ruby-test-auth2')
+ @client.drop_database('mongo-ruby-test-auth1')
+ @client.drop_database('mongo-ruby-test-auth2')
end
def test_authenticate
View
4 test/auxillary/autoreconnect_test.rb
@@ -6,8 +6,8 @@ class AutoreconnectTest < Test::Unit::TestCase
include Mongo
def setup
- @conn = Mongo::Connection.new
- @db = @conn.db('mongo-ruby-test')
+ @client = Mongo::Client.new
+ @db = @client.db('mongo-ruby-test')
@db.drop_collection("test-connect")
@coll = @db.collection("test-connect")
end
View
8 test/auxillary/fork_test.rb
@@ -5,23 +5,23 @@ class ForkTest < Test::Unit::TestCase
include Mongo
def setup
- @conn = standard_connection
+ @client = standard_connection
end
def test_fork
# Now insert some data
10.times do |n|
- @conn[MONGO_TEST_DB]['nums'].insert({:a => n})
+ @client[MONGO_TEST_DB]['nums'].insert({:a => n})
end
# Now fork. You'll almost always see an exception here.
if !Kernel.fork
10.times do
- assert @conn[MONGO_TEST_DB]['nums'].find_one
+ assert @client[MONGO_TEST_DB]['nums'].find_one
end
else
10.times do
- assert @conn[MONGO_TEST_DB]['nums'].find_one
+ assert @client[MONGO_TEST_DB]['nums'].find_one
end
end
end
View
22 test/auxillary/repl_set_auth_test.rb
@@ -14,35 +14,35 @@ def teardown
end
def test_repl_set_auth
- @conn = ReplSetConnection.new(build_seeds(3), :name => @rs.name)
+ @client = ReplSetClient.new(build_seeds(3), :name => @rs.name)
# Add an admin user
- @conn['admin'].add_user("me", "secret")
+ @client['admin'].add_user("me", "secret")
# Ensure that insert fails
assert_raise_error Mongo::OperationFailure, "unauthorized" do
- @conn['foo']['stuff'].insert({:a => 2}, :safe => {:w => 3})
+ @client['foo']['stuff'].insert({:a => 2}, :safe => {:w => 3})
end
# Then authenticate
- assert @conn['admin'].authenticate("me", "secret")
+ assert @client['admin'].authenticate("me", "secret")
# Insert should succeed now
- assert @conn['foo']['stuff'].insert({:a => 2}, :safe => {:w => 3})
+ assert @client['foo']['stuff'].insert({:a => 2}, :safe => {:w => 3})
# So should a query
- assert @conn['foo']['stuff'].find_one
+ assert @client['foo']['stuff'].find_one
# But not when we logout
- @conn['admin'].logout
+ @client['admin'].logout
assert_raise_error Mongo::OperationFailure, "unauthorized" do
- @conn['foo']['stuff'].find_one
+ @client['foo']['stuff'].find_one
end
# Same should apply to a random secondary
- @slave1 = Connection.new(@conn.secondary_pools[0].host,
- @conn.secondary_pools[0].port, :slave_ok => true)
+ @slave1 = Client.new(@client.secondary_pools[0].host,
+ @client.secondary_pools[0].port, :slave_ok => true)
# Find should fail
assert_raise_error Mongo::OperationFailure, "unauthorized" do
@@ -54,7 +54,7 @@ def test_repl_set_auth
assert @slave1['foo']['stuff'].find_one
# Same should apply when using :secondary_only
- @second_only = ReplSetConnection.new(build_seeds(3),
+ @second_only = ReplSetClient.new(build_seeds(3),
:require_primary => false, :read => :secondary_only)
# Find should fail
View
12 test/auxillary/slave_connection_test.rb
@@ -7,8 +7,8 @@ class SlaveConnectionTest < Test::Unit::TestCase
def self.connect_to_slave
@@host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
- @@port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
- conn = Connection.new(@@host, @@port, :slave_ok => true)
+ @@port = ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT
+ conn = Client.new(@@host, @@port, :slave_ok => true)
response = conn['admin'].command(:ismaster => 1)
Mongo::Support.ok?(response) && response['ismaster'] != 1
end
@@ -18,20 +18,20 @@ def self.connect_to_slave
def test_connect_to_slave
assert_raise Mongo::ConnectionFailure do
- @db = Connection.new(@@host, @@port, :slave_ok => false).db('ruby-mongo-demo')
+ @db = Client.new(@@host, @@port, :slave_ok => false).db('ruby-mongo-demo')
end
end
def test_slave_ok_sent_to_queries
- @con = Connection.new(@@host, @@port, :slave_ok => true)
+ @con = Client.new(@@host, @@port, :slave_ok => true)
assert_equal true, @con.slave_ok?
end
else
puts "Not connected to slave; skipping slave connection tests."
def test_slave_ok_false_on_queries
- @conn = Connection.new(@@host, @@port)
- assert !@conn.slave_ok?
+ @client = Client.new(@@host, @@port)
+ assert !@client.slave_ok?
end
end
end
View
12 test/auxillary/threaded_authentication_test.rb
@@ -8,17 +8,17 @@ class AuthenticationTest < Test::Unit::TestCase
include Mongo
def setup
- @conn = standard_connection(:pool_size => 10)
- @db1 = @conn.db('mongo-ruby-test-auth1')
- @db2 = @conn.db('mongo-ruby-test-auth2')
- @admin = @conn.db('admin')
+ @client = standard_connection(:pool_size => 10)
+ @db1 = @client.db('mongo-ruby-test-auth1')
+ @db2 = @client.db('mongo-ruby-test-auth2')
+ @admin = @client.db('admin')
end
def teardown
@db1.authenticate('user1', 'secret')
@db2.authenticate('user2', 'secret')
- @conn.drop_database('mongo-ruby-test-auth1')
- @conn.drop_database('mongo-ruby-test-auth2')
+ @client.drop_database('mongo-ruby-test-auth1')
+ @client.drop_database('mongo-ruby-test-auth2')
end
def threaded_exec
View
14 test/functional/collection_test.rb
@@ -28,8 +28,8 @@ def test_optional_pk_factory
assert_equal BSON::ObjectId, @coll_default_pk.pk_factory
# Create a db with a pk_factory.
- @db = Connection.new(ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost',
- ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT).db(MONGO_TEST_DB, :pk => Object.new)
+ @db = Client.new(ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost',
+ ENV['MONGO_RUBY_DRIVER_PORT'] || Client::DEFAULT_PORT).db(MONGO_TEST_DB, :pk => Object.new)
@coll = @db.collection('coll-with-pk')
assert @coll.pk_factory.is_a?(Object)
@@ -367,11 +367,11 @@ def test_safe_save
end
def test_mocked_safe_remove
- @conn = standard_connection
- @db = @conn[MONGO_TEST_DB]
+ @client = standard_connection
+ @db = @client[MONGO_TEST_DB]
@test = @db['test-safe-remove']
@test.save({:a => 20})
- @conn.stubs(:receive).returns([[{'ok' => 0, 'err' => 'failed'}], 1, 0])
+ @client.stubs(:receive).returns([[{'ok' => 0, 'err' => 'failed'}], 1, 0])
assert_raise OperationFailure do
@test.remove({}, :safe => true)
@@ -380,8 +380,8 @@ def test_mocked_safe_remove
end
def test_safe_remove
- @conn = standard_connection
- @db = @conn[MONGO_TEST_DB]
+ @client = standard_connection
+ @db = @client[MONGO_TEST_DB]
@test = @db['test-safe-remove']
@test.remove
@test.save({:a => 50})
View
156 test/functional/connection_test.rb
@@ -9,57 +9,43 @@ class TestConnection < Test::Unit::TestCase
include BSON
def setup
- @conn = standard_connection
+ @client = standard_connection
end
def teardown