Class: Mongo::Connection

Inherits:
Object show all
Extended by:
JavaImpl::Connection_::ClassMethods, JavaImpl::NoImplYetClass
Includes:
JavaImpl::Connection_::InstanceMethods, JavaImpl::Utils
Defined in:
lib/jmongo/connection.rb

Constant Summary collapse

DEFAULT_PORT =
27017

Constants included from JavaImpl::Connection_::ClassMethods

JavaImpl::Connection_::ClassMethods::OPTS_KEYS, JavaImpl::Connection_::ClassMethods::URI_RE

Constants included from JavaImpl::Utils

JavaImpl::Utils::SortingHash

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from JavaImpl::NoImplYetClass

raise_not_implemented

Methods included from JavaImpl::Connection_::ClassMethods

_from_uri

Methods included from JavaImpl::Utils

#from_dbobject, #prep_fields, #prep_hint, #prep_id, #prep_sort, #raise_not_implemented, #sort_value, #system_name?, #to_dbobject, #trap_raise, #validate_name

Constructor Details

#initialize(host = nil, port = nil, opts = {}) ⇒ Connection

Returns a new instance of Connection.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/jmongo/connection.rb', line 27

def initialize host = nil, port = nil, opts = {}
  @logger = opts.delete(:logger)
  @auths = opts.delete(:auths) || []
  if opts.has_key?(:new_from_uri)
    @mongo_uri = opts[:new_from_uri]
    @options = @mongo_uri.options
    @write_concern = @options.write_concern
    @connection = JMongo::Mongo.new(@mongo_uri)
  else
    @host = host || 'localhost'
    @port = port || 27017
    @server_address = JMongo::ServerAddress.new @host, @port
    @options = JMongo::MongoOptions.new
    opts.each do |k,v|
      key = k.to_sym
      jmo_key = JMongo.options_ruby2java_lu(key)
      case jmo_key
      when :safe
        @write_concern = DB.write_concern(v)
        @options.w = @write_concern.w
        @options.wtimeout = @write_concern.wtimeout
        @options.fsync = @write_concern.fsync
      else
        jmo_val = JMongo.options_ruby2java_xf(key, v)
        @options.send("#{jmo_key}=", jmo_val)
      end
    end
    @connection = JMongo::Mongo.new(@server_address, @options)
  end
  @connector = @connection.connector
  add = @connector.address
  @primary = [add.host, add.port]
end

Instance Attribute Details

#authsObject (readonly)

Returns the value of attribute auths.



23
24
25
# File 'lib/jmongo/connection.rb', line 23

def auths
  @auths
end

#connectionObject (readonly)

Returns the value of attribute connection.



23
24
25
# File 'lib/jmongo/connection.rb', line 23

def connection
  @connection
end

#connectorObject (readonly)

Returns the value of attribute connector.



23
24
25
# File 'lib/jmongo/connection.rb', line 23

def connector
  @connector
end

#loggerObject (readonly)

Returns the value of attribute logger.



23
24
25
# File 'lib/jmongo/connection.rb', line 23

def logger
  @logger
end

#primaryObject (readonly)

Returns the value of attribute primary.



23
24
25
# File 'lib/jmongo/connection.rb', line 23

def primary
  @primary
end

#write_concernObject (readonly)

Returns the value of attribute write_concern.



23
24
25
# File 'lib/jmongo/connection.rb', line 23

def write_concern
  @write_concern
end

Class Method Details

.from_uri(uri, opts = {}) ⇒ Mongo::Connection

Initialize a connection to MongoDB using the MongoDB URI spec:

Parameters:

Returns:



73
74
75
# File 'lib/jmongo/connection.rb', line 73

def self.from_uri(uri, opts={})
  _from_uri(uri,opts)
end

.paired(nodes, opts = {}) ⇒ Object



61
62
63
# File 'lib/jmongo/connection.rb', line 61

def self.paired(nodes, opts={})
  raise_not_implemented
end

Instance Method Details

#[](db_name) ⇒ Mongo::DB

Shortcut for returning a database. Use DB#db to accept options.

Parameters:

  • db_name (String)

    a valid database name.

Returns:



171
172
173
# File 'lib/jmongo/connection.rb', line 171

def [](db_name)
  db db_name
end

#add_auth(db_name, username, password) ⇒ Hash

Save an authentication to this connection. When connecting, the connection will attempt to re-authenticate on every db specificed in the list of auths. This method is called automatically by DB#authenticate.

Parameters:

Returns:

  • (Hash)

    a hash representing the authentication just added.



102
103
104
105
106
107
108
109
110
# File 'lib/jmongo/connection.rb', line 102

def add_auth(db_name, username, password)
  remove_auth(db_name)
  auth = {}
  auth['db_name']  = db_name
  auth['username'] = username
  auth['password'] = password
  @auths << auth
  auth
end

#apply_saved_authenticationBoolean

Apply each of the saved database authentications.

Returns:

  • (Boolean)

    returns true if authentications exist and succeeed, false if none exists.

Raises:



84
85
86
87
88
89
90
# File 'lib/jmongo/connection.rb', line 84

def apply_saved_authentication
  return false if @auths.empty?
  @auths.each do |auth|
    self[auth['db_name']].authenticate(auth['username'], auth['password'], false)
  end
  true
end

#clear_authstrue

Remove all authenication information stored in this connection.

Returns:

  • (true)

    this operation return true because it always succeeds.



129
130
131
132
# File 'lib/jmongo/connection.rb', line 129

def clear_auths
  @auths = []
  true
end

#closeObject



280
281
282
283
# File 'lib/jmongo/connection.rb', line 280

