read_concern.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. """Tools for working with read concerns."""
  15. from bson.py3compat import string_type
  16. class ReadConcern(object):
  17. """ReadConcern
  18. :Parameters:
  19. - `level`: (string) The read concern level specifies the level of
  20. isolation for read operations. For example, a read operation using a
  21. read concern level of ``majority`` will only return data that has been
  22. written to a majority of nodes. If the level is left unspecified, the
  23. server default will be used.
  24. .. versionadded:: 3.2
  25. """
  26. def __init__(self, level=None):
  27. if level is None or isinstance(level, string_type):
  28. self.__level = level
  29. else:
  30. raise TypeError(
  31. 'level must be a string or None.')
  32. @property
  33. def level(self):
  34. """The read concern level."""
  35. return self.__level
  36. @property
  37. def ok_for_legacy(self):
  38. """Return ``True`` if this read concern is compatible with
  39. old wire protocol versions."""
  40. return self.level is None or self.level == 'local'
  41. @property
  42. def document(self):
  43. """The document representation of this read concern.
  44. .. note::
  45. :class:`ReadConcern` is immutable. Mutating the value of
  46. :attr:`document` does not mutate this :class:`ReadConcern`.
  47. """
  48. doc = {}
  49. if self.__level:
  50. doc['level'] = self.level
  51. return doc
  52. def __eq__(self, other):
  53. if isinstance(other, ReadConcern):
  54. return self.document == other.document
  55. return NotImplemented
  56. def __repr__(self):
  57. if self.level:
  58. return 'ReadConcern(%s)' % self.level
  59. return 'ReadConcern()'
  60. DEFAULT_READ_CONCERN = ReadConcern()