~ubuntu-branches/ubuntu/wily/pymongo/wily-proposed

« back to all changes in this revision

Viewing changes to pymongo/operations.py

  • Committer: Package Import Robot
  • Author(s): Federico Ceratto
  • Date: 2015-04-26 22:43:13 UTC
  • mfrom: (24.1.5 sid)
  • Revision ID: package-import@ubuntu.com-20150426224313-0hga2jphvf0rrmfe
Tags: 3.0.1-1
New upstream release.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2015 MongoDB, Inc.
 
2
#
 
3
# Licensed under the Apache License, Version 2.0 (the "License");
 
4
# you may not use this file except in compliance with the License.
 
5
# You may obtain a copy of the License at
 
6
#
 
7
# http://www.apache.org/licenses/LICENSE-2.0
 
8
#
 
9
# Unless required by applicable law or agreed to in writing, software
 
10
# distributed under the License is distributed on an "AS IS" BASIS,
 
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
12
# See the License for the specific language governing permissions and
 
13
# limitations under the License.
 
14
 
 
15
"""Operation class definitions."""
 
16
 
 
17
from pymongo.common import validate_boolean, validate_is_mapping
 
18
from pymongo.helpers import _gen_index_name, _index_document, _index_list
 
19
 
 
20
 
 
21
class _WriteOp(object):
 
22
    """Private base class for all write operations."""
 
23
 
 
24
    __slots__ = ("_filter", "_doc", "_upsert")
 
25
 
 
26
    def __init__(self, filter=None, doc=None, upsert=None):
 
27
        if filter is not None:
 
28
            validate_is_mapping("filter", filter)
 
29
        if upsert is not None:
 
30
            validate_boolean("upsert", upsert)
 
31
        self._filter = filter
 
32
        self._doc = doc
 
33
        self._upsert = upsert
 
34
 
 
35
 
 
36
class InsertOne(_WriteOp):
 
37
    """Represents an insert_one operation."""
 
38
 
 
39
    def __init__(self, document):
 
40
        """Create an InsertOne instance.
 
41
 
 
42
        For use with :meth:`~pymongo.collection.Collection.bulk_write`.
 
43
 
 
44
        :Parameters:
 
45
          - `document`: The document to insert. If the document is missing an
 
46
            _id field one will be added.
 
47
        """
 
48
        super(InsertOne, self).__init__(doc=document)
 
49
 
 
50
    def _add_to_bulk(self, bulkobj):
 
51
        """Add this operation to the _Bulk instance `bulkobj`."""
 
52
        bulkobj.add_insert(self._doc)
 
53
 
 
54
    def __repr__(self):
 
55
        return "InsertOne(%r)" % (self._doc,)
 
56
 
 
57
 
 
58
class DeleteOne(_WriteOp):
 
59
    """Represents a delete_one operation."""
 
60
 
 
61
    def __init__(self, filter):
 
62
        """Create a DeleteOne instance.
 
63
 
 
64
        For use with :meth:`~pymongo.collection.Collection.bulk_write`.
 
65
 
 
66
        :Parameters:
 
67
          - `filter`: A query that matches the document to delete.
 
68
        """
 
69
        super(DeleteOne, self).__init__(filter)
 
70
 
 
71
    def _add_to_bulk(self, bulkobj):
 
72
        """Add this operation to the _Bulk instance `bulkobj`."""
 
73
        bulkobj.add_delete(self._filter, 1)
 
74
 
 
75
    def __repr__(self):
 
76
        return "DeleteOne(%r)" % (self._filter,)
 
77
 
 
78
 
 
79
class DeleteMany(_WriteOp):
 
80
    """Represents a delete_many operation."""
 
81
 
 
82
    def __init__(self, filter):
 
83
        """Create a DeleteMany instance.
 
84
 
 
85
        For use with :meth:`~pymongo.collection.Collection.bulk_write`.
 
86
 
 
87
        :Parameters:
 
88
          - `filter`: A query that matches the documents to delete.
 
89
        """
 
90
        super(DeleteMany, self).__init__(filter)
 
91
 
 
92
    def _add_to_bulk(self, bulkobj):
 
93
        """Add this operation to the _Bulk instance `bulkobj`."""
 
94
        bulkobj.add_delete(self._filter, 0)
 
95
 
 
96
    def __repr__(self):
 
97
        return "DeleteMany(%r)" % (self._filter,)
 
98
 
 
99
 
 
100
class ReplaceOne(_WriteOp):
 
101
    """Represents a replace_one operation."""
 
102
 
 
103
    def __init__(self, filter, replacement, upsert=False):
 
104
        """Create a ReplaceOne instance.
 
105
 
 
106
        For use with :meth:`~pymongo.collection.Collection.bulk_write`.
 
107
 
 
108
        :Parameters:
 
109
          - `filter`: A query that matches the document to replace.
 
110
          - `replacement`: The new document.
 
111
          - `upsert` (optional): If ``True``, perform an insert if no documents
 
112
            match the filter.
 
113
        """
 
114
        super(ReplaceOne, self).__init__(filter, replacement, upsert)
 
115
 
 
116
    def _add_to_bulk(self, bulkobj):
 
117
        """Add this operation to the _Bulk instance `bulkobj`."""
 
118
        bulkobj.add_replace(self._filter, self._doc, self._upsert)
 
