binary.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. # Copyright 2009-present 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. from uuid import UUID
  15. from warnings import warn
  16. from bson.py3compat import PY3
  17. """Tools for representing BSON binary data.
  18. """
  19. BINARY_SUBTYPE = 0
  20. """BSON binary subtype for binary data.
  21. This is the default subtype for binary data.
  22. """
  23. FUNCTION_SUBTYPE = 1
  24. """BSON binary subtype for functions.
  25. """
  26. OLD_BINARY_SUBTYPE = 2
  27. """Old BSON binary subtype for binary data.
  28. This is the old default subtype, the current
  29. default is :data:`BINARY_SUBTYPE`.
  30. """
  31. OLD_UUID_SUBTYPE = 3
  32. """Old BSON binary subtype for a UUID.
  33. :class:`uuid.UUID` instances will automatically be encoded
  34. by :mod:`bson` using this subtype.
  35. .. versionadded:: 2.1
  36. """
  37. UUID_SUBTYPE = 4
  38. """BSON binary subtype for a UUID.
  39. This is the new BSON binary subtype for UUIDs. The
  40. current default is :data:`OLD_UUID_SUBTYPE`.
  41. .. versionchanged:: 2.1
  42. Changed to subtype 4.
  43. """
  44. class UuidRepresentation:
  45. UNSPECIFIED = 0
  46. """An unspecified UUID representation.
  47. When configured, :class:`uuid.UUID` instances will **not** be
  48. automatically encoded to or decoded from :class:`~bson.binary.Binary`.
  49. When encoding a :class:`uuid.UUID` instance, an error will be raised.
  50. To encode a :class:`uuid.UUID` instance with this configuration, it must
  51. be wrapped in the :class:`~bson.binary.Binary` class by the application
  52. code. When decoding a BSON binary field with a UUID subtype, a
  53. :class:`~bson.binary.Binary` instance will be returned instead of a
  54. :class:`uuid.UUID` instance.
  55. See :ref:`unspecified-representation-details` for details.
  56. .. versionadded:: 3.11
  57. """
  58. STANDARD = UUID_SUBTYPE
  59. """The standard UUID representation.
  60. :class:`uuid.UUID` instances will automatically be encoded to
  61. and decoded from BSON binary, using RFC-4122 byte order with
  62. binary subtype :data:`UUID_SUBTYPE`.
  63. See :ref:`standard-representation-details` for details.
  64. .. versionadded:: 3.11
  65. """
  66. PYTHON_LEGACY = OLD_UUID_SUBTYPE
  67. """The Python legacy UUID representation.
  68. :class:`uuid.UUID` instances will automatically be encoded to
  69. and decoded from BSON binary, using RFC-4122 byte order with
  70. binary subtype :data:`OLD_UUID_SUBTYPE`.
  71. See :ref:`python-legacy-representation-details` for details.
  72. .. versionadded:: 3.11
  73. """
  74. JAVA_LEGACY = 5
  75. """The Java legacy UUID representation.
  76. :class:`uuid.UUID` instances will automatically be encoded to
  77. and decoded from BSON binary subtype :data:`OLD_UUID_SUBTYPE`,
  78. using the Java driver's legacy byte order.
  79. See :ref:`java-legacy-representation-details` for details.
  80. .. versionadded:: 3.11
  81. """
  82. CSHARP_LEGACY = 6
  83. """The C#/.net legacy UUID representation.
  84. :class:`uuid.UUID` instances will automatically be encoded to
  85. and decoded from BSON binary subtype :data:`OLD_UUID_SUBTYPE`,
  86. using the C# driver's legacy byte order.
  87. See :ref:`csharp-legacy-representation-details` for details.
  88. .. versionadded:: 3.11
  89. """
  90. STANDARD = UuidRepresentation.STANDARD
  91. """An alias for :data:`UuidRepresentation.STANDARD`.
  92. .. versionadded:: 3.0
  93. """
  94. PYTHON_LEGACY = UuidRepresentation.PYTHON_LEGACY
  95. """An alias for :data:`UuidRepresentation.PYTHON_LEGACY`.
  96. .. versionadded:: 3.0
  97. """
  98. JAVA_LEGACY = UuidRepresentation.JAVA_LEGACY
  99. """An alias for :data:`UuidRepresentation.JAVA_LEGACY`.
  100. .. versionchanged:: 3.6
  101. BSON binary subtype 4 is decoded using RFC-4122 byte order.
  102. .. versionadded:: 2.3
  103. """
  104. CSHARP_LEGACY = UuidRepresentation.CSHARP_LEGACY
  105. """An alias for :data:`UuidRepresentation.CSHARP_LEGACY`.
  106. .. versionchanged:: 3.6
  107. BSON binary subtype 4 is decoded using RFC-4122 byte order.
  108. .. versionadded:: 2.3
  109. """
  110. ALL_UUID_SUBTYPES = (OLD_UUID_SUBTYPE, UUID_SUBTYPE)
  111. ALL_UUID_REPRESENTATIONS = (UuidRepresentation.UNSPECIFIED,
  112. UuidRepresentation.STANDARD,
  113. UuidRepresentation.PYTHON_LEGACY,
  114. UuidRepresentation.JAVA_LEGACY,
  115. UuidRepresentation.CSHARP_LEGACY)
  116. UUID_REPRESENTATION_NAMES = {
  117. UuidRepresentation.UNSPECIFIED: 'UuidRepresentation.UNSPECIFIED',
  118. UuidRepresentation.STANDARD: 'UuidRepresentation.STANDARD',
  119. UuidRepresentation.PYTHON_LEGACY: 'UuidRepresentation.PYTHON_LEGACY',
  120. UuidRepresentation.JAVA_LEGACY: 'UuidRepresentation.JAVA_LEGACY',
  121. UuidRepresentation.CSHARP_LEGACY: 'UuidRepresentation.CSHARP_LEGACY'}
  122. MD5_SUBTYPE = 5
  123. """BSON binary subtype for an MD5 hash.
  124. """
  125. USER_DEFINED_SUBTYPE = 128
  126. """BSON binary subtype for any user defined structure.
  127. """
  128. class Binary(bytes):
  129. """Representation of BSON binary data.
  130. This is necessary because we want to represent Python strings as
  131. the BSON string type. We need to wrap binary data so we can tell
  132. the difference between what should be considered binary data and
  133. what should be considered a string when we encode to BSON.
  134. Raises TypeError if `data` is not an instance of :class:`bytes`
  135. (:class:`str` in python 2) or `subtype` is not an instance of
  136. :class:`int`. Raises ValueError if `subtype` is not in [0, 256).
  137. .. note::
  138. In python 3 instances of Binary with subtype 0 will be decoded
  139. directly to :class:`bytes`.
  140. :Parameters:
  141. - `data`: the binary data to represent. Can be any bytes-like type
  142. that implements the buffer protocol.
  143. - `subtype` (optional): the `binary subtype
  144. <http://bsonspec.org/#/specification>`_
  145. to use
  146. .. versionchanged:: 3.9
  147. Support any bytes-like type that implements the buffer protocol.
  148. """
  149. _type_marker = 5
  150. def __new__(cls, data, subtype=BINARY_SUBTYPE):
  151. if not isinstance(subtype, int):
  152. raise TypeError("subtype must be an instance of int")
  153. if subtype >= 256 or subtype < 0:
  154. raise ValueError("subtype must be contained in [0, 256)")
  155. # Support any type that implements the buffer protocol.
  156. self = bytes.__new__(cls, memoryview(data).tobytes())
  157. self.__subtype = subtype
  158. return self
  159. @classmethod
  160. def from_uuid(cls, uuid, uuid_representation=UuidRepresentation.STANDARD):
  161. """Create a BSON Binary object from a Python UUID.
  162. Creates a :class:`~bson.binary.Binary` object from a
  163. :class:`uuid.UUID` instance. Assumes that the native
  164. :class:`uuid.UUID` instance uses the byte-order implied by the
  165. provided ``uuid_representation``.
  166. Raises :exc:`TypeError` if `uuid` is not an instance of
  167. :class:`~uuid.UUID`.
  168. :Parameters:
  169. - `uuid`: A :class:`uuid.UUID` instance.
  170. - `uuid_representation`: A member of
  171. :class:`~bson.binary.UuidRepresentation`. Default:
  172. :const:`~bson.binary.UuidRepresentation.STANDARD`.
  173. See :ref:`handling-uuid-data-example` for details.
  174. .. versionadded:: 3.11
  175. """
  176. if not isinstance(uuid, UUID):
  177. raise TypeError("uuid must be an instance of uuid.UUID")
  178. if uuid_representation not in ALL_UUID_REPRESENTATIONS:
  179. raise ValueError("uuid_representation must be a value "
  180. "from bson.binary.UuidRepresentation")
  181. if uuid_representation == UuidRepresentation.UNSPECIFIED:
  182. raise ValueError(
  183. "cannot encode native uuid.UUID with "
  184. "UuidRepresentation.UNSPECIFIED. UUIDs can be manually "
  185. "converted to bson.Binary instances using "
  186. "bson.Binary.from_uuid() or a different UuidRepresentation "
  187. "can be configured. See the documentation for "
  188. "UuidRepresentation for more information.")
  189. subtype = OLD_UUID_SUBTYPE
  190. if uuid_representation == UuidRepresentation.PYTHON_LEGACY:
  191. payload = uuid.bytes
  192. elif uuid_representation == UuidRepresentation.JAVA_LEGACY:
  193. from_uuid = uuid.bytes
  194. payload = from_uuid[0:8][::-1] + from_uuid[8:16][::-1]
  195. elif uuid_representation == UuidRepresentation.CSHARP_LEGACY:
  196. payload = uuid.bytes_le
  197. else:
  198. # uuid_representation == UuidRepresentation.STANDARD
  199. subtype = UUID_SUBTYPE
  200. payload = uuid.bytes
  201. return cls(payload, subtype)
  202. def as_uuid(self, uuid_representation=UuidRepresentation.STANDARD):
  203. """Create a Python UUID from this BSON Binary object.
  204. Decodes this binary object as a native :class:`uuid.UUID` instance
  205. with the provided ``uuid_representation``.
  206. Raises :exc:`ValueError` if this :class:`~bson.binary.Binary` instance
  207. does not contain a UUID.
  208. :Parameters:
  209. - `uuid_representation`: A member of
  210. :class:`~bson.binary.UuidRepresentation`. Default:
  211. :const:`~bson.binary.UuidRepresentation.STANDARD`.
  212. See :ref:`handling-uuid-data-example` for details.
  213. .. versionadded:: 3.11
  214. """
  215. if self.subtype not in ALL_UUID_SUBTYPES:
  216. raise ValueError("cannot decode subtype %s as a uuid" % (
  217. self.subtype,))
  218. if uuid_representation not in ALL_UUID_REPRESENTATIONS:
  219. raise ValueError("uuid_representation must be a value from "
  220. "bson.binary.UuidRepresentation")
  221. if uuid_representation == UuidRepresentation.UNSPECIFIED:
  222. raise ValueError("uuid_representation cannot be UNSPECIFIED")
  223. elif uuid_representation == UuidRepresentation.PYTHON_LEGACY:
  224. if self.subtype == OLD_UUID_SUBTYPE:
  225. return UUID(bytes=self)
  226. elif uuid_representation == UuidRepresentation.JAVA_LEGACY:
  227. if self.subtype == OLD_UUID_SUBTYPE:
  228. return UUID(bytes=self[0:8][::-1] + self[8:16][::-1])
  229. elif uuid_representation == UuidRepresentation.CSHARP_LEGACY:
  230. if self.subtype == OLD_UUID_SUBTYPE:
  231. return UUID(bytes_le=self)
  232. else:
  233. # uuid_representation == UuidRepresentation.STANDARD
  234. if self.subtype == UUID_SUBTYPE:
  235. return UUID(bytes=self)
  236. raise ValueError("cannot decode subtype %s to %s" % (
  237. self.subtype, UUID_REPRESENTATION_NAMES[uuid_representation]))
  238. @property
  239. def subtype(self):
  240. """Subtype of this binary data.
  241. """
  242. return self.__subtype
  243. def __getnewargs__(self):
  244. # Work around http://bugs.python.org/issue7382
  245. data = super(Binary, self).__getnewargs__()[0]
  246. if PY3 and not isinstance(data, bytes):
  247. data = data.encode('latin-1')
  248. return data, self.__subtype
  249. def __eq__(self, other):
  250. if isinstance(other, Binary):
  251. return ((self.__subtype, bytes(self)) ==
  252. (other.subtype, bytes(other)))
  253. # We don't return NotImplemented here because if we did then
  254. # Binary("foo") == "foo" would return True, since Binary is a
  255. # subclass of str...
  256. return False
  257. def __hash__(self):
  258. return super(Binary, self).__hash__() ^ hash(self.__subtype)
  259. def __ne__(self, other):
  260. return not self == other
  261. def __repr__(self):
  262. return "Binary(%s, %s)" % (bytes.__repr__(self), self.__subtype)
  263. class UUIDLegacy(Binary):
  264. """**DEPRECATED** - UUID wrapper to support working with UUIDs stored as
  265. PYTHON_LEGACY.
  266. .. note:: This class has been deprecated and will be removed in
  267. PyMongo 4.0. Use :meth:`~bson.binary.Binary.from_uuid` and
  268. :meth:`~bson.binary.Binary.as_uuid` with the appropriate
  269. :class:`~bson.binary.UuidRepresentation` to handle legacy-formatted
  270. UUIDs instead.::
  271. from bson import Binary, UUIDLegacy, UuidRepresentation
  272. import uuid
  273. my_uuid = uuid.uuid4()
  274. legacy_uuid = UUIDLegacy(my_uuid)
  275. binary_uuid = Binary.from_uuid(
  276. my_uuid, UuidRepresentation.PYTHON_LEGACY)
  277. assert legacy_uuid == binary_uuid
  278. assert legacy_uuid.uuid == binary_uuid.as_uuid(
  279. UuidRepresentation.PYTHON_LEGACY)
  280. .. doctest::
  281. >>> import uuid
  282. >>> from bson.binary import Binary, UUIDLegacy, STANDARD
  283. >>> from bson.codec_options import CodecOptions
  284. >>> my_uuid = uuid.uuid4()
  285. >>> coll = db.get_collection('test',
  286. ... CodecOptions(uuid_representation=STANDARD))
  287. >>> coll.insert_one({'uuid': Binary(my_uuid.bytes, 3)}).inserted_id
  288. ObjectId('...')
  289. >>> coll.count_documents({'uuid': my_uuid})
  290. 0
  291. >>> coll.count_documents({'uuid': UUIDLegacy(my_uuid)})
  292. 1
  293. >>> coll.find({'uuid': UUIDLegacy(my_uuid)})[0]['uuid']
  294. UUID('...')
  295. >>>
  296. >>> # Convert from subtype 3 to subtype 4
  297. >>> doc = coll.find_one({'uuid': UUIDLegacy(my_uuid)})
  298. >>> coll.replace_one({"_id": doc["_id"]}, doc).matched_count
  299. 1
  300. >>> coll.count_documents({'uuid': UUIDLegacy(my_uuid)})
  301. 0
  302. >>> coll.count_documents({'uuid': {'$in': [UUIDLegacy(my_uuid), my_uuid]}})
  303. 1
  304. >>> coll.find_one({'uuid': my_uuid})['uuid']
  305. UUID('...')
  306. Raises :exc:`TypeError` if `obj` is not an instance of :class:`~uuid.UUID`.
  307. :Parameters:
  308. - `obj`: An instance of :class:`~uuid.UUID`.
  309. .. versionchanged:: 3.11
  310. Deprecated. The same functionality can be replicated using the
  311. :meth:`~Binary.from_uuid` and :meth:`~Binary.to_uuid` methods with
  312. :data:`~UuidRepresentation.PYTHON_LEGACY`.
  313. .. versionadded:: 2.1
  314. """
  315. def __new__(cls, obj):
  316. warn(
  317. "The UUIDLegacy class has been deprecated and will be removed "
  318. "in PyMongo 4.0. Use the Binary.from_uuid() and Binary.to_uuid() "
  319. "with the appropriate UuidRepresentation to handle "
  320. "legacy-formatted UUIDs instead.",
  321. DeprecationWarning, stacklevel=2)
  322. if not isinstance(obj, UUID):
  323. raise TypeError("obj must be an instance of uuid.UUID")
  324. self = Binary.__new__(cls, obj.bytes, OLD_UUID_SUBTYPE)
  325. self.__uuid = obj
  326. return self
  327. def __getnewargs__(self):
  328. # Support copy and deepcopy
  329. return (self.__uuid,)
  330. @property
  331. def uuid(self):
  332. """UUID instance wrapped by this UUIDLegacy instance.
  333. """
  334. return self.__uuid
  335. def __repr__(self):
  336. return "UUIDLegacy('%s')" % self.__uuid