Class: Mongo::URI

Inherits:
Object
  • Object
show all
Includes:
Loggable
Defined in:
lib/mongo/uri.rb,
lib/mongo/uri/srv_protocol.rb

Overview

The URI class provides a way for users to parse the MongoDB uri as defined in the connection string format spec.

docs.mongodb.org/manual/reference/connection-string/

Examples:

Use the uri string to make a client connection.

uri = Mongo::URI.new('mongodb://localhost:27017')
client = Mongo::Client.new(uri.servers, uri.options)
client.(uri.credentials)
client[uri.database]

Since:

  • 2.0.0

Direct Known Subclasses

SRVProtocol

Defined Under Namespace

Classes: SRVProtocol

Constant Summary collapse

SCHEME =
Deprecated.

Will be removed in 3.0.

The mongodb connection string scheme.

Since:

  • 2.0.0

'mongodb://'.freeze
MONGODB_SCHEME =

The mongodb connection string scheme root.

Since:

  • 2.5.0

'mongodb'.freeze
MONGODB_SRV_SCHEME =

The mongodb srv protocol connection string scheme root.

Since:

  • 2.5.0

'mongodb+srv'.freeze
INVALID_SCHEME =

Error details for an invalid scheme.

Since:

  • 2.1.0

"Invalid scheme. Scheme must be '#{MONGODB_SCHEME}' or '#{MONGODB_SRV_SCHEME}'".freeze
FORMAT =

MongoDB URI format specification.

Since:

  • 2.0.0

'mongodb://[username:password@]host1[:port1][,host2[:port2]' +
',...[,hostN[:portN]]][/[database][?options]]'.freeze
HELP =

MongoDB URI (connection string) documentation url

Since:

  • 2.0.0

'http://docs.mongodb.org/manual/reference/connection-string/'.freeze
UNSAFE =

Unsafe characters that must be urlencoded.

Since:

  • 2.1.0

/[\:\/\+\@]/
PERCENT_CHAR =

Percent sign that must be encoded in user creds.

Since:

  • 2.5.1

/\%/
UNIX_SOCKET =

Unix socket suffix.

Since:

  • 2.1.0

/.sock/
HOST_DELIM =

The character delimiting hosts.

Since:

  • 2.1.0

','.freeze
HOST_PORT_DELIM =

The character separating a host and port.

Since:

  • 2.1.0

':'.freeze
DATABASE_DELIM =

The character delimiting a database.

Since:

  • 2.1.0

'/'.freeze
URI_OPTS_DELIM =

The character delimiting options.

Since:

  • 2.1.0

'?'.freeze
INDIV_URI_OPTS_DELIM =

The character delimiting multiple options.

Since:

  • 2.1.0

'&'.freeze
URI_OPTS_VALUE_DELIM =

The character delimiting an option and its value.

Since:

  • 2.1.0

'='.freeze
AUTH_USER_PWD_DELIM =

The character separating a username from the password.

Since:

  • 2.1.0

':'.freeze
AUTH_DELIM =

The character delimiting auth credentials.

Since:

  • 2.1.0

'@'.freeze
SCHEME_DELIM =

Scheme delimiter.

Since:

  • 2.5.0

'://'.freeze
INVALID_OPTS_VALUE_DELIM =

Error details for an invalid options format.

Since:

  • 2.1.0

"Options and their values must be delimited" +
" by '#{URI_OPTS_VALUE_DELIM}'".freeze
UNESCAPED_USER_PWD =

Error details for an non-urlencoded user name or password.

Since:

  • 2.1.0

"User name and password must be urlencoded.".freeze
UNESCAPED_UNIX_SOCKET =

Error details for a non-urlencoded unix socket path.

Since:

  • 2.1.0

"UNIX domain sockets must be urlencoded.".freeze
UNESCAPED_DATABASE =

Error details for a non-urlencoded auth database name.

Since:

  • 2.1.0

"Auth database must be urlencoded.".freeze
INVALID_OPTS_DELIM =

Error details for providing options without a database delimiter.

Since:

  • 2.1.0

"Database delimiter '#{DATABASE_DELIM}' must be present if options are specified.".freeze
INVALID_HOST =

Error details for a missing host.

Since:

  • 2.1.0

"Missing host; at least one must be provided.".freeze
INVALID_PORT =

Error details for an invalid port.

Since:

  • 2.1.0

"Invalid port. Port must be an integer greater than 0 and less than 65536".freeze
READ_MODE_MAP =

Map of URI read preference modes to Ruby driver read preference modes

Since:

  • 2.0.0

{
  'primary'            => :primary,
  'primarypreferred'   => :primary_preferred,
  'secondary'          => :secondary,
  'secondarypreferred' => :secondary_preferred,
  'nearest'            => :nearest
}.freeze
AUTH_MECH_MAP =

Map of URI authentication mechanisms to Ruby driver mechanisms

Since:

  • 2.0.0

