Skip to content

Commit fedbb1e

Browse files
author
Brandon Black
committed
improvement: clean-up of db, lots-o-improvements
1 parent d55f564 commit fedbb1e

File tree

1 file changed

+69
-83
lines changed

1 file changed

+69
-83
lines changed

lib/mongo/db.rb

Lines changed: 69 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,12 @@ class DB
1414
SYSTEM_JS_COLLECTION = 'system.js'
1515
SYSTEM_COMMAND_COLLECTION = '$cmd'
1616

17+
PROFILE_LEVEL = {
18+
:off => 0,
19+
:slow_only => 1,
20+
:all => 2
21+
}
22+
1723
# Counter for generating unique request ids.
1824
@@current_request_id = 0
1925

@@ -59,8 +65,9 @@ def strict?
5965
# @param [Mongo::MongoClient] client a connection object pointing to MongoDB. Note
6066
# that databases are usually instantiated via the MongoClient class. See the examples below.
6167
#
62-
# @option opts [Boolean] :strict (False) If true, collections must exist to be accessed and must
63-
# not exist to be created. See DB#collection and DB#create_collection.
68+
# @option opts [Boolean] :strict (False) [DEPRECATED] If true, collections existence checks are
69+
# performed during a number of relevant operations. See DB#collection, DB#create_collection and
70+
# DB#drop_collection.
6471
#
6572
# @option opts [Object, #create_pk(doc)] :pk (BSON::ObjectId) A primary key factory object,
6673
# which should take a hash and return a hash which merges the original hash with any primary key
@@ -138,17 +145,15 @@ def issue_authentication(username, password, save_auth=true, opts={})
138145
auth['nonce'] = nonce
139146
auth['key'] = Mongo::Support.auth_key(username, password, nonce)
140147
if ok?(doc = self.command(auth, :check_response => false, :socket => opts[:socket]))
141-
if save_auth
142-
@connection.add_auth(@name, username, password)
143-
end
144-
true
148+
@connection.add_auth(@name, username, password) if save_auth
145149
else
146150
message = "Failed to authenticate user '#{username}' on db '#{self.name}'"
147151
raise Mongo::AuthenticationError.new(message, doc['code'], doc)
148152
end
153+
true
149154
end
150155

151-
# Adds a stored Javascript function to the database which can executed
156+
# Adds a stored Javascript function to the database which can executed
152157
# server-side in map_reduce, db.eval and $where clauses.
153158
#
154159
# @param [String] function_name
@@ -158,7 +163,7 @@ def issue_authentication(username, password, save_auth=true, opts={})
158163
def add_stored_function(function_name, code)
159164
self[SYSTEM_JS_COLLECTION].save(
160165
{
161-
"_id" => function_name,
166+
"_id" => function_name,
162167
:value => BSON::Code.new(code)
163168
}
164169
)
@@ -171,11 +176,8 @@ def add_stored_function(function_name, code)
171176
#
172177
# @return [Boolean]
173178
def remove_stored_function(function_name)
174-
if self[SYSTEM_JS_COLLECTION].find_one({"_id" => function_name})
175-
self[SYSTEM_JS_COLLECTION].remove({"_id" => function_name}, :w => 1)
176-
else
177-
return false
178-
end
179+
return false unless self[SYSTEM_JS_COLLECTION].find_one({"_id" => function_name})
180+
self[SYSTEM_JS_COLLECTION].remove({"_id" => function_name}, :w => 1)
179181
end
180182

181183
# Adds a user to this database for use with authentication. If the user already
@@ -193,7 +195,7 @@ def add_user(username, password, read_only = false)
193195
user['pwd'] = Mongo::Support.hash_password(username, password)
194196
user['readOnly'] = true if read_only;
195197
users.save(user)
196-
return user
198+
user
197199
end
198200

199201
# Remove the given user from this database. Returns false if the user
@@ -206,7 +208,7 @@ def remove_user(username)
206208
if self[SYSTEM_USER_COLLECTION].find_one({:user => username})
207209
self[SYSTEM_USER_COLLECTION].remove({:user => username}, :w => 1)
208210
else
209-
return false
211+
false
210212
end
211213
end
212214

@@ -225,10 +227,10 @@ def logout(opts={})
225227
def issue_logout(opts={})
226228
if ok?(doc = command({:logout => 1}, :socket => opts[:socket]))
227229
@connection.remove_auth(@name)
228-
true
229230
else
230-
raise MongoDBError, "error logging out: #{doc.inspect}"
231+
raise MongoDBError, "Error logging out: #{doc.inspect}"
231232
end
233+
true
232234
end
233235

