forked from mongodb/mongoid
/
indexes.rb
105 lines (95 loc) · 2.84 KB
/
indexes.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# encoding: utf-8
require "mongoid/indexes/validators/options"
module Mongoid
module Indexes
extend ActiveSupport::Concern
included do
cattr_accessor :index_options
self.index_options = {}
end
module ClassMethods
# Send the actual index creation comments to the MongoDB driver
#
# @example Create the indexes for the class.
# Person.create_indexes
#
# @return [ true ] If the operation succeeded.
#
# @since 1.0.0
def create_indexes
return unless index_options
index_options.each_pair do |spec, options|
collection.indexes.create(spec, options)
end and true
end
# Send the actual index removal comments to the MongoDB driver,
# but lets _id untouched.
#
# @example Remove the indexes for the class.
# Person.remove_indexes
#
# @return [ true ] If the operation succeeded.
#
# @since 3.0.0
def remove_indexes
collection.indexes.each do |spec|
next if spec["name"] == "_id_"
collection.indexes.drop(spec["key"])
end and true
end
# Add the default indexes to the root document if they do not already
# exist. Currently this is only _type.
#
# @example Add Mongoid internal indexes.
# Person.add_indexes
#
# @return [ true ] If the operation succeeded.
#
# @since 1.0.0
def add_indexes
if hereditary? && !index_options[{ _type: 1 }]
index({ _type: 1 }, { unique: false, background: true })
end
true
end
# Adds an index on the field specified. Options can be :unique => true or
# :unique => false. It will default to the latter.
#
# @example Create a basic index.
# class Person
# include Mongoid::Document
# field :name, type: String
# index({ name: 1 }, { background: true })
# end
#
# @param [ Symbol ] name The name of the field.
# @param [ Hash ] options The index options.
#
# @return [ Hash ] The index options.
#
# @since 1.0.0
def index(spec, options = nil)
Validators::Options.validate(self, spec, options || {})
index_options[spec] = normalize_index_options(options)
end
private
# Normalize the index options, if any are provided.
#
# @api private
#
# @example Normalize the index options.
# Model.normalize_index_options(drop_dups: true)
#
# @param [ Hash ] options The index options.
#
# @return [ Hash ] The normalized options.
#
# @since 3.0.0
def normalize_index_options(options)
opts = options || {}
opts[:dropDups] = opts.delete(:drop_dups) if opts.has_key?(:drop_dups)
opts
end
end
end
end