__init__.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. # Copyright 2009-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. """BSON (Binary JSON) encoding and decoding.
  15. """
  16. import calendar
  17. import collections
  18. import datetime
  19. import itertools
  20. import re
  21. import struct
  22. import sys
  23. import uuid
  24. from codecs import (utf_8_decode as _utf_8_decode,
  25. utf_8_encode as _utf_8_encode)
  26. from bson.binary import (Binary, OLD_UUID_SUBTYPE,
  27. JAVA_LEGACY, CSHARP_LEGACY,
  28. UUIDLegacy)
  29. from bson.code import Code
  30. from bson.codec_options import CodecOptions, DEFAULT_CODEC_OPTIONS
  31. from bson.dbref import DBRef
  32. from bson.errors import (InvalidBSON,
  33. InvalidDocument,
  34. InvalidStringData)
  35. from bson.int64 import Int64
  36. from bson.max_key import MaxKey
  37. from bson.min_key import MinKey
  38. from bson.objectid import ObjectId
  39. from bson.py3compat import (b,
  40. PY3,
  41. iteritems,
  42. text_type,
  43. string_type,
  44. reraise)
  45. from bson.regex import Regex
  46. from bson.son import SON, RE_TYPE
  47. from bson.timestamp import Timestamp
  48. from bson.tz_util import utc
  49. try:
  50. from bson import _cbson
  51. _USE_C = True
  52. except ImportError:
  53. _USE_C = False
  54. EPOCH_AWARE = datetime.datetime.fromtimestamp(0, utc)
  55. EPOCH_NAIVE = datetime.datetime.utcfromtimestamp(0)
  56. BSONNUM = b"\x01" # Floating point
  57. BSONSTR = b"\x02" # UTF-8 string
  58. BSONOBJ = b"\x03" # Embedded document
  59. BSONARR = b"\x04" # Array
  60. BSONBIN = b"\x05" # Binary
  61. BSONUND = b"\x06" # Undefined
  62. BSONOID = b"\x07" # ObjectId
  63. BSONBOO = b"\x08" # Boolean
  64. BSONDAT = b"\x09" # UTC Datetime
  65. BSONNUL = b"\x0A" # Null
  66. BSONRGX = b"\x0B" # Regex
  67. BSONREF = b"\x0C" # DBRef
  68. BSONCOD = b"\x0D" # Javascript code
  69. BSONSYM = b"\x0E" # Symbol
  70. BSONCWS = b"\x0F" # Javascript code with scope
  71. BSONINT = b"\x10" # 32bit int
  72. BSONTIM = b"\x11" # Timestamp
  73. BSONLON = b"\x12" # 64bit int
  74. BSONMIN = b"\xFF" # Min key
  75. BSONMAX = b"\x7F" # Max key
  76. _UNPACK_FLOAT = struct.Struct("<d").unpack
  77. _UNPACK_INT = struct.Struct("<i").unpack
  78. _UNPACK_LENGTH_SUBTYPE = struct.Struct("<iB").unpack
  79. _UNPACK_LONG = struct.Struct("<q").unpack
  80. _UNPACK_TIMESTAMP = struct.Struct("<II").unpack
  81. def _get_int(data, position, dummy0, dummy1):
  82. """Decode a BSON int32 to python int."""
  83. end = position + 4
  84. return _UNPACK_INT(data[position:end])[0], end
  85. def _get_c_string(data, position):
  86. """Decode a BSON 'C' string to python unicode string."""
  87. end = data.index(b"\x00", position)
  88. return _utf_8_decode(data[position:end], None, True)[0], end + 1
  89. def _get_float(data, position, dummy0, dummy1):
  90. """Decode a BSON double to python float."""
  91. end = position + 8
  92. return _UNPACK_FLOAT(data[position:end])[0], end
  93. def _get_string(data, position, obj_end, dummy):
  94. """Decode a BSON string to python unicode string."""
  95. length = _UNPACK_INT(data[position:position + 4])[0]
  96. position += 4
  97. if length < 1 or obj_end - position < length:
  98. raise InvalidBSON("invalid string length")
  99. end = position + length - 1
  100. if data[end:end + 1] != b"\x00":
  101. raise InvalidBSON("invalid end of string")
  102. return _utf_8_decode(data[position:end], None, True)[0], end + 1
  103. def _get_object(data, position, obj_end, opts):
  104. """Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef."""
  105. obj_size = _UNPACK_INT(data[position:position + 4])[0]
  106. end = position + obj_size - 1
  107. if data[end:position + obj_size] != b"\x00":
  108. raise InvalidBSON("bad eoo")
  109. if end >= obj_end:
  110. raise InvalidBSON("invalid object length")
  111. obj = _elements_to_dict(data, position + 4, end, opts)
  112. position += obj_size
  113. if "$ref" in obj:
  114. return (DBRef(obj.pop("$ref"), obj.pop("$id", None),
  115. obj.pop("$db", None), obj), position)
  116. return obj, position
  117. def _get_array(data, position, obj_end, opts):
  118. """Decode a BSON array to python list."""
  119. size = _UNPACK_INT(data[position:position + 4])[0]
  120. end = position + size - 1
  121. if data[end:end + 1] != b"\x00":
  122. raise InvalidBSON("bad eoo")
  123. position += 4
  124. end -= 1
  125. result = []
  126. # Avoid doing global and attibute lookups in the loop.
  127. append = result.append
  128. index = data.index
  129. getter = _ELEMENT_GETTER
  130. while position < end:
  131. element_type = data[position:position + 1]
  132. # Just skip the keys.
  133. position = index(b'\x00', position) + 1
  134. value, position = getter[element_type](data, position, obj_end, opts)
  135. append(value)
  136. return result, position + 1
  137. def _get_binary(data, position, dummy, opts):
  138. """Decode a BSON binary to bson.binary.Binary or python UUID."""
  139. length, subtype = _UNPACK_LENGTH_SUBTYPE(data[position:position + 5])
  140. position += 5
  141. if subtype == 2:
  142. length2 = _UNPACK_INT(data[position:position + 4])[0]
  143. position += 4
  144. if length2 != length - 4:
  145. raise InvalidBSON("invalid binary (st 2) - lengths don't match!")
  146. length = length2
  147. end = position + length
  148. if subtype in (3, 4):
  149. # Java Legacy
  150. uuid_representation = opts.uuid_representation
  151. if uuid_representation == JAVA_LEGACY:
  152. java = data[position:end]
  153. value = uuid.UUID(bytes=java[0:8][::-1] + java[8:16][::-1])
  154. # C# legacy
  155. elif uuid_representation == CSHARP_LEGACY:
  156. value = uuid.UUID(bytes_le=data[position:end])
  157. # Python
  158. else:
  159. value = uuid.UUID(bytes=data[position:end])
  160. return value, end
  161. # Python3 special case. Decode subtype 0 to 'bytes'.
  162. if PY3 and subtype == 0:
  163. value = data[position:end]
  164. else:
  165. value = Binary(data[position:end], subtype)
  166. return value, end
  167. def _get_oid(data, position, dummy0, dummy1):
  168. """Decode a BSON ObjectId to bson.objectid.ObjectId."""
  169. end = position + 12
  170. return ObjectId(data[position:end]), end
  171. def _get_boolean(data, position, dummy0, dummy1):
  172. """Decode a BSON true/false to python True/False."""
  173. end = position + 1
  174. return data[position:end] == b"\x01", end
  175. def _get_date(data, position, dummy, opts):
  176. """Decode a BSON datetime to python datetime.datetime."""
  177. end = position + 8
  178. millis = _UNPACK_LONG(data[position:end])[0]
  179. diff = ((millis % 1000) + 1000) % 1000
  180. seconds = (millis - diff) / 1000
  181. micros = diff * 1000
  182. if opts.tz_aware:
  183. return EPOCH_AWARE + datetime.timedelta(
  184. seconds=seconds, microseconds=micros), end
  185. else:
  186. return EPOCH_NAIVE + datetime.timedelta(
  187. seconds=seconds, microseconds=micros), end
  188. def _get_code(data, position, obj_end, opts):
  189. """Decode a BSON code to bson.code.Code."""
  190. code, position = _get_string(data, position, obj_end, opts)
  191. return Code(code), position
  192. def _get_code_w_scope(data, position, obj_end, opts):
  193. """Decode a BSON code_w_scope to bson.code.Code."""
  194. code, position = _get_string(data, position + 4, obj_end, opts)
  195. scope, position = _get_object(data, position, obj_end, opts)
  196. return Code(code, scope), position
  197. def _get_regex(data, position, dummy0, dummy1):
  198. """Decode a BSON regex to bson.regex.Regex or a python pattern object."""
  199. pattern, position = _get_c_string(data, position)
  200. bson_flags, position = _get_c_string(data, position)
  201. bson_re = Regex(pattern, bson_flags)
  202. return bson_re, position
  203. def _get_ref(data, position, obj_end, opts):
  204. """Decode (deprecated) BSON DBPointer to bson.dbref.DBRef."""
  205. collection, position = _get_string(data, position, obj_end, opts)
  206. oid, position = _get_oid(data, position, obj_end, opts)
  207. return DBRef(collection, oid), position
  208. def _get_timestamp(data, position, dummy0, dummy1):
  209. """Decode a BSON timestamp to bson.timestamp.Timestamp."""
  210. end = position + 8
  211. inc, timestamp = _UNPACK_TIMESTAMP(data[position:end])
  212. return Timestamp(timestamp, inc), end
  213. def _get_int64(data, position, dummy0, dummy1):
  214. """Decode a BSON int64 to bson.int64.Int64."""
  215. end = position + 8
  216. return Int64(_UNPACK_LONG(data[position:end])[0]), end
  217. # Each decoder function's signature is:
  218. # - data: bytes
  219. # - position: int, beginning of object in 'data' to decode
  220. # - obj_end: int, end of object to decode in 'data' if variable-length type
  221. # - opts: a CodecOptions
  222. _ELEMENT_GETTER = {
  223. BSONNUM: _get_float,
  224. BSONSTR: _get_string,
  225. BSONOBJ: _get_object,
  226. BSONARR: _get_array,
  227. BSONBIN: _get_binary,
  228. BSONUND: lambda w, x, y, z: (None, x), # Deprecated undefined
  229. BSONOID: _get_oid,
  230. BSONBOO: _get_boolean,
  231. BSONDAT: _get_date,
  232. BSONNUL: lambda w, x, y, z: (None, x),
  233. BSONRGX: _get_regex,
  234. BSONREF: _get_ref, # Deprecated DBPointer
  235. BSONCOD: _get_code,
  236. BSONSYM: _get_string, # Deprecated symbol
  237. BSONCWS: _get_code_w_scope,
  238. BSONINT: _get_int,
  239. BSONTIM: _get_timestamp,
  240. BSONLON: _get_int64,
  241. BSONMIN: lambda w, x, y, z: (MinKey(), x),
  242. BSONMAX: lambda w, x, y, z: (MaxKey(), x)}
  243. def _element_to_dict(data, position, obj_end, opts):
  244. """Decode a single key, value pair."""
  245. element_type = data[position:position + 1]
  246. position += 1
  247. element_name, position = _get_c_string(data, position)
  248. value, position = _ELEMENT_GETTER[element_type](data,
  249. position, obj_end, opts)
  250. return element_name, value, position
  251. def _elements_to_dict(data, position, obj_end, opts):
  252. """Decode a BSON document."""
  253. result = opts.document_class()
  254. end = obj_end - 1
  255. while position < end:
  256. (key, value, position) = _element_to_dict(data, position, obj_end, opts)
  257. result[key] = value
  258. return result
  259. def _bson_to_dict(data, opts):
  260. """Decode a BSON string to document_class."""
  261. try:
  262. obj_size = _UNPACK_INT(data[:4])[0]
  263. except struct.error as exc:
  264. raise InvalidBSON(str(exc))
  265. if obj_size != len(data):
  266. raise InvalidBSON("invalid object size")
  267. if data[obj_size - 1:obj_size] != b"\x00":
  268. raise InvalidBSON("bad eoo")
  269. try:
  270. return _elements_to_dict(data, 4, obj_size - 1, opts)
  271. except InvalidBSON:
  272. raise
  273. except Exception:
  274. # Change exception type to InvalidBSON but preserve traceback.
  275. _, exc_value, exc_tb = sys.exc_info()
  276. reraise(InvalidBSON, exc_value, exc_tb)
  277. if _USE_C:
  278. _bson_to_dict = _cbson._bson_to_dict
  279. _PACK_FLOAT = struct.Struct("<d").pack
  280. _PACK_INT = struct.Struct("<i").pack
  281. _PACK_LENGTH_SUBTYPE = struct.Struct("<iB").pack
  282. _PACK_LONG = struct.Struct("<q").pack
  283. _PACK_TIMESTAMP = struct.Struct("<II").pack
  284. _LIST_NAMES = tuple(b(str(i)) + b"\x00" for i in range(1000))
  285. def gen_list_name():
  286. """Generate "keys" for encoded lists in the sequence
  287. b"0\x00", b"1\x00", b"2\x00", ...
  288. The first 1000 keys are returned from a pre-built cache. All
  289. subsequent keys are generated on the fly.
  290. """
  291. for name in _LIST_NAMES:
  292. yield name
  293. counter = itertools.count(1000)
  294. while True:
  295. yield b(str(next(counter))) + b"\x00"
  296. def _make_c_string_check(string):
  297. """Make a 'C' string, checking for embedded NUL characters."""
  298. if isinstance(string, bytes):
  299. if b"\x00" in string:
  300. raise InvalidDocument("BSON keys / regex patterns must not "
  301. "contain a NUL character")
  302. try:
  303. _utf_8_decode(string, None, True)
  304. return string + b"\x00"
  305. except UnicodeError:
  306. raise InvalidStringData("strings in documents must be valid "
  307. "UTF-8: %r" % string)
  308. else:
  309. if "\x00" in string:
  310. raise InvalidDocument("BSON keys / regex patterns must not "
  311. "contain a NUL character")
  312. return _utf_8_encode(string)[0] + b"\x00"
  313. def _make_c_string(string):
  314. """Make a 'C' string."""
  315. if isinstance(string, bytes):
  316. try:
  317. _utf_8_decode(string, None, True)
  318. return string + b"\x00"
  319. except UnicodeError:
  320. raise InvalidStringData("strings in documents must be valid "
  321. "UTF-8: %r" % string)
  322. else:
  323. return _utf_8_encode(string)[0] + b"\x00"
  324. if PY3:
  325. def _make_name(string):
  326. """Make a 'C' string suitable for a BSON key."""
  327. # Keys can only be text in python 3.
  328. if "\x00" in string:
  329. raise InvalidDocument("BSON keys / regex patterns must not "
  330. "contain a NUL character")
  331. return _utf_8_encode(string)[0] + b"\x00"
  332. else:
  333. # Keys can be unicode or bytes in python 2.
  334. _make_name = _make_c_string_check
  335. def _encode_float(name, value, dummy0, dummy1):
  336. """Encode a float."""
  337. return b"\x01" + name + _PACK_FLOAT(value)
  338. if PY3:
  339. def _encode_bytes(name, value, dummy0, dummy1):
  340. """Encode a python bytes."""
  341. # Python3 special case. Store 'bytes' as BSON binary subtype 0.
  342. return b"\x05" + name + _PACK_INT(len(value)) + b"\x00" + value
  343. else:
  344. def _encode_bytes(name, value, dummy0, dummy1):
  345. """Encode a python str (python 2.x)."""
  346. try:
  347. _utf_8_decode(value, None, True)
  348. except UnicodeError:
  349. raise InvalidStringData("strings in documents must be valid "
  350. "UTF-8: %r" % (value,))
  351. return b"\x02" + name + _PACK_INT(len(value) + 1) + value + b"\x00"
  352. def _encode_mapping(name, value, check_keys, opts):
  353. """Encode a mapping type."""
  354. data = b"".join([_element_to_bson(key, val, check_keys, opts)
  355. for key, val in iteritems(value)])
  356. return b"\x03" + name + _PACK_INT(len(data) + 5) + data + b"\x00"
  357. def _encode_dbref(name, value, check_keys, opts):
  358. """Encode bson.dbref.DBRef."""
  359. buf = bytearray(b"\x03" + name + b"\x00\x00\x00\x00")
  360. begin = len(buf) - 4
  361. buf += _name_value_to_bson(b"$ref\x00",
  362. value.collection, check_keys, opts)
  363. buf += _name_value_to_bson(b"$id\x00",
  364. value.id, check_keys, opts)
  365. if value.database is not None:
  366. buf += _name_value_to_bson(
  367. b"$db\x00", value.database, check_keys, opts)
  368. for key, val in iteritems(value._DBRef__kwargs):
  369. buf += _element_to_bson(key, val, check_keys, opts)
  370. buf += b"\x00"
  371. buf[begin:begin + 4] = _PACK_INT(len(buf) - begin)
  372. return bytes(buf)
  373. def _encode_list(name, value, check_keys, opts):
  374. """Encode a list/tuple."""
  375. lname = gen_list_name()
  376. data = b"".join([_name_value_to_bson(next(lname), item,
  377. check_keys, opts)
  378. for item in value])
  379. return b"\x04" + name + _PACK_INT(len(data) + 5) + data + b"\x00"
  380. def _encode_text(name, value, dummy0, dummy1):
  381. """Encode a python unicode (python 2.x) / str (python 3.x)."""
  382. value = _utf_8_encode(value)[0]
  383. return b"\x02" + name + _PACK_INT(len(value) + 1) + value + b"\x00"
  384. def _encode_binary(name, value, dummy0, dummy1):
  385. """Encode bson.binary.Binary."""
  386. subtype = value.subtype
  387. if subtype == 2:
  388. value = _PACK_INT(len(value)) + value
  389. return b"\x05" + name + _PACK_LENGTH_SUBTYPE(len(value), subtype) + value
  390. def _encode_uuid(name, value, dummy, opts):
  391. """Encode uuid.UUID."""
  392. uuid_representation = opts.uuid_representation
  393. # Python Legacy Common Case
  394. if uuid_representation == OLD_UUID_SUBTYPE:
  395. return b"\x05" + name + b'\x10\x00\x00\x00\x03' + value.bytes
  396. # Java Legacy
  397. elif uuid_representation == JAVA_LEGACY:
  398. from_uuid = value.bytes
  399. data = from_uuid[0:8][::-1] + from_uuid[8:16][::-1]
  400. return b"\x05" + name + b'\x10\x00\x00\x00\x03' + data
  401. # C# legacy
  402. elif uuid_representation == CSHARP_LEGACY:
  403. # Microsoft GUID representation.
  404. return b"\x05" + name + b'\x10\x00\x00\x00\x03' + value.bytes_le
  405. # New
  406. else:
  407. return b"\x05" + name + b'\x10\x00\x00\x00\x04' + value.bytes
  408. def _encode_objectid(name, value, dummy0, dummy1):
  409. """Encode bson.objectid.ObjectId."""
  410. return b"\x07" + name + value.binary
  411. def _encode_bool(name, value, dummy0, dummy1):
  412. """Encode a python boolean (True/False)."""
  413. return b"\x08" + name + (value and b"\x01" or b"\x00")
  414. def _encode_datetime(name, value, dummy0, dummy1):
  415. """Encode datetime.datetime."""
  416. if value.utcoffset() is not None:
  417. value = value - value.utcoffset()
  418. millis = int(calendar.timegm(value.timetuple()) * 1000 +
  419. value.microsecond / 1000)
  420. return b"\x09" + name + _PACK_LONG(millis)
  421. def _encode_none(name, dummy0, dummy1, dummy2):
  422. """Encode python None."""
  423. return b"\x0A" + name
  424. def _encode_regex(name, value, dummy0, dummy1):
  425. """Encode a python regex or bson.regex.Regex."""
  426. flags = value.flags
  427. # Python 2 common case
  428. if flags == 0:
  429. return b"\x0B" + name + _make_c_string_check(value.pattern) + b"\x00"
  430. # Python 3 common case
  431. elif flags == re.UNICODE:
  432. return b"\x0B" + name + _make_c_string_check(value.pattern) + b"u\x00"
  433. else:
  434. sflags = b""
  435. if flags & re.IGNORECASE:
  436. sflags += b"i"
  437. if flags & re.LOCALE:
  438. sflags += b"l"
  439. if flags & re.MULTILINE:
  440. sflags += b"m"
  441. if flags & re.DOTALL:
  442. sflags += b"s"
  443. if flags & re.UNICODE:
  444. sflags += b"u"
  445. if flags & re.VERBOSE:
  446. sflags += b"x"
  447. sflags += b"\x00"
  448. return b"\x0B" + name + _make_c_string_check(value.pattern) + sflags
  449. def _encode_code(name, value, dummy, opts):
  450. """Encode bson.code.Code."""
  451. cstring = _make_c_string(value)
  452. cstrlen = len(cstring)
  453. if not value.scope:
  454. return b"\x0D" + name + _PACK_INT(cstrlen) + cstring
  455. scope = _dict_to_bson(value.scope, False, opts, False)
  456. full_length = _PACK_INT(8 + cstrlen + len(scope))
  457. return b"\x0F" + name + full_length + _PACK_INT(cstrlen) + cstring + scope
  458. def _encode_int(name, value, dummy0, dummy1):
  459. """Encode a python int."""
  460. if -2147483648 <= value <= 2147483647:
  461. return b"\x10" + name + _PACK_INT(value)
  462. else:
  463. try:
  464. return b"\x12" + name + _PACK_LONG(value)
  465. except struct.error:
  466. raise OverflowError("BSON can only handle up to 8-byte ints")
  467. def _encode_timestamp(name, value, dummy0, dummy1):
  468. """Encode bson.timestamp.Timestamp."""
  469. return b"\x11" + name + _PACK_TIMESTAMP(value.inc, value.time)
  470. def _encode_long(name, value, dummy0, dummy1):
  471. """Encode a python long (python 2.x)"""
  472. try:
  473. return b"\x12" + name + _PACK_LONG(value)
  474. except struct.error:
  475. raise OverflowError("BSON can only handle up to 8-byte ints")
  476. def _encode_minkey(name, dummy0, dummy1, dummy2):
  477. """Encode bson.min_key.MinKey."""
  478. return b"\xFF" + name
  479. def _encode_maxkey(name, dummy0, dummy1, dummy2):
  480. """Encode bson.max_key.MaxKey."""
  481. return b"\x7F" + name
  482. # Each encoder function's signature is:
  483. # - name: utf-8 bytes
  484. # - value: a Python data type, e.g. a Python int for _encode_int
  485. # - check_keys: bool, whether to check for invalid names
  486. # - opts: a CodecOptions
  487. _ENCODERS = {
  488. bool: _encode_bool,
  489. bytes: _encode_bytes,
  490. datetime.datetime: _encode_datetime,
  491. dict: _encode_mapping,
  492. float: _encode_float,
  493. int: _encode_int,
  494. list: _encode_list,
  495. # unicode in py2, str in py3
  496. text_type: _encode_text,
  497. tuple: _encode_list,
  498. type(None): _encode_none,
  499. uuid.UUID: _encode_uuid,
  500. Binary: _encode_binary,
  501. Int64: _encode_long,
  502. Code: _encode_code,
  503. DBRef: _encode_dbref,
  504. MaxKey: _encode_maxkey,
  505. MinKey: _encode_minkey,
  506. ObjectId: _encode_objectid,
  507. Regex: _encode_regex,
  508. RE_TYPE: _encode_regex,
  509. SON: _encode_mapping,
  510. Timestamp: _encode_timestamp,
  511. UUIDLegacy: _encode_binary,
  512. # Special case. This will never be looked up directly.
  513. collections.Mapping: _encode_mapping,
  514. }
  515. _MARKERS = {
  516. 5: _encode_binary,
  517. 7: _encode_objectid,
  518. 11: _encode_regex,
  519. 13: _encode_code,
  520. 17: _encode_timestamp,
  521. 18: _encode_long,
  522. 100: _encode_dbref,
  523. 127: _encode_maxkey,
  524. 255: _encode_minkey,
  525. }
  526. if not PY3:
  527. _ENCODERS[long] = _encode_long
  528. def _name_value_to_bson(name, value, check_keys, opts):
  529. """Encode a single name, value pair."""
  530. # First see if the type is already cached. KeyError will only ever
  531. # happen once per subtype.
  532. try:
  533. return _ENCODERS[type(value)](name, value, check_keys, opts)
  534. except KeyError:
  535. pass
  536. # Second, fall back to trying _type_marker. This has to be done
  537. # before the loop below since users could subclass one of our
  538. # custom types that subclasses a python built-in (e.g. Binary)
  539. marker = getattr(value, "_type_marker", None)
  540. if isinstance(marker, int) and marker in _MARKERS:
  541. func = _MARKERS[marker]
  542. # Cache this type for faster subsequent lookup.
  543. _ENCODERS[type(value)] = func
  544. return func(name, value, check_keys, opts)
  545. # If all else fails test each base type. This will only happen once for
  546. # a subtype of a supported base type.
  547. for base in _ENCODERS:
  548. if isinstance(value, base):
  549. func = _ENCODERS[base]
  550. # Cache this type for faster subsequent lookup.
  551. _ENCODERS[type(value)] = func
  552. return func(name, value, check_keys, opts)
  553. raise InvalidDocument("cannot convert value of type %s to bson" %
  554. type(value))
  555. def _element_to_bson(key, value, check_keys, opts):
  556. """Encode a single key, value pair."""
  557. if not isinstance(key, string_type):
  558. raise InvalidDocument("documents must have only string keys, "
  559. "key was %r" % (key,))
  560. if check_keys:
  561. if key.startswith("$"):
  562. raise InvalidDocument("key %r must not start with '$'" % (key,))
  563. if "." in key:
  564. raise InvalidDocument("key %r must not contain '.'" % (key,))
  565. name = _make_name(key)
  566. return _name_value_to_bson(name, value, check_keys, opts)
  567. def _dict_to_bson(doc, check_keys, opts, top_level=True):
  568. """Encode a document to BSON."""
  569. try:
  570. elements = []
  571. if top_level and "_id" in doc:
  572. elements.append(_name_value_to_bson(b"_id\x00", doc["_id"],
  573. check_keys, opts))
  574. for (key, value) in iteritems(doc):
  575. if not top_level or key != "_id":
  576. elements.append(_element_to_bson(key, value,
  577. check_keys, opts))
  578. except AttributeError:
  579. raise TypeError("encoder expected a mapping type but got: %r" % (doc,))
  580. encoded = b"".join(elements)
  581. return _PACK_INT(len(encoded) + 5) + encoded + b"\x00"
  582. if _USE_C:
  583. _dict_to_bson = _cbson._dict_to_bson
  584. _CODEC_OPTIONS_TYPE_ERROR = TypeError(
  585. "codec_options must be an instance of CodecOptions")
  586. def decode_all(data, codec_options=DEFAULT_CODEC_OPTIONS):
  587. """Decode BSON data to multiple documents.
  588. `data` must be a string of concatenated, valid, BSON-encoded
  589. documents.
  590. :Parameters:
  591. - `data`: BSON data
  592. - `codec_options` (optional): An instance of
  593. :class:`~bson.codec_options.CodecOptions`.
  594. .. versionchanged:: 3.0
  595. Removed `compile_re` option: PyMongo now always represents BSON regular
  596. expressions as :class:`~bson.regex.Regex` objects. Use
  597. :meth:`~bson.regex.Regex.try_compile` to attempt to convert from a
  598. BSON regular expression to a Python regular expression object.
  599. Replaced `as_class`, `tz_aware`, and `uuid_subtype` options with
  600. `codec_options`.
  601. .. versionchanged:: 2.7
  602. Added `compile_re` option. If set to False, PyMongo represented BSON
  603. regular expressions as :class:`~bson.regex.Regex` objects instead of
  604. attempting to compile BSON regular expressions as Python native
  605. regular expressions, thus preventing errors for some incompatible
  606. patterns, see `PYTHON-500`_.
  607. .. _PYTHON-500: https://jira.mongodb.org/browse/PYTHON-500
  608. """
  609. if not isinstance(codec_options, CodecOptions):
  610. raise _CODEC_OPTIONS_TYPE_ERROR
  611. docs = []
  612. position = 0
  613. end = len(data) - 1
  614. try:
  615. while position < end:
  616. obj_size = _UNPACK_INT(data[position:position + 4])[0]
  617. if len(data) - position < obj_size:
  618. raise InvalidBSON("invalid object size")
  619. obj_end = position + obj_size - 1
  620. if data[obj_end:position + obj_size] != b"\x00":
  621. raise InvalidBSON("bad eoo")
  622. docs.append(_elements_to_dict(data,
  623. position + 4,
  624. obj_end,
  625. codec_options))
  626. position += obj_size
  627. return docs
  628. except InvalidBSON:
  629. raise
  630. except Exception:
  631. # Change exception type to InvalidBSON but preserve traceback.
  632. _, exc_value, exc_tb = sys.exc_info()
  633. reraise(InvalidBSON, exc_value, exc_tb)
  634. if _USE_C:
  635. decode_all = _cbson.decode_all
  636. def decode_iter(data, codec_options=DEFAULT_CODEC_OPTIONS):
  637. """Decode BSON data to multiple documents as a generator.
  638. Works similarly to the decode_all function, but yields one document at a
  639. time.
  640. `data` must be a string of concatenated, valid, BSON-encoded
  641. documents.
  642. :Parameters:
  643. - `data`: BSON data
  644. - `codec_options` (optional): An instance of
  645. :class:`~bson.codec_options.CodecOptions`.
  646. .. versionchanged:: 3.0
  647. Replaced `as_class`, `tz_aware`, and `uuid_subtype` options with
  648. `codec_options`.
  649. .. versionadded:: 2.8
  650. """
  651. if not isinstance(codec_options, CodecOptions):
  652. raise _CODEC_OPTIONS_TYPE_ERROR
  653. position = 0
  654. end = len(data) - 1
  655. while position < end:
  656. obj_size = _UNPACK_INT(data[position:position + 4])[0]
  657. elements = data[position:position + obj_size]
  658. position += obj_size
  659. yield _bson_to_dict(elements, codec_options)
  660. def decode_file_iter(file_obj, codec_options=DEFAULT_CODEC_OPTIONS):
  661. """Decode bson data from a file to multiple documents as a generator.
  662. Works similarly to the decode_all function, but reads from the file object
  663. in chunks and parses bson in chunks, yielding one document at a time.
  664. :Parameters:
  665. - `file_obj`: A file object containing BSON data.
  666. - `codec_options` (optional): An instance of
  667. :class:`~bson.codec_options.CodecOptions`.
  668. .. versionchanged:: 3.0
  669. Replaced `as_class`, `tz_aware`, and `uuid_subtype` options with
  670. `codec_options`.
  671. .. versionadded:: 2.8
  672. """
  673. while True:
  674. # Read size of next object.
  675. size_data = file_obj.read(4)
  676. if len(size_data) == 0:
  677. break # Finished with file normaly.
  678. elif len(size_data) != 4:
  679. raise InvalidBSON("cut off in middle of objsize")
  680. obj_size = _UNPACK_INT(size_data)[0] - 4
  681. elements = size_data + file_obj.read(obj_size)
  682. yield _bson_to_dict(elements, codec_options)
  683. def is_valid(bson):
  684. """Check that the given string represents valid :class:`BSON` data.
  685. Raises :class:`TypeError` if `bson` is not an instance of
  686. :class:`str` (:class:`bytes` in python 3). Returns ``True``
  687. if `bson` is valid :class:`BSON`, ``False`` otherwise.
  688. :Parameters:
  689. - `bson`: the data to be validated
  690. """
  691. if not isinstance(bson, bytes):
  692. raise TypeError("BSON data must be an instance of a subclass of bytes")
  693. try:
  694. _bson_to_dict(bson, DEFAULT_CODEC_OPTIONS)
  695. return True
  696. except Exception:
  697. return False
  698. class BSON(bytes):
  699. """BSON (Binary JSON) data.
  700. """
  701. @classmethod
  702. def encode(cls, document, check_keys=False,
  703. codec_options=DEFAULT_CODEC_OPTIONS):
  704. """Encode a document to a new :class:`BSON` instance.
  705. A document can be any mapping type (like :class:`dict`).
  706. Raises :class:`TypeError` if `document` is not a mapping type,
  707. or contains keys that are not instances of
  708. :class:`basestring` (:class:`str` in python 3). Raises
  709. :class:`~bson.errors.InvalidDocument` if `document` cannot be
  710. converted to :class:`BSON`.
  711. :Parameters:
  712. - `document`: mapping type representing a document
  713. - `check_keys` (optional): check if keys start with '$' or
  714. contain '.', raising :class:`~bson.errors.InvalidDocument` in
  715. either case
  716. - `codec_options` (optional): An instance of
  717. :class:`~bson.codec_options.CodecOptions`.
  718. .. versionchanged:: 3.0
  719. Replaced `uuid_subtype` option with `codec_options`.
  720. """
  721. if not isinstance(codec_options, CodecOptions):
  722. raise _CODEC_OPTIONS_TYPE_ERROR
  723. return cls(_dict_to_bson(document, check_keys, codec_options))
  724. def decode(self, codec_options=DEFAULT_CODEC_OPTIONS):
  725. """Decode this BSON data.
  726. By default, returns a BSON document represented as a Python
  727. :class:`dict`. To use a different :class:`MutableMapping` class,
  728. configure a :class:`~bson.codec_options.CodecOptions`::
  729. >>> import collections # From Python standard library.
  730. >>> import bson
  731. >>> from bson.codec_options import CodecOptions
  732. >>> data = bson.BSON.encode({'a': 1})
  733. >>> decoded_doc = bson.BSON.decode(data)
  734. <type 'dict'>
  735. >>> options = CodecOptions(document_class=collections.OrderedDict)
  736. >>> decoded_doc = bson.BSON.decode(data, codec_options=options)
  737. >>> type(decoded_doc)
  738. <class 'collections.OrderedDict'>
  739. :Parameters:
  740. - `codec_options` (optional): An instance of
  741. :class:`~bson.codec_options.CodecOptions`.
  742. .. versionchanged:: 3.0
  743. Removed `compile_re` option: PyMongo now always represents BSON
  744. regular expressions as :class:`~bson.regex.Regex` objects. Use
  745. :meth:`~bson.regex.Regex.try_compile` to attempt to convert from a
  746. BSON regular expression to a Python regular expression object.
  747. Replaced `as_class`, `tz_aware`, and `uuid_subtype` options with
  748. `codec_options`.
  749. .. versionchanged:: 2.7
  750. Added `compile_re` option. If set to False, PyMongo represented BSON
  751. regular expressions as :class:`~bson.regex.Regex` objects instead of
  752. attempting to compile BSON regular expressions as Python native
  753. regular expressions, thus preventing errors for some incompatible
  754. patterns, see `PYTHON-500`_.
  755. .. _PYTHON-500: https://jira.mongodb.org/browse/PYTHON-500
  756. """
  757. if not isinstance(codec_options, CodecOptions):
  758. raise _CODEC_OPTIONS_TYPE_ERROR
  759. return _bson_to_dict(self, codec_options)
  760. def has_c():
  761. """Is the C extension installed?
  762. """
  763. return _USE_C