234236
# Get an array of collection names in this database.
@@ -330,7 +332,7 @@ def collection(name, opts={})
330332
def drop_collection(name)
331333
return false if strict? && !collection_names.include?(name.to_s)
332334
begin
333-
ok?(command(:drop => name, :check_response => false))
335+
ok?(command(:drop => name))
334336
rescue OperationFailure => e
335337
false
336338
end
@@ -351,7 +353,7 @@ def get_last_error(opts={})
351353
cmd[:getlasterror] = 1
352354
cmd.merge!(opts)
353355
doc = command(cmd, :check_response => false)
354-
raise MongoDBError, "error retrieving last error: #{doc.inspect}" unless ok?(doc)
356+
raise MongoDBError, "Error retrieving last error: #{doc.inspect}" unless ok?(doc)
355357
doc
356358
end
357359

@@ -371,11 +373,7 @@ def error?
371373
# @return [String, Nil] the text of the error or +nil+ if no error has occurred.
372374
def previous_error
373375
error = command(:getpreverror => 1)
374-
if error["err"]
375-
error
376-
else
377-
nil
378-
end
376+
error["err"] ? error : nil
379377
end
380378

381379
# Reset the error history of this database
@@ -402,19 +400,19 @@ def dereference(dbref)
402400
# Evaluate a JavaScript expression in MongoDB.
403401
#
404402
# @param [String, Code] code a JavaScript expression to evaluate server-side.
405-
# @param [Integer, Hash] args any additional argument to be passed to the +code+ expression when
403+
# @param [Integer, Hash] args any additional argument to be passed to the +code+ expression when
406404
# it's run on the server.
407405
#
408406
# @return [String] the return value of the function.
409407
def eval(code, *args)
410-
if not code.is_a? BSON::Code
408+
unless code.is_a?(BSON::Code)
411409
code = BSON::Code.new(code)
412410
end
413411

414-
oh = BSON::OrderedHash.new
415-
oh[:$eval] = code
416-
oh[:args] = args
417-
doc = command(oh)
412+
cmd = BSON::OrderedHash.new
413+
cmd[:$eval] = code
414+
cmd[:args] = args
415+
doc = command(cmd)
418416
doc['retval']
419417
end
420418

@@ -427,10 +425,10 @@ def eval(code, *args)
427425
#
428426
# @raise MongoDBError if there's an error renaming the collection.
429427
def rename_collection(from, to)
430-
oh = BSON::OrderedHash.new
431-
oh[:renameCollection] = "#{@name}.#{from}"
432-
oh[:to] = "#{@name}.#{to}"
433-
doc = DB.new('admin', @connection).command(oh, :check_response => false)
428+
cmd = BSON::OrderedHash.new
429+
cmd[:renameCollection] = "#{@name}.#{from}"
430+
cmd[:to] = "#{@name}.#{to}"
431+
doc = DB.new('admin', @connection).command(cmd, :check_response => false)
434432
ok?(doc) || raise(MongoDBError, "Error renaming collection: #{doc.inspect}")
435433
end
436434

@@ -444,10 +442,10 @@ def rename_collection(from, to)
444442
#
445443
# @raise MongoDBError if there's an error dropping the index.
446444
def drop_index(collection_name, index_name)
447-
oh = BSON::OrderedHash.new
448-
oh[:deleteIndexes] = collection_name
449-
oh[:index] = index_name.to_s
450-
doc = command(oh, :check_response => false)
445+
cmd = BSON::OrderedHash.new
446+
cmd[:deleteIndexes] = collection_name
447+
cmd[:index] = index_name.to_s
448+
doc = command(cmd, :check_response => false)
451449
ok?(doc) || raise(MongoDBError, "Error with drop_index command: #{doc.inspect}")
452450
end
453451

@@ -508,8 +506,9 @@ def ok?(doc)
508506
# @core commands command_instance-method
509507
def command(selector, opts={})
510508
check_response = opts.fetch(:check_response, true)
511-
socket = opts[:socket]
512-
raise MongoArgumentError, "command must be given a selector" unless selector.is_a?(Hash) && !selector.empty?
509+
socket = opts[:socket]
510+
raise MongoArgumentError, "Command must be given a selector" unless selector.is_a?(Hash) && !selector.empty?
511+
513512
if selector.keys.length > 1 && RUBY_VERSION < '1.9' && selector.class != BSON::OrderedHash
514513
raise MongoArgumentError, "DB#command requires an OrderedHash when hash contains multiple keys"
515514
end
@@ -522,29 +521,31 @@ def command(selector, opts={})
522521
end
523522

