|
| 1 | +# Copyright 2019-present MongoDB, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); you |
| 4 | +# may not use this file except in compliance with the License. You |
| 5 | +# 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 |
| 12 | +# implied. See the License for the specific language governing |
| 13 | +# permissions and limitations under the License. |
| 14 | + |
| 15 | +"""Perform aggregation operations on a collection or database.""" |
| 16 | + |
| 17 | +from bson.son import SON |
| 18 | + |
| 19 | +from pymongo import common |
| 20 | +from pymongo.collation import validate_collation_or_none |
| 21 | +from pymongo.errors import ConfigurationError |
| 22 | + |
| 23 | + |
| 24 | +class _AggregationCommand(object): |
| 25 | + """The internal abstract base class for aggregation cursors. |
| 26 | +
|
| 27 | + Should not be called directly by application developers. Use |
| 28 | + :meth:`pymongo.collection.Collection.aggregate`, or |
| 29 | + :meth:`pymongo.database.Database.aggregate` instead. |
| 30 | + """ |
| 31 | + def __init__(self, target, cursor_class, pipeline, options, |
| 32 | + explicit_session, user_fields=None, result_processor=None): |
| 33 | + if "explain" in options: |
| 34 | + raise ConfigurationError("The explain option is not supported. " |
| 35 | + "Use Database.command instead.") |
| 36 | + |
| 37 | + self._target = target |
| 38 | + |
| 39 | + common.validate_list('pipeline', pipeline) |
| 40 | + self._pipeline = pipeline |
| 41 | + |
| 42 | + common.validate_is_mapping('options', options) |
| 43 | + self._options = options |
| 44 | + |
| 45 | + self._cursor_class = cursor_class |
| 46 | + self._explicit_session = explicit_session |
| 47 | + self._user_fields = user_fields |
| 48 | + self._result_processor = result_processor |
| 49 | + |
| 50 | + self._collation = validate_collation_or_none( |
| 51 | + options.pop('collation', None)) |
| 52 | + |
| 53 | + self._max_await_time_ms = options.pop('maxAwaitTimeMS', None) |
| 54 | + self._batch_size = common.validate_non_negative_integer_or_none( |
| 55 | + "batchSize", options.pop("batchSize", None)) |
| 56 | + |
| 57 | + self._dollar_out = (self._pipeline and |
| 58 | + '$out' in self._pipeline[-1]) |
| 59 | + |
| 60 | + @property |
| 61 | + def _aggregation_target(self): |
| 62 | + """The argument to pass to the aggregate command.""" |
| 63 | + raise NotImplementedError |
| 64 | + |
| 65 | + @property |
| 66 | + def _cursor_namespace(self): |
| 67 | + """The namespace in which the aggregate command is run.""" |
| 68 | + raise NotImplementedError |
| 69 | + |
| 70 | + @property |
| 71 | + def _database(self): |
| 72 | + """The database against which the aggregation command is run.""" |
| 73 | + raise NotImplementedError |
| 74 | + |
| 75 | + @staticmethod |
| 76 | + def _check_compat(sock_info): |
| 77 | + """Check whether the server version in-use supports aggregation.""" |
| 78 | + pass |
| 79 | + |
| 80 | + def _process_result(self, result, session, server, sock_info, slave_ok): |
| 81 | + if self._result_processor: |
| 82 | + self._result_processor( |
| 83 | + result, session, server, sock_info, slave_ok) |
| 84 | + |
| 85 | + def get_cursor(self, session, server, sock_info, slave_ok): |
| 86 | + # Ensure command compatibility. |
| 87 | + self._check_compat(sock_info) |
| 88 | + |
| 89 | + # Serialize command. |
| 90 | + cmd = SON([("aggregate", self._aggregation_target), |
| 91 | + ("pipeline", self._pipeline)]) |
| 92 | + cmd.update(self._options) |
| 93 | + |
| 94 | + # Cache read preference for easy access. |
| 95 | + read_preference = self._target._read_preference_for(session) |
| 96 | + |
| 97 | + # Apply this target's read concern if: |
| 98 | + # readConcern has not been specified as a kwarg and either |
| 99 | + # - server version is >= 4.2 or |
| 100 | + # - server version is >= 3.2 and pipeline doesn't use $out |
| 101 | + if (('readConcern' not in cmd) and |
| 102 | + ((sock_info.max_wire_version >= 4 and not self._dollar_out) or |
| 103 | + (sock_info.max_wire_version >= 8))): |
| 104 | + read_concern = self._target.read_concern |
| 105 | + else: |
| 106 | + read_concern = None |
| 107 | + |
| 108 | + # Apply this target's write concern if: |
| 109 | + # writeConcern has not been specified as a kwarg and pipeline doesn't |
| 110 | + # use $out |
| 111 | + if 'writeConcern' not in cmd and self._dollar_out: |
| 112 | + write_concern = self._target._write_concern_for(session) |
| 113 | + else: |
| 114 | + write_concern = None |
| 115 | + |
| 116 | + # Run command. |
| 117 | + result = sock_info.command( |
| 118 | + self._database.name, |
| 119 | + cmd, |
| 120 | + slave_ok, |
| 121 | + read_preference, |
| 122 | + self._target.codec_options, |
| 123 | + parse_write_concern_error=True, |
| 124 | + read_concern=read_concern, |
| 125 | + write_concern=write_concern, |
| 126 | + collation=self._collation, |
| 127 | + session=session, |
| 128 | + client=self._database.client, |
| 129 | + user_fields=self._user_fields) |
| 130 | + |
| 131 | + self._process_result(result, session, server, sock_info, slave_ok) |
| 132 | + |
| 133 | + # Extract cursor from result or mock/fake one if necessary. |
| 134 | + if 'cursor' in result: |
| 135 | + cursor = result['cursor'] |
| 136 | + else: |
| 137 | + # Pre-MongoDB 2.6 or unacknowledged write. Fake a cursor. |
| 138 | + cursor = { |
| 139 | + "id": 0, |
| 140 | + "firstBatch": result.get("result", []), |
| 141 | + "ns": self._cursor_namespace, |
| 142 | + } |
| 143 | + |
| 144 | + # Get collection to target with cursor. |
| 145 | + ns = cursor["ns"] |
| 146 | + _, collname = ns.split(".", 1) |
| 147 | + aggregation_collection = self._database.get_collection( |
| 148 | + collname, codec_options=self._target.codec_options, |
| 149 | + read_preference=read_preference, |
| 150 | + write_concern=self._target.write_concern, |
| 151 | + read_concern=self._target.read_concern) |
| 152 | + |
| 153 | + # Create and return cursor instance. |
| 154 | + return self._cursor_class( |
| 155 | + aggregation_collection, cursor, sock_info.address, |
| 156 | + batch_size=self._batch_size or 0, |
| 157 | + max_await_time_ms=self._max_await_time_ms, |
| 158 | + session=session, explicit_session=self._explicit_session) |
| 159 | + |
| 160 | + |
| 161 | +class _CollectionAggregationCommand(_AggregationCommand): |
| 162 | + @property |
| 163 | + def _aggregation_target(self): |
| 164 | + return self._target.name |
| 165 | + |
| 166 | + @property |
| 167 | + def _cursor_namespace(self): |
| 168 | + return self._target.full_name |
| 169 | + |
| 170 | + @property |
| 171 | + def _database(self): |
| 172 | + return self._target.database |
| 173 | + |
| 174 | + |
| 175 | +class _DatabaseAggregationCommand(_AggregationCommand): |
| 176 | + @property |
| 177 | + def _aggregation_target(self): |
| 178 | + return 1 |
| 179 | + |
| 180 | + @property |
| 181 | + def _cursor_namespace(self): |
| 182 | + return "%s.%s.aggregate" % (self._target.name, "$cmd") |
| 183 | + |
| 184 | + @property |
| 185 | + def _database(self): |
| 186 | + return self._target |
| 187 | + |
| 188 | + @staticmethod |
| 189 | + def _check_compat(sock_info): |
| 190 | + # Older server version don't raise a descriptive error, so we raise |
| 191 | + # one instead. |
| 192 | + if not sock_info.max_wire_version >= 6: |
| 193 | + err_msg = "Database.aggregation is only supported on MongoDB 3.6+." |
| 194 | + raise ConfigurationError(err_msg) |
0 commit comments