json.py 4.6 KB

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