You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

445 lines
12KB

  1. # postgresql/hstore.py
  2. # Copyright (C) 2005-2021 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: http://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. """
  127. return self.operate(CONTAINS, other, result_type=sqltypes.Boolean)
  128. def contained_by(self, other):
  129. """Boolean expression. Test if keys are a proper subset of the
  130. keys of the argument jsonb expression.
  131. """
  132. return self.operate(
  133. CONTAINED_BY, other, result_type=sqltypes.Boolean
  134. )
  135. def _setup_getitem(self, index):
  136. return GETITEM, index, self.type.text_type
  137. def defined(self, key):
  138. """Boolean expression. Test for presence of a non-NULL value for
  139. the key. Note that the key may be a SQLA expression.
  140. """
  141. return _HStoreDefinedFunction(self.expr, key)
  142. def delete(self, key):
  143. """HStore expression. Returns the contents of this hstore with the
  144. given key deleted. Note that the key may be a SQLA expression.
  145. """
  146. if isinstance(key, dict):
  147. key = _serialize_hstore(key)
  148. return _HStoreDeleteFunction(self.expr, key)
  149. def slice(self, array):
  150. """HStore expression. Returns a subset of an hstore defined by
  151. array of keys.
  152. """
  153. return _HStoreSliceFunction(self.expr, array)
  154. def keys(self):
  155. """Text array expression. Returns array of keys."""
  156. return _HStoreKeysFunction(self.expr)
  157. def vals(self):
  158. """Text array expression. Returns array of values."""
  159. return _HStoreValsFunction(self.expr)
  160. def array(self):
  161. """Text array expression. Returns array of alternating keys and
  162. values.
  163. """
  164. return _HStoreArrayFunction(self.expr)
  165. def matrix(self):
  166. """Text array expression. Returns array of [key, value] pairs."""
  167. return _HStoreMatrixFunction(self.expr)
  168. comparator_factory = Comparator
  169. def bind_processor(self, dialect):
  170. if util.py2k:
  171. encoding = dialect.encoding
  172. def process(value):
  173. if isinstance(value, dict):
  174. return _serialize_hstore(value).encode(encoding)
  175. else:
  176. return value
  177. else:
  178. def process(value):
  179. if isinstance(value, dict):
  180. return _serialize_hstore(value)
  181. else:
  182. return value
  183. return process
  184. def result_processor(self, dialect, coltype):
  185. if util.py2k:
  186. encoding = dialect.encoding
  187. def process(value):
  188. if value is not None:
  189. return _parse_hstore(value.decode(encoding))
  190. else:
  191. return value
  192. else:
  193. def process(value):
  194. if value is not None:
  195. return _parse_hstore(value)
  196. else:
  197. return value
  198. return process
  199. class hstore(sqlfunc.GenericFunction):
  200. """Construct an hstore value within a SQL expression using the
  201. PostgreSQL ``hstore()`` function.
  202. The :class:`.hstore` function accepts one or two arguments as described
  203. in the PostgreSQL documentation.
  204. E.g.::
  205. from sqlalchemy.dialects.postgresql import array, hstore
  206. select(hstore('key1', 'value1'))
  207. select(
  208. hstore(
  209. array(['key1', 'key2', 'key3']),
  210. array(['value1', 'value2', 'value3'])
  211. )
  212. )
  213. .. seealso::
  214. :class:`.HSTORE` - the PostgreSQL ``HSTORE`` datatype.
  215. """
  216. type = HSTORE
  217. name = "hstore"
  218. class _HStoreDefinedFunction(sqlfunc.GenericFunction):
  219. type = sqltypes.Boolean
  220. name = "defined"
  221. class _HStoreDeleteFunction(sqlfunc.GenericFunction):
  222. type = HSTORE
  223. name = "delete"
  224. class _HStoreSliceFunction(sqlfunc.GenericFunction):
  225. type = HSTORE
  226. name = "slice"
  227. class _HStoreKeysFunction(sqlfunc.GenericFunction):
  228. type = ARRAY(sqltypes.Text)
  229. name = "akeys"
  230. class _HStoreValsFunction(sqlfunc.GenericFunction):
  231. type = ARRAY(sqltypes.Text)
  232. name = "avals"
  233. class _HStoreArrayFunction(sqlfunc.GenericFunction):
  234. type = ARRAY(sqltypes.Text)
  235. name = "hstore_to_array"
  236. class _HStoreMatrixFunction(sqlfunc.GenericFunction):
  237. type = ARRAY(sqltypes.Text)
  238. name = "hstore_to_matrix"
  239. #
  240. # parsing. note that none of this is used with the psycopg2 backend,
  241. # which provides its own native extensions.
  242. #
  243. # My best guess at the parsing rules of hstore literals, since no formal
  244. # grammar is given. This is mostly reverse engineered from PG's input parser
  245. # behavior.
  246. HSTORE_PAIR_RE = re.compile(
  247. r"""
  248. (
  249. "(?P<key> (\\ . | [^"])* )" # Quoted key
  250. )
  251. [ ]* => [ ]* # Pair operator, optional adjoining whitespace
  252. (
  253. (?P<value_null> NULL ) # NULL value
  254. | "(?P<value> (\\ . | [^"])* )" # Quoted value
  255. )
  256. """,
  257. re.VERBOSE,
  258. )
  259. HSTORE_DELIMITER_RE = re.compile(
  260. r"""
  261. [ ]* , [ ]*
  262. """,
  263. re.VERBOSE,
  264. )
  265. def _parse_error(hstore_str, pos):
  266. """format an unmarshalling error."""
  267. ctx = 20
  268. hslen = len(hstore_str)
  269. parsed_tail = hstore_str[max(pos - ctx - 1, 0) : min(pos, hslen)]
  270. residual = hstore_str[min(pos, hslen) : min(pos + ctx + 1, hslen)]
  271. if len(parsed_tail) > ctx:
  272. parsed_tail = "[...]" + parsed_tail[1:]
  273. if len(residual) > ctx:
  274. residual = residual[:-1] + "[...]"
  275. return "After %r, could not parse residual at position %d: %r" % (
  276. parsed_tail,
  277. pos,
  278. residual,
  279. )
  280. def _parse_hstore(hstore_str):
  281. """Parse an hstore from its literal string representation.
  282. Attempts to approximate PG's hstore input parsing rules as closely as
  283. possible. Although currently this is not strictly necessary, since the
  284. current implementation of hstore's output syntax is stricter than what it
  285. accepts as input, the documentation makes no guarantees that will always
  286. be the case.
  287. """
  288. result = {}
  289. pos = 0
  290. pair_match = HSTORE_PAIR_RE.match(hstore_str)
  291. while pair_match is not None:
  292. key = pair_match.group("key").replace(r"\"", '"').replace("\\\\", "\\")
  293. if pair_match.group("value_null"):
  294. value = None
  295. else:
  296. value = (
  297. pair_match.group("value")
  298. .replace(r"\"", '"')
  299. .replace("\\\\", "\\")
  300. )
  301. result[key] = value
  302. pos += pair_match.end()
  303. delim_match = HSTORE_DELIMITER_RE.match(hstore_str[pos:])
  304. if delim_match is not None:
  305. pos += delim_match.end()
  306. pair_match = HSTORE_PAIR_RE.match(hstore_str[pos:])
  307. if pos != len(hstore_str):
  308. raise ValueError(_parse_error(hstore_str, pos))
  309. return result
  310. def _serialize_hstore(val):
  311. """Serialize a dictionary into an hstore literal. Keys and values must
  312. both be strings (except None for values).
  313. """
  314. def esc(s, position):
  315. if position == "value" and s is None:
  316. return "NULL"
  317. elif isinstance(s, util.string_types):
  318. return '"%s"' % s.replace("\\", "\\\\").replace('"', r"\"")
  319. else:
  320. raise ValueError(
  321. "%r in %s position is not a string." % (s, position)
  322. )
  323. return ", ".join(
  324. "%s=>%s" % (esc(k, "key"), esc(v, "value")) for k, v in val.items()
  325. )