Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

85 linhas
2.3KB

  1. # mysql/json.py
  2. # Copyright (C) 2005-2021 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. from ... import types as sqltypes
  9. class JSON(sqltypes.JSON):
  10. """MySQL JSON type.
  11. MySQL supports JSON as of version 5.7.
  12. MariaDB supports JSON (as an alias for LONGTEXT) as of version 10.2.
  13. :class:`_mysql.JSON` is used automatically whenever the base
  14. :class:`_types.JSON` datatype is used against a MySQL or MariaDB backend.
  15. .. seealso::
  16. :class:`_types.JSON` - main documentation for the generic
  17. cross-platform JSON datatype.
  18. The :class:`.mysql.JSON` type supports persistence of JSON values
  19. as well as the core index operations provided by :class:`_types.JSON`
  20. datatype, by adapting the operations to render the ``JSON_EXTRACT``
  21. function at the database level.
  22. .. versionadded:: 1.1
  23. """
  24. pass
  25. class _FormatTypeMixin(object):
  26. def _format_value(self, value):
  27. raise NotImplementedError()
  28. def bind_processor(self, dialect):
  29. super_proc = self.string_bind_processor(dialect)
  30. def process(value):
  31. value = self._format_value(value)
  32. if super_proc:
  33. value = super_proc(value)
  34. return value
  35. return process
  36. def literal_processor(self, dialect):
  37. super_proc = self.string_literal_processor(dialect)
  38. def process(value):
  39. value = self._format_value(value)
  40. if super_proc:
  41. value = super_proc(value)
  42. return value
  43. return process
  44. class JSONIndexType(_FormatTypeMixin, sqltypes.JSON.JSONIndexType):
  45. def _format_value(self, value):
  46. if isinstance(value, int):
  47. value = "$[%s]" % value
  48. else:
  49. value = '$."%s"' % value
  50. return value
  51. class JSONPathType(_FormatTypeMixin, sqltypes.JSON.JSONPathType):
  52. def _format_value(self, value):
  53. return "$%s" % (
  54. "".join(
  55. [
  56. "[%s]" % elem if isinstance(elem, int) else '."%s"' % elem
  57. for elem in value
  58. ]
  59. )
  60. )