Convert a legacy write result to write command format.
(
operation: str, command: Mapping[str, Any], result: Mapping[str, Any]
)
| 153 | |
| 154 | |
| 155 | def _convert_write_result( |
| 156 | operation: str, command: Mapping[str, Any], result: Mapping[str, Any] |
| 157 | ) -> dict[str, Any]: |
| 158 | """Convert a legacy write result to write command format.""" |
| 159 | # Based on _merge_legacy from bulk.py |
| 160 | affected = result.get("n", 0) |
| 161 | res = {"ok": 1, "n": affected} |
| 162 | errmsg = result.get("errmsg", result.get("err", "")) |
| 163 | if errmsg: |
| 164 | # The write was successful on at least the primary so don't return. |
| 165 | if result.get("wtimeout"): |
| 166 | res["writeConcernError"] = {"errmsg": errmsg, "code": 64, "errInfo": {"wtimeout": True}} |
| 167 | else: |
| 168 | # The write failed. |
| 169 | error = {"index": 0, "code": result.get("code", 8), "errmsg": errmsg} |
| 170 | if "errInfo" in result: |
| 171 | error["errInfo"] = result["errInfo"] |
| 172 | res["writeErrors"] = [error] |
| 173 | return res |
| 174 | if operation == "insert": |
| 175 | # GLE result for insert is always 0 in most MongoDB versions. |
| 176 | res["n"] = len(command["documents"]) |
| 177 | elif operation == "update": |
| 178 | if "upserted" in result: |
| 179 | res["upserted"] = [{"index": 0, "_id": result["upserted"]}] |
| 180 | # Versions of MongoDB before 2.6 don't return the _id for an |
| 181 | # upsert if _id is not an ObjectId. |
| 182 | elif result.get("updatedExisting") is False and affected == 1: |
| 183 | # If _id is in both the update document *and* the query spec |
| 184 | # the update document _id takes precedence. |
| 185 | update = command["updates"][0] |
| 186 | _id = update["u"].get("_id", update["q"].get("_id")) |
| 187 | res["upserted"] = [{"index": 0, "_id": _id}] |
| 188 | return res |
| 189 | |
| 190 | |
| 191 | _OPTIONS = { |
no test coverage detected