_json.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. """Implementation of the JSON adaptation objects
  2. This module exists to avoid a circular import problem: pyscopg2.extras depends
  3. on psycopg2.extension, so I can't create the default JSON typecasters in
  4. extensions importing register_json from extras.
  5. """
  6. # psycopg/_json.py - Implementation of the JSON adaptation objects
  7. #
  8. # Copyright (C) 2012-2019 Daniele Varrazzo <daniele.varrazzo@gmail.com>
  9. # Copyright (C) 2020-2021 The Psycopg Team
  10. #
  11. # psycopg2 is free software: you can redistribute it and/or modify it
  12. # under the terms of the GNU Lesser General Public License as published
  13. # by the Free Software Foundation, either version 3 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # In addition, as a special exception, the copyright holders give
  17. # permission to link this program with the OpenSSL library (or with
  18. # modified versions of OpenSSL that use the same license as OpenSSL),
  19. # and distribute linked combinations including the two.
  20. #
  21. # You must obey the GNU Lesser General Public License in all respects for
  22. # all of the code used other than OpenSSL.
  23. #
  24. # psycopg2 is distributed in the hope that it will be useful, but WITHOUT
  25. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  26. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  27. # License for more details.
  28. import json
  29. from psycopg2._psycopg import ISQLQuote, QuotedString
  30. from psycopg2._psycopg import new_type, new_array_type, register_type
  31. # oids from PostgreSQL 9.2
  32. JSON_OID = 114
  33. JSONARRAY_OID = 199
  34. # oids from PostgreSQL 9.4
  35. JSONB_OID = 3802
  36. JSONBARRAY_OID = 3807
  37. class Json:
  38. """
  39. An `~psycopg2.extensions.ISQLQuote` wrapper to adapt a Python object to
  40. :sql:`json` data type.
  41. `!Json` can be used to wrap any object supported by the provided *dumps*
  42. function. If none is provided, the standard :py:func:`json.dumps()` is
  43. used.
  44. """
  45. def __init__(self, adapted, dumps=None):
  46. self.adapted = adapted
  47. self._conn = None
  48. self._dumps = dumps or json.dumps
  49. def __conform__(self, proto):
  50. if proto is ISQLQuote:
  51. return self
  52. def dumps(self, obj):
  53. """Serialize *obj* in JSON format.
  54. The default is to call `!json.dumps()` or the *dumps* function
  55. provided in the constructor. You can override this method to create a
  56. customized JSON wrapper.
  57. """
  58. return self._dumps(obj)
  59. def prepare(self, conn):
  60. self._conn = conn
  61. def getquoted(self):
  62. s = self.dumps(self.adapted)
  63. qs = QuotedString(s)
  64. if self._conn is not None:
  65. qs.prepare(self._conn)
  66. return qs.getquoted()
  67. def __str__(self):
  68. # getquoted is binary
  69. return self.getquoted().decode('ascii', 'replace')
  70. def register_json(conn_or_curs=None, globally=False, loads=None,
  71. oid=None, array_oid=None, name='json'):
  72. """Create and register typecasters converting :sql:`json` type to Python objects.
  73. :param conn_or_curs: a connection or cursor used to find the :sql:`json`
  74. and :sql:`json[]` oids; the typecasters are registered in a scope
  75. limited to this object, unless *globally* is set to `!True`. It can be
  76. `!None` if the oids are provided
  77. :param globally: if `!False` register the typecasters only on
  78. *conn_or_curs*, otherwise register them globally
  79. :param loads: the function used to parse the data into a Python object. If
  80. `!None` use `!json.loads()`, where `!json` is the module chosen
  81. according to the Python version (see above)
  82. :param oid: the OID of the :sql:`json` type if known; If not, it will be
  83. queried on *conn_or_curs*
  84. :param array_oid: the OID of the :sql:`json[]` array type if known;
  85. if not, it will be queried on *conn_or_curs*
  86. :param name: the name of the data type to look for in *conn_or_curs*
  87. The connection or cursor passed to the function will be used to query the
  88. database and look for the OID of the :sql:`json` type (or an alternative
  89. type if *name* if provided). No query is performed if *oid* and *array_oid*
  90. are provided. Raise `~psycopg2.ProgrammingError` if the type is not found.
  91. """
  92. if oid is None:
  93. oid, array_oid = _get_json_oids(conn_or_curs, name)
  94. JSON, JSONARRAY = _create_json_typecasters(
  95. oid, array_oid, loads=loads, name=name.upper())
  96. register_type(JSON, not globally and conn_or_curs or None)
  97. if JSONARRAY is not None:
  98. register_type(JSONARRAY, not globally and conn_or_curs or None)
  99. return JSON, JSONARRAY
  100. def register_default_json(conn_or_curs=None, globally=False, loads=None):
  101. """
  102. Create and register :sql:`json` typecasters for PostgreSQL 9.2 and following.
  103. Since PostgreSQL 9.2 :sql:`json` is a builtin type, hence its oid is known
  104. and fixed. This function allows specifying a customized *loads* function
  105. for the default :sql:`json` type without querying the database.
  106. All the parameters have the same meaning of `register_json()`.
  107. """
  108. return register_json(conn_or_curs=conn_or_curs, globally=globally,
  109. loads=loads, oid=JSON_OID, array_oid=JSONARRAY_OID)
  110. def register_default_jsonb(conn_or_curs=None, globally=False, loads=None):
  111. """
  112. Create and register :sql:`jsonb` typecasters for PostgreSQL 9.4 and following.
  113. As in `register_default_json()`, the function allows to register a
  114. customized *loads* function for the :sql:`jsonb` type at its known oid for
  115. PostgreSQL 9.4 and following versions. All the parameters have the same
  116. meaning of `register_json()`.
  117. """
  118. return register_json(conn_or_curs=conn_or_curs, globally=globally,
  119. loads=loads, oid=JSONB_OID, array_oid=JSONBARRAY_OID, name='jsonb')
  120. def _create_json_typecasters(oid, array_oid, loads=None, name='JSON'):
  121. """Create typecasters for json data type."""
  122. if loads is None:
  123. loads = json.loads
  124. def typecast_json(s, cur):
  125. if s is None:
  126. return None
  127. return loads(s)
  128. JSON = new_type((oid, ), name, typecast_json)
  129. if array_oid is not None:
  130. JSONARRAY = new_array_type((array_oid, ), f"{name}ARRAY", JSON)
  131. else:
  132. JSONARRAY = None
  133. return JSON, JSONARRAY
  134. def _get_json_oids(conn_or_curs, name='json'):
  135. # lazy imports
  136. from psycopg2.extensions import STATUS_IN_TRANSACTION
  137. from psycopg2.extras import _solve_conn_curs
  138. conn, curs = _solve_conn_curs(conn_or_curs)
  139. # Store the transaction status of the connection to revert it after use
  140. conn_status = conn.status
  141. # column typarray not available before PG 8.3
  142. typarray = conn.info.server_version >= 80300 and "typarray" or "NULL"
  143. # get the oid for the hstore
  144. curs.execute(
  145. "SELECT t.oid, %s FROM pg_type t WHERE t.typname = %%s;"
  146. % typarray, (name,))
  147. r = curs.fetchone()
  148. # revert the status of the connection as before the command
  149. if conn_status != STATUS_IN_TRANSACTION and not conn.autocommit:
  150. conn.rollback()
  151. if not r:
  152. raise conn.ProgrammingError(f"{name} data type not found")
  153. return r