119
 
 
120
    def __repr__(self):
 
121
        return "ReplaceOne(%r, %r, %r)" % (self._filter,
 
122
                                           self._doc,
 
123
                                           self._upsert)
 
124
 
 
125
 
 
126
class UpdateOne(_WriteOp):
 
127
    """Represents an update_one operation."""
 
128
 
 
129
    def __init__(self, filter, update, upsert=False):
 
130
        """Represents an update_one operation.
 
131
 
 
132
        For use with :meth:`~pymongo.collection.Collection.bulk_write`.
 
133
 
 
134
        :Parameters:
 
135
          - `filter`: A query that matches the document to update.
 
136
          - `update`: The modifications to apply.
 
137
          - `upsert` (optional): If ``True``, perform an insert if no documents
 
138
            match the filter.
 
139
        """
 
140
        super(UpdateOne, self).__init__(filter, update, upsert)
 
141
 
 
142
    def _add_to_bulk(self, bulkobj):
 
143
        """Add this operation to the _Bulk instance `bulkobj`."""
 
144
        bulkobj.add_update(self._filter, self._doc, False, self._upsert)
 
145
 
 
146
    def __repr__(self):
 
147
        return "UpdateOne(%r, %r, %r)" % (self._filter,
 
148
                                          self._doc,
 
149
                                          self._upsert)
 
150
 
 
151
 
 
152
class UpdateMany(_WriteOp):
 
153
    """Represents an update_many operation."""
 
154
 
 
155
    def __init__(self, filter, update, upsert=False):
 
156
        """Create an UpdateMany instance.
 
157
 
 
158
        For use with :meth:`~pymongo.collection.Collection.bulk_write`.
 
159
 
 
160
        :Parameters:
 
161
          - `filter`: A query that matches the documents to update.
 
162
          - `update`: The modifications to apply.
 
163
          - `upsert` (optional): If ``True``, perform an insert if no documents
 
164
            match the filter.
 
165
        """
 
166
        super(UpdateMany, self).__init__(filter, update, upsert)
 
167
 
 
168
    def _add_to_bulk(self, bulkobj):
 
169
        """Add this operation to the _Bulk instance `bulkobj`."""
 
170
        bulkobj.add_update(self._filter, self._doc, True, self._upsert)
 
171
 
 
172
    def __repr__(self):
 
173
        return "UpdateMany(%r, %r, %r)" % (self._filter,
 
174
                                           self._doc,
 
175
                                           self._upsert)
 
176
 
 
177
 
 
178
class IndexModel(object):
 
179
    """Represents an index to create."""
 
180
 
 
181
    __slots__ = ("__document",)
 
182
 
 
183
    def __init__(self, keys, **kwargs):
 
184
        """Create an Index instance.
 
185
 
 
186
        For use with :meth:`~pymongo.collection.Collection.create_indexes`.
 
187
 
 
188
        Takes either a single key or a list of (key, direction) pairs.
 
189
        The key(s) must be an instance of :class:`basestring`
 
190
        (:class:`str` in python 3), and the direction(s) must be one of
 
191
        (:data:`~pymongo.ASCENDING`, :data:`~pymongo.DESCENDING`,
 
192
        :data:`~pymongo.GEO2D`, :data:`~pymongo.GEOHAYSTACK`,
 
193
        :data:`~pymongo.GEOSPHERE`, :data:`~pymongo.HASHED`,
 
194
        :data:`~pymongo.TEXT`).
 
195
 
 
196
        Valid options include, but are not limited to:
 
197
 
 
198
          - `name`: custom name to use for this index - if none is
 
199
            given, a name will be generated.
 
200
          - `unique`: if ``True`` creates a uniqueness constraint on the index.
 
201
          - `background`: if ``True`` this index should be created in the
 
202
            background.
 
203
          - `sparse`: if ``True``, omit from the index any documents that lack
 
204
            the indexed field.
 
205
          - `bucketSize`: for use with geoHaystack indexes.
 
206
            Number of documents to group together within a certain proximity
 
207
            to a given longitude and latitude.
 
208
          - `min`: minimum value for keys in a :data:`~pymongo.GEO2D`
 
209
            index.
 
210
          - `max`: maximum value for keys in a :data:`~pymongo.GEO2D`
 
211
            index.
 
212
          - `expireAfterSeconds`: <int> Used to create an expiring (TTL)
 
213
            collection. MongoDB will automatically delete documents from
 
214
            this collection after <int> seconds. The indexed field must
 
215
            be a UTC datetime or the data will not expire.
 
216
 
 
217
        See the MongoDB documentation for a full list of supported options by
 
218
        server version.
 
219
 
 
220
        :Parameters:
 
221
          - `keys`: a single key or a list of (key, direction)
 
222
            pairs specifying the index to create
 
223
          - `**kwargs` (optional): any additional index creation
 
224
            options (see the above list) should be passed as keyword
 
225
            arguments
 
226
        """
 
227
        keys = _index_list(keys)
 
228
        if "name" not in kwargs:
 
229
            kwargs["name"] = _gen_index_name(keys)
 
230
        kwargs["key"] = _index_document(keys)
 
231
        self.__document = kwargs
 
232
 
 
233
    @property
 
234
    def document(self):
 
235
        """An index document suitable for passing to the createIndexes
 
236
        command.
 
237
        """
 
238
        return self.__document