hstore.py 13 KB

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