json.py 4.6 KB

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