def close
  @connection.close if @connection
  @connection = @connector = nil
end

#connectObject Also known as: reconnect



269
270
271
272
273
274
275
276
277
# File 'lib/jmongo/connection.rb', line 269

def connect
  close
  if @mongo_uri
    @connection = JMongo::Mongo.new(@mongo_uri)
  else
    @connection = JMongo::Mongo.new(@server_address, @options)
  end
  @connector = @connection.connector
end

#connect_to_masterObject



261
262
263
# File 'lib/jmongo/connection.rb', line 261

def connect_to_master
  connect
end

#connected?Boolean

Returns:

  • (Boolean)


265
266
267
# File 'lib/jmongo/connection.rb', line 265

def connected?
  @connection && @connector && @connector.is_open
end

#copy_database(from, to, from_host = "localhost", username = nil, password = nil) ⇒ Object

Copy the database from to to on localhost. The from database is assumed to be on localhost, but an alternate host can be specified.

Parameters:

  • from (String)

    name of the database to copy from.

  • to (String)

    name of the database to copy to.

  • from_host (String) (defaults to: "localhost")

    host of the ‘from’ database.

  • username (String) (defaults to: nil)

    username for authentication against from_db (>=1.3.x).

  • password (String) (defaults to: nil)

    password for authentication against from_db (>=1.3.x).



190
191
192
# File 'lib/jmongo/connection.rb', line 190

def copy_database(from, to, from_host="localhost", username=nil, password=nil)
  raise_not_implemented
end

#database_infoHash

Return a hash with all database names and their respective sizes on disk.

Returns:



138
139
140
141
142
143
# File 'lib/jmongo/connection.rb', line 138

def database_info
  doc = self['admin'].command({:listDatabases => 1})
  doc['databases'].each_with_object({}) do |db, info|
    info[db['name']] = db['sizeOnDisk'].to_i
  end
end

#database_namesArray

Return an array of database names.

Returns:



148
149
150
# File 'lib/jmongo/connection.rb', line 148

def database_names
  get_db_names
end

#db(db_name, options = {}) ⇒ Mongo::DB

Return a database with the given name. See DB#new for valid options hash parameters.

Parameters:

  • db_name (String)

    a valid database name.

Returns:



160
161
162
# File 'lib/jmongo/connection.rb', line 160

def db(db_name, options={})
  DB.new db_name, self, options 
end

#drop_database(name) ⇒ Object

Drop a database.

Parameters:

  • name (String)

    name of an existing database.



178
179
180
# File 'lib/jmongo/connection.rb', line 178

def drop_database(name)
  drop_a_db name
end

#get_request_idObject

Increment and return the next available request id.

return [Integer]



197
198
199
# File 'lib/jmongo/connection.rb', line 197

def get_request_id
  raise_not_implemented
end

#log_operation(name, payload) ⇒ Object



230
231
232
233
234
235
236
237
238
# File 'lib/jmongo/connection.rb', line 230

def log_operation(name, payload)
  return unless @logger
  msg = "#{payload[:database]}['#{payload[:collection]}'].#{name}("
  msg += payload.values_at(:selector, :document, :documents, :fields ).compact.map(&:inspect).join(', ') + ")"
  msg += ".skip(#{payload[:skip]})"  if payload[:skip]
  msg += ".limit(#{payload[:limit]})"  if payload[:limit]
  msg += ".sort(#{payload[:order]})"  if payload[:order]
  @logger.debug "MONGODB #{msg}"
end

#pingHash

Checks if a server is alive. This command will return immediately even if the server is in a lock.

Returns:



205
206
207
# File 'lib/jmongo/connection.rb', line 205

def ping
  db("admin").command('ping')
end

#receive_message(operation, message, log_message = nil, socket = nil) ⇒ Object



257
258
259
# File 'lib/jmongo/connection.rb', line 257

def receive_message(operation, message, log_message=nil, socket=nil)
  raise_not_implemented
end

#remove_auth(db_name) ⇒ Boolean

Remove a saved authentication for this connection.

Parameters:

Returns:

  • (Boolean)


117
118
119
120
121
122
123
124
# File 'lib/jmongo/connection.rb', line 117

def remove_auth(db_name)
  return unless @auths
  if @auths.reject! { |a| a['db_name'] == db_name }
    true
  else
    false
  end
end

#send_message(operation, message, log_message = nil) ⇒ True

Send a message to MongoDB, adding the necessary headers.

Parameters:

  • operation (Integer)

    a MongoDB opcode.

  • message (BSON::ByteBuffer)

    a message to send to the database.

  • log_message (String) (defaults to: nil)

    text version of message for logging.

Returns:

  • (True)


249
250
251
# File 'lib/jmongo/connection.rb', line 249

def send_message(operation, message, log_message=nil)
  raise_not_implemented
end

#send_message_with_safe_check(operation, message, db_name, log_message = nil) ⇒ Object



253
254
255
# File 'lib/jmongo/connection.rb', line 253

def send_message_with_safe_check(operation, message, db_name, log_message=nil)
  raise_not_implemented
end

#server_infoHash

Get the build information for the current connection.

Returns:



211
212
213
# File 'lib/jmongo/connection.rb', line 211

def server_info
  db("admin").command('buildinfo')
end

#server_versionMongo::ServerVersion

Get the build version of the current server.

Returns:



219
220
221
# File 'lib/jmongo/connection.rb', line 219

def server_version
  ServerVersion.new(server_info["version"])
end

#slave_ok?Boolean

Is it okay to connect to a slave?

Returns:

  • (Boolean)


226
227
228
# File 'lib/jmongo/connection.rb', line 226

def slave_ok?
  raise_not_implemented
end