json.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. # dialects/mssql/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. # technically, all the dialect-specific datatypes that don't have any special
  9. # behaviors would be private with names like _MSJson. However, we haven't been
  10. # doing this for mysql.JSON or sqlite.JSON which both have JSON / JSONIndexType
  11. # / JSONPathType in their json.py files, so keep consistent with that
  12. # sub-convention for now. A future change can update them all to be
  13. # package-private at once.
  14. class JSON(sqltypes.JSON):
  15. """MSSQL JSON type.
  16. MSSQL supports JSON-formatted data as of SQL Server 2016.
  17. The :class:`_mssql.JSON` datatype at the DDL level will represent the
  18. datatype as ``NVARCHAR(max)``, but provides for JSON-level comparison
  19. functions as well as Python coercion behavior.
  20. :class:`_mssql.JSON` is used automatically whenever the base
  21. :class:`_types.JSON` datatype is used against a SQL Server backend.
  22. .. seealso::
  23. :class:`_types.JSON` - main documentation for the generic
  24. cross-platform JSON datatype.
  25. The :class:`_mssql.JSON` type supports persistence of JSON values
  26. as well as the core index operations provided by :class:`_types.JSON`
  27. datatype, by adapting the operations to render the ``JSON_VALUE``
  28. or ``JSON_QUERY`` functions at the database level.
  29. The SQL Server :class:`_mssql.JSON` type necessarily makes use of the
  30. ``JSON_QUERY`` and ``JSON_VALUE`` functions when querying for elements
  31. of a JSON object. These two functions have a major restriction in that
  32. they are **mutually exclusive** based on the type of object to be returned.
  33. The ``JSON_QUERY`` function **only** returns a JSON dictionary or list,
  34. but not an individual string, numeric, or boolean element; the
  35. ``JSON_VALUE`` function **only** returns an individual string, numeric,
  36. or boolean element. **both functions either return NULL or raise
  37. an error if they are not used against the correct expected value**.
  38. To handle this awkward requirement, indexed access rules are as follows:
  39. 1. When extracting a sub element from a JSON that is itself a JSON
  40. dictionary or list, the :meth:`_types.JSON.Comparator.as_json` accessor
  41. should be used::
  42. stmt = select(
  43. data_table.c.data["some key"].as_json()
  44. ).where(
  45. data_table.c.data["some key"].as_json() == {"sub": "structure"}
  46. )
  47. 2. When extracting a sub element from a JSON that is a plain boolean,
  48. string, integer, or float, use the appropriate method among
  49. :meth:`_types.JSON.Comparator.as_boolean`,
  50. :meth:`_types.JSON.Comparator.as_string`,
  51. :meth:`_types.JSON.Comparator.as_integer`,
  52. :meth:`_types.JSON.Comparator.as_float`::
  53. stmt = select(
  54. data_table.c.data["some key"].as_string()
  55. ).where(
  56. data_table.c.data["some key"].as_string() == "some string"
  57. )
  58. .. versionadded:: 1.4
  59. """
  60. # note there was a result processor here that was looking for "number",
  61. # but none of the tests seem to exercise it.
  62. # Note: these objects currently match exactly those of MySQL, however since
  63. # these are not generalizable to all JSON implementations, remain separately
  64. # implemented for each dialect.
  65. class _FormatTypeMixin(object):
  66. def _format_value(self, value):
  67. raise NotImplementedError()
  68. def bind_processor(self, dialect):
  69. super_proc = self.string_bind_processor(dialect)
  70. def process(value):
  71. value = self._format_value(value)
  72. if super_proc:
  73. value = super_proc(value)
  74. return value
  75. return process
  76. def literal_processor(self, dialect):
  77. super_proc = self.string_literal_processor(dialect)
  78. def process(value):
  79. value = self._format_value(value)
  80. if super_proc:
  81. value = super_proc(value)
  82. return value
  83. return process
  84. class JSONIndexType(_FormatTypeMixin, sqltypes.JSON.JSONIndexType):
  85. def _format_value(self, value):
  86. if isinstance(value, int):
  87. value = "$[%s]" % value
  88. else:
  89. value = '$."%s"' % value
  90. return value
  91. class JSONPathType(_FormatTypeMixin, sqltypes.JSON.JSONPathType):
  92. def _format_value(self, value):
  93. return "$%s" % (
  94. "".join(
  95. [
  96. "[%s]" % elem if isinstance(elem, int) else '."%s"' % elem
  97. for elem in value
  98. ]
  99. )
  100. )