524523
begin
525-
result = Cursor.new(system_command_collection,
526-
:limit => -1,
527-
:selector => selector,
528-
:socket => socket,
529-
:read => read_pref,
530-
:comment => opts[:comment]).next_document
524+
result = Cursor.new(
525+
system_command_collection,
526+
:limit => -1,
527+
:selector => selector,
528+
:socket => socket,
529+
:read => read_pref,
530+
:comment => opts[:comment]).next_document
531531
rescue OperationFailure => ex
532532
raise OperationFailure, "Database command '#{selector.keys.first}' failed: #{ex.message}"
533533
end
534534

535-
if result.nil?
536-
raise OperationFailure, "Database command '#{selector.keys.first}' failed: returned null."
537-
elsif (check_response && !ok?(result))
535+
raise OperationFailure,
536+
"Database command '#{selector.keys.first}' failed: returned null." unless result
537+
538+
if check_response && !ok?(result)
538539
message = "Database command '#{selector.keys.first}' failed: ("
539540
message << result.map do |key, value|
540541
"#{key}: '#{value}'"
541542
end.join('; ')
542543
message << ').'
543544
code = result['code'] || result['assertionCode']
544545
raise OperationFailure.new(message, code, result)
545-
else
546-
result
547546
end
547+
548+
result
548549
end
549550

550551
# A shortcut returning db plus dot plus collection name.
@@ -567,9 +568,8 @@ def pk_factory
567568
#
568569
# @raise [MongoArgumentError] if the primary key factory has already been set.
569570
def pk_factory=(pk_factory)
570-
if @pk_factory
571-
raise MongoArgumentError, "Cannot change primary key factory once it's been set"
572-
end
571+
raise MongoArgumentError,
572+
"Cannot change primary key factory once it's been set" if @pk_factory
573573

574574
@pk_factory = pk_factory
575575
end
@@ -581,39 +581,25 @@ def pk_factory=(pk_factory)
581581
#
582582
# @core profiling profiling_level-instance_method
583583
def profiling_level
584-
oh = BSON::OrderedHash.new
585-
oh[:profile] = -1
586-
doc = command(oh, :check_response => false)
587-
raise "Error with profile command: #{doc.inspect}" unless ok?(doc) && doc['was'].kind_of?(Numeric)
588-
case doc['was'].to_i
589-
when 0
590-
:off
591-
when 1
592-
:slow_only
593-
when 2
594-
:all
595-
else
596-
raise "Error: illegal profiling level value #{doc['was']}"
597-
end
584+
cmd = BSON::OrderedHash.new
585+
cmd[:profile] = -1
586+
doc = command(cmd, :check_response => false)
587+
588+
raise "Error with profile command: #{doc.inspect}" unless ok?(doc)
589+
590+
level_sym = PROFILE_LEVEL.invert[doc['was'].to_i]
591+
raise "Error: illegal profiling level value #{doc['was']}" unless level_sym
592+
level_sym
598593
end
599594

600595
# Set this database's profiling level. If profiling is enabled, you can
601596
# get the results using DB#profiling_info.
602597
#
603598
# @param [Symbol] level acceptable options are +:off+, +:slow_only+, or +:all+.
604599
def profiling_level=(level)
605-
oh = BSON::OrderedHash.new
606-
oh[:profile] = case level
607-
when :off
608-
0
609-
when :slow_only
610-
1
611-
when :all
612-
2
613-
else
614-
raise "Error: illegal profiling level value #{level}"
615-
end
616-
doc = command(oh, :check_response => false)
600+
cmd = BSON::OrderedHash.new
601+
cmd[:profile] = PROFILE_LEVEL[level]
602+
doc = command(cmd, :check_response => false)
617603
ok?(doc) || raise(MongoDBError, "Error with profile command: #{doc.inspect}")
618604
end
619605

@@ -637,9 +623,9 @@ def validate_collection(name)
637623
cmd[:validate] = name
638624
cmd[:full] = true
639625
doc = command(cmd, :check_response => false)
640-
if !ok?(doc)
641-
raise MongoDBError, "Error with validate command: #{doc.inspect}"
642-
end
626+
627+
raise MongoDBError, "Error with validate command: #{doc.inspect}" unless ok?(doc)
628+
643629
if (doc.has_key?('valid') && !doc['valid']) || (doc['result'] =~ /\b(exception|corrupt)\b/i)
644630
raise MongoDBError, "Error: invalid collection #{name}: #{doc.inspect}"
645631
end

0 commit comments

Comments
 (0)