json.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # mysql/json.py
  2. # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. from __future__ import absolute_import
  8. import json
  9. from ...sql import elements
  10. from ... import types as sqltypes
  11. from ... import util
  12. class JSON(sqltypes.JSON):
  13. """MySQL JSON type.
  14. MySQL supports JSON as of version 5.7. Note that MariaDB does **not**
  15. support JSON at the time of this writing.
  16. The :class:`.mysql.JSON` type supports persistence of JSON values
  17. as well as the core index operations provided by :class:`.types.JSON`
  18. datatype, by adapting the operations to render the ``JSON_EXTRACT``
  19. function at the database level.
  20. .. versionadded:: 1.1
  21. """
  22. pass
  23. class _FormatTypeMixin(object):
  24. def _format_value(self, value):
  25. raise NotImplementedError()
  26. def bind_processor(self, dialect):
  27. super_proc = self.string_bind_processor(dialect)
  28. def process(value):
  29. value = self._format_value(value)
  30. if super_proc:
  31. value = super_proc(value)
  32. return value
  33. return process
  34. def literal_processor(self, dialect):
  35. super_proc = self.string_literal_processor(dialect)
  36. def process(value):
  37. value = self._format_value(value)
  38. if super_proc:
  39. value = super_proc(value)
  40. return value
  41. return process
  42. class JSONIndexType(_FormatTypeMixin, sqltypes.JSON.JSONIndexType):
  43. def _format_value(self, value):
  44. if isinstance(value, int):
  45. value = "$[%s]" % value
  46. else:
  47. value = '$."%s"' % value
  48. return value
  49. class JSONPathType(_FormatTypeMixin, sqltypes.JSON.JSONPathType):
  50. def _format_value(self, value):
  51. return "$%s" % (
  52. "".join([
  53. "[%s]" % elem if isinstance(elem, int)
  54. else '."%s"' % elem for elem in value
  55. ])
  56. )