json.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # dialects/sqlite/json.py
  2. # Copyright (C) 2005-2024 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: https://www.opensource.org/licenses/mit-license.php
  7. from ... import types as sqltypes
  8. class JSON(sqltypes.JSON):
  9. """SQLite JSON type.
  10. SQLite supports JSON as of version 3.9 through its JSON1_ extension. Note
  11. that JSON1_ is a
  12. `loadable extension <https://www.sqlite.org/loadext.html>`_ and as such
  13. may not be available, or may require run-time loading.
  14. :class:`_sqlite.JSON` is used automatically whenever the base
  15. :class:`_types.JSON` datatype is used against a SQLite backend.
  16. .. seealso::
  17. :class:`_types.JSON` - main documentation for the generic
  18. cross-platform JSON datatype.
  19. The :class:`_sqlite.JSON` type supports persistence of JSON values
  20. as well as the core index operations provided by :class:`_types.JSON`
  21. datatype, by adapting the operations to render the ``JSON_EXTRACT``
  22. function wrapped in the ``JSON_QUOTE`` function at the database level.
  23. Extracted values are quoted in order to ensure that the results are
  24. always JSON string values.
  25. .. versionadded:: 1.3
  26. .. _JSON1: https://www.sqlite.org/json1.html
  27. """
  28. # Note: these objects currently match exactly those of MySQL, however since
  29. # these are not generalizable to all JSON implementations, remain separately
  30. # implemented for each dialect.
  31. class _FormatTypeMixin(object):
  32. def _format_value(self, value):
  33. raise NotImplementedError()
  34. def bind_processor(self, dialect):
  35. super_proc = self.string_bind_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. def literal_processor(self, dialect):
  43. super_proc = self.string_literal_processor(dialect)
  44. def process(value):
  45. value = self._format_value(value)
  46. if super_proc:
  47. value = super_proc(value)
  48. return value
  49. return process
  50. class JSONIndexType(_FormatTypeMixin, sqltypes.JSON.JSONIndexType):
  51. def _format_value(self, value):
  52. if isinstance(value, int):
  53. value = "$[%s]" % value
  54. else:
  55. value = '$."%s"' % value
  56. return value
  57. class JSONPathType(_FormatTypeMixin, sqltypes.JSON.JSONPathType):
  58. def _format_value(self, value):
  59. return "$%s" % (
  60. "".join(
  61. [
  62. "[%s]" % elem if isinstance(elem, int) else '."%s"' % elem
  63. for elem in value
  64. ]
  65. )
  66. )