ranges.py 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. # dialects/postgresql/ranges.py
  2. # Copyright (C) 2013-2025 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. from __future__ import annotations
  8. import dataclasses
  9. from datetime import date
  10. from datetime import datetime
  11. from datetime import timedelta
  12. from decimal import Decimal
  13. from typing import Any
  14. from typing import cast
  15. from typing import Generic
  16. from typing import List
  17. from typing import Optional
  18. from typing import overload
  19. from typing import Sequence
  20. from typing import Tuple
  21. from typing import Type
  22. from typing import TYPE_CHECKING
  23. from typing import TypeVar
  24. from typing import Union
  25. from .operators import ADJACENT_TO
  26. from .operators import CONTAINED_BY
  27. from .operators import CONTAINS
  28. from .operators import NOT_EXTEND_LEFT_OF
  29. from .operators import NOT_EXTEND_RIGHT_OF
  30. from .operators import OVERLAP
  31. from .operators import STRICTLY_LEFT_OF
  32. from .operators import STRICTLY_RIGHT_OF
  33. from ... import types as sqltypes
  34. from ...sql import operators
  35. from ...sql.type_api import TypeEngine
  36. from ...util import py310
  37. from ...util.typing import Literal
  38. if TYPE_CHECKING:
  39. from ...sql.elements import ColumnElement
  40. from ...sql.type_api import _TE
  41. from ...sql.type_api import TypeEngineMixin
  42. _T = TypeVar("_T", bound=Any)
  43. _BoundsType = Literal["()", "[)", "(]", "[]"]
  44. if py310:
  45. dc_slots = {"slots": True}
  46. dc_kwonly = {"kw_only": True}
  47. else:
  48. dc_slots = {}
  49. dc_kwonly = {}
  50. @dataclasses.dataclass(frozen=True, **dc_slots)
  51. class Range(Generic[_T]):
  52. """Represent a PostgreSQL range.
  53. E.g.::
  54. r = Range(10, 50, bounds="()")
  55. The calling style is similar to that of psycopg and psycopg2, in part
  56. to allow easier migration from previous SQLAlchemy versions that used
  57. these objects directly.
  58. :param lower: Lower bound value, or None
  59. :param upper: Upper bound value, or None
  60. :param bounds: keyword-only, optional string value that is one of
  61. ``"()"``, ``"[)"``, ``"(]"``, ``"[]"``. Defaults to ``"[)"``.
  62. :param empty: keyword-only, optional bool indicating this is an "empty"
  63. range
  64. .. versionadded:: 2.0
  65. """
  66. lower: Optional[_T] = None
  67. """the lower bound"""
  68. upper: Optional[_T] = None
  69. """the upper bound"""
  70. if TYPE_CHECKING:
  71. bounds: _BoundsType = dataclasses.field(default="[)")
  72. empty: bool = dataclasses.field(default=False)
  73. else:
  74. bounds: _BoundsType = dataclasses.field(default="[)", **dc_kwonly)
  75. empty: bool = dataclasses.field(default=False, **dc_kwonly)
  76. if not py310:
  77. def __init__(
  78. self,
  79. lower: Optional[_T] = None,
  80. upper: Optional[_T] = None,
  81. *,
  82. bounds: _BoundsType = "[)",
  83. empty: bool = False,
  84. ):
  85. # no __slots__ either so we can update dict
  86. self.__dict__.update(
  87. {
  88. "lower": lower,
  89. "upper": upper,
  90. "bounds": bounds,
  91. "empty": empty,
  92. }
  93. )
  94. def __bool__(self) -> bool:
  95. return not self.empty
  96. @property
  97. def isempty(self) -> bool:
  98. "A synonym for the 'empty' attribute."
  99. return self.empty
  100. @property
  101. def is_empty(self) -> bool:
  102. "A synonym for the 'empty' attribute."
  103. return self.empty
  104. @property
  105. def lower_inc(self) -> bool:
  106. """Return True if the lower bound is inclusive."""
  107. return self.bounds[0] == "["
  108. @property
  109. def lower_inf(self) -> bool:
  110. """Return True if this range is non-empty and lower bound is
  111. infinite."""
  112. return not self.empty and self.lower is None
  113. @property
  114. def upper_inc(self) -> bool:
  115. """Return True if the upper bound is inclusive."""
  116. return self.bounds[1] == "]"
  117. @property
  118. def upper_inf(self) -> bool:
  119. """Return True if this range is non-empty and the upper bound is
  120. infinite."""
  121. return not self.empty and self.upper is None
  122. @property
  123. def __sa_type_engine__(self) -> AbstractSingleRange[_T]:
  124. return AbstractSingleRange()
  125. def _contains_value(self, value: _T) -> bool:
  126. """Return True if this range contains the given value."""
  127. if self.empty:
  128. return False
  129. if self.lower is None:
  130. return self.upper is None or (
  131. value < self.upper
  132. if self.bounds[1] == ")"
  133. else value <= self.upper
  134. )
  135. if self.upper is None:
  136. return ( # type: ignore
  137. value > self.lower
  138. if self.bounds[0] == "("
  139. else value >= self.lower
  140. )
  141. return ( # type: ignore
  142. value > self.lower
  143. if self.bounds[0] == "("
  144. else value >= self.lower
  145. ) and (
  146. value < self.upper
  147. if self.bounds[1] == ")"
  148. else value <= self.upper
  149. )
  150. def _get_discrete_step(self) -> Any:
  151. "Determine the “step” for this range, if it is a discrete one."
  152. # See
  153. # https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-DISCRETE
  154. # for the rationale
  155. if isinstance(self.lower, int) or isinstance(self.upper, int):
  156. return 1
  157. elif isinstance(self.lower, datetime) or isinstance(
  158. self.upper, datetime
  159. ):
  160. # This is required, because a `isinstance(datetime.now(), date)`
  161. # is True
  162. return None
  163. elif isinstance(self.lower, date) or isinstance(self.upper, date):
  164. return timedelta(days=1)
  165. else:
  166. return None
  167. def _compare_edges(
  168. self,
  169. value1: Optional[_T],
  170. bound1: str,
  171. value2: Optional[_T],
  172. bound2: str,
  173. only_values: bool = False,
  174. ) -> int:
  175. """Compare two range bounds.
  176. Return -1, 0 or 1 respectively when `value1` is less than,
  177. equal to or greater than `value2`.
  178. When `only_value` is ``True``, do not consider the *inclusivity*
  179. of the edges, just their values.
  180. """
  181. value1_is_lower_bound = bound1 in {"[", "("}
  182. value2_is_lower_bound = bound2 in {"[", "("}
  183. # Infinite edges are equal when they are on the same side,
  184. # otherwise a lower edge is considered less than the upper end
  185. if value1 is value2 is None:
  186. if value1_is_lower_bound == value2_is_lower_bound:
  187. return 0
  188. else:
  189. return -1 if value1_is_lower_bound else 1
  190. elif value1 is None:
  191. return -1 if value1_is_lower_bound else 1
  192. elif value2 is None:
  193. return 1 if value2_is_lower_bound else -1
  194. # Short path for trivial case
  195. if bound1 == bound2 and value1 == value2:
  196. return 0
  197. value1_inc = bound1 in {"[", "]"}
  198. value2_inc = bound2 in {"[", "]"}
  199. step = self._get_discrete_step()
  200. if step is not None:
  201. # "Normalize" the two edges as '[)', to simplify successive
  202. # logic when the range is discrete: otherwise we would need
  203. # to handle the comparison between ``(0`` and ``[1`` that
  204. # are equal when dealing with integers while for floats the
  205. # former is lesser than the latter
  206. if value1_is_lower_bound:
  207. if not value1_inc:
  208. value1 += step
  209. value1_inc = True
  210. else:
  211. if value1_inc:
  212. value1 += step
  213. value1_inc = False
  214. if value2_is_lower_bound:
  215. if not value2_inc:
  216. value2 += step
  217. value2_inc = True
  218. else:
  219. if value2_inc:
  220. value2 += step
  221. value2_inc = False
  222. if value1 < value2:
  223. return -1
  224. elif value1 > value2:
  225. return 1
  226. elif only_values:
  227. return 0
  228. else:
  229. # Neither one is infinite but are equal, so we
  230. # need to consider the respective inclusive/exclusive
  231. # flag
  232. if value1_inc and value2_inc:
  233. return 0
  234. elif not value1_inc and not value2_inc:
  235. if value1_is_lower_bound == value2_is_lower_bound:
  236. return 0
  237. else:
  238. return 1 if value1_is_lower_bound else -1
  239. elif not value1_inc:
  240. return 1 if value1_is_lower_bound else -1
  241. elif not value2_inc:
  242. return -1 if value2_is_lower_bound else 1
  243. else:
  244. return 0
  245. def __eq__(self, other: Any) -> bool:
  246. """Compare this range to the `other` taking into account
  247. bounds inclusivity, returning ``True`` if they are equal.
  248. """
  249. if not isinstance(other, Range):
  250. return NotImplemented
  251. if self.empty and other.empty:
  252. return True
  253. elif self.empty != other.empty:
  254. return False
  255. slower = self.lower
  256. slower_b = self.bounds[0]
  257. olower = other.lower
  258. olower_b = other.bounds[0]
  259. supper = self.upper
  260. supper_b = self.bounds[1]
  261. oupper = other.upper
  262. oupper_b = other.bounds[1]
  263. return (
  264. self._compare_edges(slower, slower_b, olower, olower_b) == 0
  265. and self._compare_edges(supper, supper_b, oupper, oupper_b) == 0
  266. )
  267. def contained_by(self, other: Range[_T]) -> bool:
  268. "Determine whether this range is a contained by `other`."
  269. # Any range contains the empty one
  270. if self.empty:
  271. return True
  272. # An empty range does not contain any range except the empty one
  273. if other.empty:
  274. return False
  275. slower = self.lower
  276. slower_b = self.bounds[0]
  277. olower = other.lower
  278. olower_b = other.bounds[0]
  279. if self._compare_edges(slower, slower_b, olower, olower_b) < 0:
  280. return False
  281. supper = self.upper
  282. supper_b = self.bounds[1]
  283. oupper = other.upper
  284. oupper_b = other.bounds[1]
  285. if self._compare_edges(supper, supper_b, oupper, oupper_b) > 0:
  286. return False
  287. return True
  288. def contains(self, value: Union[_T, Range[_T]]) -> bool:
  289. "Determine whether this range contains `value`."
  290. if isinstance(value, Range):
  291. return value.contained_by(self)
  292. else:
  293. return self._contains_value(value)
  294. __contains__ = contains
  295. def overlaps(self, other: Range[_T]) -> bool:
  296. "Determine whether this range overlaps with `other`."
  297. # Empty ranges never overlap with any other range
  298. if self.empty or other.empty:
  299. return False
  300. slower = self.lower
  301. slower_b = self.bounds[0]
  302. supper = self.upper
  303. supper_b = self.bounds[1]
  304. olower = other.lower
  305. olower_b = other.bounds[0]
  306. oupper = other.upper
  307. oupper_b = other.bounds[1]
  308. # Check whether this lower bound is contained in the other range
  309. if (
  310. self._compare_edges(slower, slower_b, olower, olower_b) >= 0
  311. and self._compare_edges(slower, slower_b, oupper, oupper_b) <= 0
  312. ):
  313. return True
  314. # Check whether other lower bound is contained in this range
  315. if (
  316. self._compare_edges(olower, olower_b, slower, slower_b) >= 0
  317. and self._compare_edges(olower, olower_b, supper, supper_b) <= 0
  318. ):
  319. return True
  320. return False
  321. def strictly_left_of(self, other: Range[_T]) -> bool:
  322. "Determine whether this range is completely to the left of `other`."
  323. # Empty ranges are neither to left nor to the right of any other range
  324. if self.empty or other.empty:
  325. return False
  326. supper = self.upper
  327. supper_b = self.bounds[1]
  328. olower = other.lower
  329. olower_b = other.bounds[0]
  330. # Check whether this upper edge is less than other's lower end
  331. return self._compare_edges(supper, supper_b, olower, olower_b) < 0
  332. __lshift__ = strictly_left_of
  333. def strictly_right_of(self, other: Range[_T]) -> bool:
  334. "Determine whether this range is completely to the right of `other`."
  335. # Empty ranges are neither to left nor to the right of any other range
  336. if self.empty or other.empty:
  337. return False
  338. slower = self.lower
  339. slower_b = self.bounds[0]
  340. oupper = other.upper
  341. oupper_b = other.bounds[1]
  342. # Check whether this lower edge is greater than other's upper end
  343. return self._compare_edges(slower, slower_b, oupper, oupper_b) > 0
  344. __rshift__ = strictly_right_of
  345. def not_extend_left_of(self, other: Range[_T]) -> bool:
  346. "Determine whether this does not extend to the left of `other`."
  347. # Empty ranges are neither to left nor to the right of any other range
  348. if self.empty or other.empty:
  349. return False
  350. slower = self.lower
  351. slower_b = self.bounds[0]
  352. olower = other.lower
  353. olower_b = other.bounds[0]
  354. # Check whether this lower edge is not less than other's lower end
  355. return self._compare_edges(slower, slower_b, olower, olower_b) >= 0
  356. def not_extend_right_of(self, other: Range[_T]) -> bool:
  357. "Determine whether this does not extend to the right of `other`."
  358. # Empty ranges are neither to left nor to the right of any other range
  359. if self.empty or other.empty:
  360. return False
  361. supper = self.upper
  362. supper_b = self.bounds[1]
  363. oupper = other.upper
  364. oupper_b = other.bounds[1]
  365. # Check whether this upper edge is not greater than other's upper end
  366. return self._compare_edges(supper, supper_b, oupper, oupper_b) <= 0
  367. def _upper_edge_adjacent_to_lower(
  368. self,
  369. value1: Optional[_T],
  370. bound1: str,
  371. value2: Optional[_T],
  372. bound2: str,
  373. ) -> bool:
  374. """Determine whether an upper bound is immediately successive to a
  375. lower bound."""
  376. # Since we need a peculiar way to handle the bounds inclusivity,
  377. # just do a comparison by value here
  378. res = self._compare_edges(value1, bound1, value2, bound2, True)
  379. if res == -1:
  380. step = self._get_discrete_step()
  381. if step is None:
  382. return False
  383. if bound1 == "]":
  384. if bound2 == "[":
  385. return value1 == value2 - step # type: ignore
  386. else:
  387. return value1 == value2
  388. else:
  389. if bound2 == "[":
  390. return value1 == value2
  391. else:
  392. return value1 == value2 - step # type: ignore
  393. elif res == 0:
  394. # Cover cases like [0,0] -|- [1,] and [0,2) -|- (1,3]
  395. if (
  396. bound1 == "]"
  397. and bound2 == "["
  398. or bound1 == ")"
  399. and bound2 == "("
  400. ):
  401. step = self._get_discrete_step()
  402. if step is not None:
  403. return True
  404. return (
  405. bound1 == ")"
  406. and bound2 == "["
  407. or bound1 == "]"
  408. and bound2 == "("
  409. )
  410. else:
  411. return False
  412. def adjacent_to(self, other: Range[_T]) -> bool:
  413. "Determine whether this range is adjacent to the `other`."
  414. # Empty ranges are not adjacent to any other range
  415. if self.empty or other.empty:
  416. return False
  417. slower = self.lower
  418. slower_b = self.bounds[0]
  419. supper = self.upper
  420. supper_b = self.bounds[1]
  421. olower = other.lower
  422. olower_b = other.bounds[0]
  423. oupper = other.upper
  424. oupper_b = other.bounds[1]
  425. return self._upper_edge_adjacent_to_lower(
  426. supper, supper_b, olower, olower_b
  427. ) or self._upper_edge_adjacent_to_lower(
  428. oupper, oupper_b, slower, slower_b
  429. )
  430. def union(self, other: Range[_T]) -> Range[_T]:
  431. """Compute the union of this range with the `other`.
  432. This raises a ``ValueError`` exception if the two ranges are
  433. "disjunct", that is neither adjacent nor overlapping.
  434. """
  435. # Empty ranges are "additive identities"
  436. if self.empty:
  437. return other
  438. if other.empty:
  439. return self
  440. if not self.overlaps(other) and not self.adjacent_to(other):
  441. raise ValueError(
  442. "Adding non-overlapping and non-adjacent"
  443. " ranges is not implemented"
  444. )
  445. slower = self.lower
  446. slower_b = self.bounds[0]
  447. supper = self.upper
  448. supper_b = self.bounds[1]
  449. olower = other.lower
  450. olower_b = other.bounds[0]
  451. oupper = other.upper
  452. oupper_b = other.bounds[1]
  453. if self._compare_edges(slower, slower_b, olower, olower_b) < 0:
  454. rlower = slower
  455. rlower_b = slower_b
  456. else:
  457. rlower = olower
  458. rlower_b = olower_b
  459. if self._compare_edges(supper, supper_b, oupper, oupper_b) > 0:
  460. rupper = supper
  461. rupper_b = supper_b
  462. else:
  463. rupper = oupper
  464. rupper_b = oupper_b
  465. return Range(
  466. rlower, rupper, bounds=cast(_BoundsType, rlower_b + rupper_b)
  467. )
  468. def __add__(self, other: Range[_T]) -> Range[_T]:
  469. return self.union(other)
  470. def difference(self, other: Range[_T]) -> Range[_T]:
  471. """Compute the difference between this range and the `other`.
  472. This raises a ``ValueError`` exception if the two ranges are
  473. "disjunct", that is neither adjacent nor overlapping.
  474. """
  475. # Subtracting an empty range is a no-op
  476. if self.empty or other.empty:
  477. return self
  478. slower = self.lower
  479. slower_b = self.bounds[0]
  480. supper = self.upper
  481. supper_b = self.bounds[1]
  482. olower = other.lower
  483. olower_b = other.bounds[0]
  484. oupper = other.upper
  485. oupper_b = other.bounds[1]
  486. sl_vs_ol = self._compare_edges(slower, slower_b, olower, olower_b)
  487. su_vs_ou = self._compare_edges(supper, supper_b, oupper, oupper_b)
  488. if sl_vs_ol < 0 and su_vs_ou > 0:
  489. raise ValueError(
  490. "Subtracting a strictly inner range is not implemented"
  491. )
  492. sl_vs_ou = self._compare_edges(slower, slower_b, oupper, oupper_b)
  493. su_vs_ol = self._compare_edges(supper, supper_b, olower, olower_b)
  494. # If the ranges do not overlap, result is simply the first
  495. if sl_vs_ou > 0 or su_vs_ol < 0:
  496. return self
  497. # If this range is completely contained by the other, result is empty
  498. if sl_vs_ol >= 0 and su_vs_ou <= 0:
  499. return Range(None, None, empty=True)
  500. # If this range extends to the left of the other and ends in its
  501. # middle
  502. if sl_vs_ol <= 0 and su_vs_ol >= 0 and su_vs_ou <= 0:
  503. rupper_b = ")" if olower_b == "[" else "]"
  504. if (
  505. slower_b != "["
  506. and rupper_b != "]"
  507. and self._compare_edges(slower, slower_b, olower, rupper_b)
  508. == 0
  509. ):
  510. return Range(None, None, empty=True)
  511. else:
  512. return Range(
  513. slower,
  514. olower,
  515. bounds=cast(_BoundsType, slower_b + rupper_b),
  516. )
  517. # If this range starts in the middle of the other and extends to its
  518. # right
  519. if sl_vs_ol >= 0 and su_vs_ou >= 0 and sl_vs_ou <= 0:
  520. rlower_b = "(" if oupper_b == "]" else "["
  521. if (
  522. rlower_b != "["
  523. and supper_b != "]"
  524. and self._compare_edges(oupper, rlower_b, supper, supper_b)
  525. == 0
  526. ):
  527. return Range(None, None, empty=True)
  528. else:
  529. return Range(
  530. oupper,
  531. supper,
  532. bounds=cast(_BoundsType, rlower_b + supper_b),
  533. )
  534. assert False, f"Unhandled case computing {self} - {other}"
  535. def __sub__(self, other: Range[_T]) -> Range[_T]:
  536. return self.difference(other)
  537. def intersection(self, other: Range[_T]) -> Range[_T]:
  538. """Compute the intersection of this range with the `other`.
  539. .. versionadded:: 2.0.10
  540. """
  541. if self.empty or other.empty or not self.overlaps(other):
  542. return Range(None, None, empty=True)
  543. slower = self.lower
  544. slower_b = self.bounds[0]
  545. supper = self.upper
  546. supper_b = self.bounds[1]
  547. olower = other.lower
  548. olower_b = other.bounds[0]
  549. oupper = other.upper
  550. oupper_b = other.bounds[1]
  551. if self._compare_edges(slower, slower_b, olower, olower_b) < 0:
  552. rlower = olower
  553. rlower_b = olower_b
  554. else:
  555. rlower = slower
  556. rlower_b = slower_b
  557. if self._compare_edges(supper, supper_b, oupper, oupper_b) > 0:
  558. rupper = oupper
  559. rupper_b = oupper_b
  560. else:
  561. rupper = supper
  562. rupper_b = supper_b
  563. return Range(
  564. rlower,
  565. rupper,
  566. bounds=cast(_BoundsType, rlower_b + rupper_b),
  567. )
  568. def __mul__(self, other: Range[_T]) -> Range[_T]:
  569. return self.intersection(other)
  570. def __str__(self) -> str:
  571. return self._stringify()
  572. def _stringify(self) -> str:
  573. if self.empty:
  574. return "empty"
  575. l, r = self.lower, self.upper
  576. l = "" if l is None else l # type: ignore
  577. r = "" if r is None else r # type: ignore
  578. b0, b1 = cast("Tuple[str, str]", self.bounds)
  579. return f"{b0}{l},{r}{b1}"
  580. class MultiRange(List[Range[_T]]):
  581. """Represents a multirange sequence.
  582. This list subclass is an utility to allow automatic type inference of
  583. the proper multi-range SQL type depending on the single range values.
  584. This is useful when operating on literal multi-ranges::
  585. import sqlalchemy as sa
  586. from sqlalchemy.dialects.postgresql import MultiRange, Range
  587. value = literal(MultiRange([Range(2, 4)]))
  588. select(tbl).where(tbl.c.value.op("@")(MultiRange([Range(-3, 7)])))
  589. .. versionadded:: 2.0.26
  590. .. seealso::
  591. - :ref:`postgresql_multirange_list_use`.
  592. """
  593. @property
  594. def __sa_type_engine__(self) -> AbstractMultiRange[_T]:
  595. return AbstractMultiRange()
  596. class AbstractRange(sqltypes.TypeEngine[_T]):
  597. """Base class for single and multi Range SQL types."""
  598. render_bind_cast = True
  599. __abstract__ = True
  600. @overload
  601. def adapt(self, cls: Type[_TE], **kw: Any) -> _TE: ...
  602. @overload
  603. def adapt(
  604. self, cls: Type[TypeEngineMixin], **kw: Any
  605. ) -> TypeEngine[Any]: ...
  606. def adapt(
  607. self,
  608. cls: Type[Union[TypeEngine[Any], TypeEngineMixin]],
  609. **kw: Any,
  610. ) -> TypeEngine[Any]:
  611. """Dynamically adapt a range type to an abstract impl.
  612. For example ``INT4RANGE().adapt(_Psycopg2NumericRange)`` should
  613. produce a type that will have ``_Psycopg2NumericRange`` behaviors
  614. and also render as ``INT4RANGE`` in SQL and DDL.
  615. """
  616. if (
  617. issubclass(cls, (AbstractSingleRangeImpl, AbstractMultiRangeImpl))
  618. and cls is not self.__class__
  619. ):
  620. # two ways to do this are: 1. create a new type on the fly
  621. # or 2. have AbstractRangeImpl(visit_name) constructor and a
  622. # visit_abstract_range_impl() method in the PG compiler.
  623. # I'm choosing #1 as the resulting type object
  624. # will then make use of the same mechanics
  625. # as if we had made all these sub-types explicitly, and will
  626. # also look more obvious under pdb etc.
  627. # The adapt() operation here is cached per type-class-per-dialect,
  628. # so is not much of a performance concern
  629. visit_name = self.__visit_name__
  630. return type( # type: ignore
  631. f"{visit_name}RangeImpl",
  632. (cls, self.__class__),
  633. {"__visit_name__": visit_name},
  634. )()
  635. else:
  636. return super().adapt(cls)
  637. class comparator_factory(TypeEngine.Comparator[Range[Any]]):
  638. """Define comparison operations for range types."""
  639. def contains(self, other: Any, **kw: Any) -> ColumnElement[bool]:
  640. """Boolean expression. Returns true if the right hand operand,
  641. which can be an element or a range, is contained within the
  642. column.
  643. kwargs may be ignored by this operator but are required for API
  644. conformance.
  645. """
  646. return self.expr.operate(CONTAINS, other)
  647. def contained_by(self, other: Any) -> ColumnElement[bool]:
  648. """Boolean expression. Returns true if the column is contained
  649. within the right hand operand.
  650. """
  651. return self.expr.operate(CONTAINED_BY, other)
  652. def overlaps(self, other: Any) -> ColumnElement[bool]:
  653. """Boolean expression. Returns true if the column overlaps
  654. (has points in common with) the right hand operand.
  655. """
  656. return self.expr.operate(OVERLAP, other)
  657. def strictly_left_of(self, other: Any) -> ColumnElement[bool]:
  658. """Boolean expression. Returns true if the column is strictly
  659. left of the right hand operand.
  660. """
  661. return self.expr.operate(STRICTLY_LEFT_OF, other)
  662. __lshift__ = strictly_left_of
  663. def strictly_right_of(self, other: Any) -> ColumnElement[bool]:
  664. """Boolean expression. Returns true if the column is strictly
  665. right of the right hand operand.
  666. """
  667. return self.expr.operate(STRICTLY_RIGHT_OF, other)
  668. __rshift__ = strictly_right_of
  669. def not_extend_right_of(self, other: Any) -> ColumnElement[bool]:
  670. """Boolean expression. Returns true if the range in the column
  671. does not extend right of the range in the operand.
  672. """
  673. return self.expr.operate(NOT_EXTEND_RIGHT_OF, other)
  674. def not_extend_left_of(self, other: Any) -> ColumnElement[bool]:
  675. """Boolean expression. Returns true if the range in the column
  676. does not extend left of the range in the operand.
  677. """
  678. return self.expr.operate(NOT_EXTEND_LEFT_OF, other)
  679. def adjacent_to(self, other: Any) -> ColumnElement[bool]:
  680. """Boolean expression. Returns true if the range in the column
  681. is adjacent to the range in the operand.
  682. """
  683. return self.expr.operate(ADJACENT_TO, other)
  684. def union(self, other: Any) -> ColumnElement[bool]:
  685. """Range expression. Returns the union of the two ranges.
  686. Will raise an exception if the resulting range is not
  687. contiguous.
  688. """
  689. return self.expr.operate(operators.add, other)
  690. def difference(self, other: Any) -> ColumnElement[bool]:
  691. """Range expression. Returns the union of the two ranges.
  692. Will raise an exception if the resulting range is not
  693. contiguous.
  694. """
  695. return self.expr.operate(operators.sub, other)
  696. def intersection(self, other: Any) -> ColumnElement[Range[_T]]:
  697. """Range expression. Returns the intersection of the two ranges.
  698. Will raise an exception if the resulting range is not
  699. contiguous.
  700. """
  701. return self.expr.operate(operators.mul, other)
  702. class AbstractSingleRange(AbstractRange[Range[_T]]):
  703. """Base for PostgreSQL RANGE types.
  704. These are types that return a single :class:`_postgresql.Range` object.
  705. .. seealso::
  706. `PostgreSQL range functions <https://www.postgresql.org/docs/current/static/functions-range.html>`_
  707. """ # noqa: E501
  708. __abstract__ = True
  709. def _resolve_for_literal(self, value: Range[Any]) -> Any:
  710. spec = value.lower if value.lower is not None else value.upper
  711. if isinstance(spec, int):
  712. # pg is unreasonably picky here: the query
  713. # "select 1::INTEGER <@ '[1, 4)'::INT8RANGE" raises
  714. # "operator does not exist: integer <@ int8range" as of pg 16
  715. if _is_int32(value):
  716. return INT4RANGE()
  717. else:
  718. return INT8RANGE()
  719. elif isinstance(spec, (Decimal, float)):
  720. return NUMRANGE()
  721. elif isinstance(spec, datetime):
  722. return TSRANGE() if not spec.tzinfo else TSTZRANGE()
  723. elif isinstance(spec, date):
  724. return DATERANGE()
  725. else:
  726. # empty Range, SQL datatype can't be determined here
  727. return sqltypes.NULLTYPE
  728. class AbstractSingleRangeImpl(AbstractSingleRange[_T]):
  729. """Marker for AbstractSingleRange that will apply a subclass-specific
  730. adaptation"""
  731. class AbstractMultiRange(AbstractRange[Sequence[Range[_T]]]):
  732. """Base for PostgreSQL MULTIRANGE types.
  733. these are types that return a sequence of :class:`_postgresql.Range`
  734. objects.
  735. """
  736. __abstract__ = True
  737. def _resolve_for_literal(self, value: Sequence[Range[Any]]) -> Any:
  738. if not value:
  739. # empty MultiRange, SQL datatype can't be determined here
  740. return sqltypes.NULLTYPE
  741. first = value[0]
  742. spec = first.lower if first.lower is not None else first.upper
  743. if isinstance(spec, int):
  744. # pg is unreasonably picky here: the query
  745. # "select 1::INTEGER <@ '{[1, 4),[6,19)}'::INT8MULTIRANGE" raises
  746. # "operator does not exist: integer <@ int8multirange" as of pg 16
  747. if all(_is_int32(r) for r in value):
  748. return INT4MULTIRANGE()
  749. else:
  750. return INT8MULTIRANGE()
  751. elif isinstance(spec, (Decimal, float)):
  752. return NUMMULTIRANGE()
  753. elif isinstance(spec, datetime):
  754. return TSMULTIRANGE() if not spec.tzinfo else TSTZMULTIRANGE()
  755. elif isinstance(spec, date):
  756. return DATEMULTIRANGE()
  757. else:
  758. # empty Range, SQL datatype can't be determined here
  759. return sqltypes.NULLTYPE
  760. class AbstractMultiRangeImpl(AbstractMultiRange[_T]):
  761. """Marker for AbstractMultiRange that will apply a subclass-specific
  762. adaptation"""
  763. class INT4RANGE(AbstractSingleRange[int]):
  764. """Represent the PostgreSQL INT4RANGE type."""
  765. __visit_name__ = "INT4RANGE"
  766. class INT8RANGE(AbstractSingleRange[int]):
  767. """Represent the PostgreSQL INT8RANGE type."""
  768. __visit_name__ = "INT8RANGE"
  769. class NUMRANGE(AbstractSingleRange[Decimal]):
  770. """Represent the PostgreSQL NUMRANGE type."""
  771. __visit_name__ = "NUMRANGE"
  772. class DATERANGE(AbstractSingleRange[date]):
  773. """Represent the PostgreSQL DATERANGE type."""
  774. __visit_name__ = "DATERANGE"
  775. class TSRANGE(AbstractSingleRange[datetime]):
  776. """Represent the PostgreSQL TSRANGE type."""
  777. __visit_name__ = "TSRANGE"
  778. class TSTZRANGE(AbstractSingleRange[datetime]):
  779. """Represent the PostgreSQL TSTZRANGE type."""
  780. __visit_name__ = "TSTZRANGE"
  781. class INT4MULTIRANGE(AbstractMultiRange[int]):
  782. """Represent the PostgreSQL INT4MULTIRANGE type."""
  783. __visit_name__ = "INT4MULTIRANGE"
  784. class INT8MULTIRANGE(AbstractMultiRange[int]):
  785. """Represent the PostgreSQL INT8MULTIRANGE type."""
  786. __visit_name__ = "INT8MULTIRANGE"
  787. class NUMMULTIRANGE(AbstractMultiRange[Decimal]):
  788. """Represent the PostgreSQL NUMMULTIRANGE type."""
  789. __visit_name__ = "NUMMULTIRANGE"
  790. class DATEMULTIRANGE(AbstractMultiRange[date]):
  791. """Represent the PostgreSQL DATEMULTIRANGE type."""
  792. __visit_name__ = "DATEMULTIRANGE"
  793. class TSMULTIRANGE(AbstractMultiRange[datetime]):
  794. """Represent the PostgreSQL TSRANGE type."""
  795. __visit_name__ = "TSMULTIRANGE"
  796. class TSTZMULTIRANGE(AbstractMultiRange[datetime]):
  797. """Represent the PostgreSQL TSTZRANGE type."""
  798. __visit_name__ = "TSTZMULTIRANGE"
  799. _max_int_32 = 2**31 - 1
  800. _min_int_32 = -(2**31)
  801. def _is_int32(r: Range[int]) -> bool:
  802. return (r.lower is None or _min_int_32 <= r.lower <= _max_int_32) and (
  803. r.upper is None or _min_int_32 <= r.upper <= _max_int_32
  804. )