{
  'PLAIN'        => :plain,
  # MONGODB-CR is deprecated and will be removed in driver version 3.0
  'MONGODB-CR'   => :mongodb_cr,
  'GSSAPI'       => :gssapi,
  'MONGODB-X509' => :mongodb_x509,
  'SCRAM-SHA-1'  => :scram,
  'SCRAM-SHA-256' => :scram256
}.freeze
REPEATABLE_OPTIONS =

Options that are allowed to appear more than once in the uri.

In order to follow the URI options spec requirement that all instances of 'tls' and 'ssl' have the same value, we need to keep track of all of the values passed in for those options. Assuming they don't conflict, they will be condensed to a single value immediately after parsing the URI.

Since:

  • 2.1.0

[ :tag_sets, :ssl ]

Constants included from Loggable

Loggable::PREFIX

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Loggable

#log_debug, #log_error, #log_fatal, #log_info, #log_warn, #logger

Constructor Details

#initialize(string, options = {}) ⇒ URI

Create the new uri from the provided string.

Examples:

Create the new URI.

URI.new('mongodb://localhost:27017')

Parameters:

  • string (String)

    The uri string.

  • options (Hash) (defaults to: {})

    The options.

Raises:

Since:

  • 2.0.0



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/mongo/uri.rb', line 258

def initialize(string, options = {})
  @string = string
  @options = options
  parsed_scheme, _, remaining = string.partition(SCHEME_DELIM)
  raise_invalid_error!(INVALID_SCHEME) unless parsed_scheme == scheme
  parse!(remaining)

  # The URI options spec requires that we raise an error if there are conflicting values of
  # 'tls' and 'ssl'. In order to fulfill this, we parse the values of each instance into an
  # array; assuming all values in the array are the same, we replace the array with that value.
  unless @uri_options[:ssl].nil? || @uri_options[:ssl].empty?
    unless @uri_options[:ssl].uniq.length == 1
      raise_invalid_error_no_fmt!("all instances of 'tls' and 'ssl' must have the same value")
    end

    @uri_options[:ssl] = @uri_options[:ssl].first
  end

  # Check for conflicting TLS insecure options.
  unless @uri_options[:ssl_verify].nil?
    unless @uri_options[:ssl_verify_certificate].nil?
      raise_invalid_error_no_fmt!("'tlsInsecure' and 'tlsAllowInvalidCertificates' cannot both be specified")
    end

    unless @uri_options[:ssl_verify_hostname].nil?
      raise_invalid_error_no_fmt!("tlsInsecure' and 'tlsAllowInvalidHostnames' cannot both be specified")
    end
  end
end

Instance Attribute Details

#optionsObject (readonly)

The uri parser object options.

Since:

  • 2.0.0



37
38
39
# File 'lib/mongo/uri.rb', line 37

def options
  @options
end

#serversObject (readonly)

The servers specified in the uri.

Since:

  • 2.0.0



47
48
49
# File 'lib/mongo/uri.rb', line 47

def servers
  @servers
end

#uri_optionsObject (readonly)

The options specified in the uri.

Since:

  • 2.1.0



42
43
44
# File 'lib/mongo/uri.rb', line 42

def uri_options
  @uri_options
end

Class Method Details

.get(string, opts = {}) ⇒ URI, URI::SRVProtocol

Get either a URI object or a SRVProtocol URI object.

Examples:

Get the uri object.

URI.get(string)

Returns:

Since:

  • 2.5.0



220
221
222
223
224
225
226
227
228
229
230
# File 'lib/mongo/uri.rb', line 220

def self.get(string, opts = {})
  scheme, _, remaining = string.partition(SCHEME_DELIM)
  case scheme
    when MONGODB_SCHEME
      URI.new(string, opts)
    when MONGODB_SRV_SCHEME
      SRVProtocol.new(string, opts)
    else
      raise Error::InvalidURI.new(string, INVALID_SCHEME)
  end
end

Instance Method Details

#client_optionsHash

Gets the options hash that needs to be passed to a Mongo::Client on instantiation, so we don't have to merge the credentials and database in at that point - we only have a single point here.

Examples:

Get the client options.

uri.client_options

Returns:

  • (Hash)

    The options passed to the Mongo::Client

Since:

  • 2.0.0



242
243
244
245
# File 'lib/mongo/uri.rb', line 242

def client_options
  opts = uri_options.merge(:database => database)
  @user ? opts.merge(credentials) : opts
end

#credentialsHash

Get the credentials provided in the URI.

Examples:

Get the credentials.

uri.credentials

Returns:

  • (Hash)

    The credentials.

    • :user [ String ] The user.

    • :password [ String ] The provided password.

Since:

  • 2.0.0



298
299
300
# File 'lib/mongo/uri.rb', line 298

def credentials
  { :user => @user, :password => @password }
end

#databaseString

Get the database provided in the URI.

Examples:

Get the database.

uri.database

Returns:

  • (String)

    The database.

Since:

  • 2.0.0



310
311
312
# File 'lib/mongo/uri.rb', line 310

def database
  @database ? @database : Database::ADMIN
end