hstore.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. # dialects/postgresql/hstore.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. # mypy: ignore-errors
  8. import re
  9. from .array import ARRAY
  10. from .operators import CONTAINED_BY
  11. from .operators import CONTAINS
  12. from .operators import GETITEM
  13. from .operators import HAS_ALL
  14. from .operators import HAS_ANY
  15. from .operators import HAS_KEY
  16. from ... import types as sqltypes
  17. from ...sql import functions as sqlfunc
  18. __all__ = ("HSTORE", "hstore")
  19. class HSTORE(sqltypes.Indexable, sqltypes.Concatenable, sqltypes.TypeEngine):
  20. """Represent the PostgreSQL HSTORE type.
  21. The :class:`.HSTORE` type stores dictionaries containing strings, e.g.::
  22. data_table = Table('data_table', metadata,
  23. Column('id', Integer, primary_key=True),
  24. Column('data', HSTORE)
  25. )
  26. with engine.connect() as conn:
  27. conn.execute(
  28. data_table.insert(),
  29. data = {"key1": "value1", "key2": "value2"}
  30. )
  31. :class:`.HSTORE` provides for a wide range of operations, including:
  32. * Index operations::
  33. data_table.c.data['some key'] == 'some value'
  34. * Containment operations::
  35. data_table.c.data.has_key('some key')
  36. data_table.c.data.has_all(['one', 'two', 'three'])
  37. * Concatenation::
  38. data_table.c.data + {"k1": "v1"}
  39. For a full list of special methods see
  40. :class:`.HSTORE.comparator_factory`.
  41. .. container:: topic
  42. **Detecting Changes in HSTORE columns when using the ORM**
  43. For usage with the SQLAlchemy ORM, it may be desirable to combine the
  44. usage of :class:`.HSTORE` with :class:`.MutableDict` dictionary now
  45. part of the :mod:`sqlalchemy.ext.mutable` extension. This extension
  46. will allow "in-place" changes to the dictionary, e.g. addition of new
  47. keys or replacement/removal of existing keys to/from the current
  48. dictionary, to produce events which will be detected by the unit of
  49. work::
  50. from sqlalchemy.ext.mutable import MutableDict
  51. class MyClass(Base):
  52. __tablename__ = 'data_table'
  53. id = Column(Integer, primary_key=True)
  54. data = Column(MutableDict.as_mutable(HSTORE))
  55. my_object = session.query(MyClass).one()
  56. # in-place mutation, requires Mutable extension
  57. # in order for the ORM to detect
  58. my_object.data['some_key'] = 'some value'
  59. session.commit()
  60. When the :mod:`sqlalchemy.ext.mutable` extension is not used, the ORM
  61. will not be alerted to any changes to the contents of an existing
  62. dictionary, unless that dictionary value is re-assigned to the
  63. HSTORE-attribute itself, thus generating a change event.
  64. .. seealso::
  65. :class:`.hstore` - render the PostgreSQL ``hstore()`` function.
  66. """
  67. __visit_name__ = "HSTORE"
  68. hashable = False
  69. text_type = sqltypes.Text()
  70. def __init__(self, text_type=None):
  71. """Construct a new :class:`.HSTORE`.
  72. :param text_type: the type that should be used for indexed values.
  73. Defaults to :class:`_types.Text`.
  74. """
  75. if text_type is not None:
  76. self.text_type = text_type
  77. class Comparator(
  78. sqltypes.Indexable.Comparator, sqltypes.Concatenable.Comparator
  79. ):
  80. """Define comparison operations for :class:`.HSTORE`."""
  81. def has_key(self, other):
  82. """Boolean expression. Test for presence of a key. Note that the
  83. key may be a SQLA expression.
  84. """
  85. return self.operate(HAS_KEY, other, result_type=sqltypes.Boolean)
  86. def has_all(self, other):
  87. """Boolean expression. Test for presence of all keys in jsonb"""
  88. return self.operate(HAS_ALL, other, result_type=sqltypes.Boolean)
  89. def has_any(self, other):
  90. """Boolean expression. Test for presence of any key in jsonb"""
  91. return self.operate(HAS_ANY, other, result_type=sqltypes.Boolean)
  92. def contains(self, other, **kwargs):
  93. """Boolean expression. Test if keys (or array) are a superset
  94. of/contained the keys of the argument jsonb expression.
  95. kwargs may be ignored by this operator but are required for API
  96. conformance.
  97. """
  98. return self.operate(CONTAINS, other, result_type=sqltypes.Boolean)
  99. def contained_by(self, other):
  100. """Boolean expression. Test if keys are a proper subset of the
  101. keys of the argument jsonb expression.
  102. """
  103. return self.operate(
  104. CONTAINED_BY, other, result_type=sqltypes.Boolean
  105. )
  106. def _setup_getitem(self, index):
  107. return GETITEM, index, self.type.text_type
  108. def defined(self, key):
  109. """Boolean expression. Test for presence of a non-NULL value for
  110. the key. Note that the key may be a SQLA expression.
  111. """
  112. return _HStoreDefinedFunction(self.expr, key)
  113. def delete(self, key):
  114. """HStore expression. Returns the contents of this hstore with the
  115. given key deleted. Note that the key may be a SQLA expression.
  116. """
  117. if isinstance(key, dict):
  118. key = _serialize_hstore(key)
  119. return _HStoreDeleteFunction(self.expr, key)
  120. def slice(self, array):
  121. """HStore expression. Returns a subset of an hstore defined by
  122. array of keys.
  123. """
  124. return _HStoreSliceFunction(self.expr, array)
  125. def keys(self):
  126. """Text array expression. Returns array of keys."""
  127. return _HStoreKeysFunction(self.expr)
  128. def vals(self):
  129. """Text array expression. Returns array of values."""
  130. return _HStoreValsFunction(self.expr)
  131. def array(self):
  132. """Text array expression. Returns array of alternating keys and
  133. values.
  134. """
  135. return _HStoreArrayFunction(self.expr)
  136. def matrix(self):
  137. """Text array expression. Returns array of [key, value] pairs."""
  138. return _HStoreMatrixFunction(self.expr)
  139. comparator_factory = Comparator
  140. def bind_processor(self, dialect):
  141. def process(value):
  142. if isinstance(value, dict):
  143. return _serialize_hstore(value)
  144. else:
  145. return value
  146. return process
  147. def result_processor(self, dialect, coltype):
  148. def process(value):
  149. if value is not None:
  150. return _parse_hstore(value)
  151. else:
  152. return value
  153. return process
  154. class hstore(sqlfunc.GenericFunction):
  155. """Construct an hstore value within a SQL expression using the
  156. PostgreSQL ``hstore()`` function.
  157. The :class:`.hstore` function accepts one or two arguments as described
  158. in the PostgreSQL documentation.
  159. E.g.::
  160. from sqlalchemy.dialects.postgresql import array, hstore
  161. select(hstore('key1', 'value1'))
  162. select(
  163. hstore(
  164. array(['key1', 'key2', 'key3']),
  165. array(['value1', 'value2', 'value3'])
  166. )
  167. )
  168. .. seealso::
  169. :class:`.HSTORE` - the PostgreSQL ``HSTORE`` datatype.
  170. """
  171. type = HSTORE
  172. name = "hstore"
  173. inherit_cache = True
  174. class _HStoreDefinedFunction(sqlfunc.GenericFunction):
  175. type = sqltypes.Boolean
  176. name = "defined"
  177. inherit_cache = True
  178. class _HStoreDeleteFunction(sqlfunc.GenericFunction):
  179. type = HSTORE
  180. name = "delete"
  181. inherit_cache = True
  182. class _HStoreSliceFunction(sqlfunc.GenericFunction):
  183. type = HSTORE
  184. name = "slice"
  185. inherit_cache = True
  186. class _HStoreKeysFunction(sqlfunc.GenericFunction):
  187. type = ARRAY(sqltypes.Text)
  188. name = "akeys"
  189. inherit_cache = True
  190. class _HStoreValsFunction(sqlfunc.GenericFunction):
  191. type = ARRAY(sqltypes.Text)
  192. name = "avals"
  193. inherit_cache = True
  194. class _HStoreArrayFunction(sqlfunc.GenericFunction):
  195. type = ARRAY(sqltypes.Text)
  196. name = "hstore_to_array"
  197. inherit_cache = True
  198. class _HStoreMatrixFunction(sqlfunc.GenericFunction):
  199. type = ARRAY(sqltypes.Text)
  200. name = "hstore_to_matrix"
  201. inherit_cache = True
  202. #
  203. # parsing. note that none of this is used with the psycopg2 backend,
  204. # which provides its own native extensions.
  205. #
  206. # My best guess at the parsing rules of hstore literals, since no formal
  207. # grammar is given. This is mostly reverse engineered from PG's input parser
  208. # behavior.
  209. HSTORE_PAIR_RE = re.compile(
  210. r"""
  211. (
  212. "(?P<key> (\\ . | [^"])* )" # Quoted key
  213. )
  214. [ ]* => [ ]* # Pair operator, optional adjoining whitespace
  215. (
  216. (?P<value_null> NULL ) # NULL value
  217. | "(?P<value> (\\ . | [^"])* )" # Quoted value
  218. )
  219. """,
  220. re.VERBOSE,
  221. )
  222. HSTORE_DELIMITER_RE = re.compile(
  223. r"""
  224. [ ]* , [ ]*
  225. """,
  226. re.VERBOSE,
  227. )
  228. def _parse_error(hstore_str, pos):
  229. """format an unmarshalling error."""
  230. ctx = 20
  231. hslen = len(hstore_str)
  232. parsed_tail = hstore_str[max(pos - ctx - 1, 0) : min(pos, hslen)]
  233. residual = hstore_str[min(pos, hslen) : min(pos + ctx + 1, hslen)]
  234. if len(parsed_tail) > ctx:
  235. parsed_tail = "[...]" + parsed_tail[1:]
  236. if len(residual) > ctx:
  237. residual = residual[:-1] + "[...]"
  238. return "After %r, could not parse residual at position %d: %r" % (
  239. parsed_tail,
  240. pos,
  241. residual,
  242. )
  243. def _parse_hstore(hstore_str):
  244. """Parse an hstore from its literal string representation.
  245. Attempts to approximate PG's hstore input parsing rules as closely as
  246. possible. Although currently this is not strictly necessary, since the
  247. current implementation of hstore's output syntax is stricter than what it
  248. accepts as input, the documentation makes no guarantees that will always
  249. be the case.
  250. """
  251. result = {}
  252. pos = 0
  253. pair_match = HSTORE_PAIR_RE.match(hstore_str)
  254. while pair_match is not None:
  255. key = pair_match.group("key").replace(r"\"", '"').replace("\\\\", "\\")
  256. if pair_match.group("value_null"):
  257. value = None
  258. else:
  259. value = (
  260. pair_match.group("value")
  261. .replace(r"\"", '"')
  262. .replace("\\\\", "\\")
  263. )
  264. result[key] = value
  265. pos += pair_match.end()
  266. delim_match = HSTORE_DELIMITER_RE.match(hstore_str[pos:])
  267. if delim_match is not None:
  268. pos += delim_match.end()
  269. pair_match = HSTORE_PAIR_RE.match(hstore_str[pos:])
  270. if pos != len(hstore_str):
  271. raise ValueError(_parse_error(hstore_str, pos))
  272. return result
  273. def _serialize_hstore(val):
  274. """Serialize a dictionary into an hstore literal. Keys and values must
  275. both be strings (except None for values).
  276. """
  277. def esc(s, position):
  278. if position == "value" and s is None:
  279. return "NULL"
  280. elif isinstance(s, str):
  281. return '"%s"' % s.replace("\\", "\\\\").replace('"', r"\"")
  282. else:
  283. raise ValueError(
  284. "%r in %s position is not a string." % (s, position)
  285. )
  286. return ", ".join(
  287. "%s=>%s" % (esc(k, "key"), esc(v, "value")) for k, v in val.items()
  288. )