_functions.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. """
  2. Implementations of SQL functions for SQLite.
  3. """
  4. import functools
  5. import operator
  6. import random
  7. import statistics
  8. import zoneinfo
  9. from datetime import timedelta
  10. from hashlib import md5, sha1, sha224, sha256, sha384, sha512
  11. from math import (
  12. acos,
  13. asin,
  14. atan,
  15. atan2,
  16. ceil,
  17. cos,
  18. degrees,
  19. exp,
  20. floor,
  21. fmod,
  22. log,
  23. pi,
  24. radians,
  25. sin,
  26. sqrt,
  27. tan,
  28. )
  29. from re import search as re_search
  30. from uuid import uuid4
  31. from django.db.backends.utils import (
  32. split_tzname_delta,
  33. typecast_time,
  34. typecast_timestamp,
  35. )
  36. from django.utils import timezone
  37. from django.utils.duration import duration_microseconds
  38. from django.utils.version import PY314
  39. if PY314:
  40. from uuid import uuid7
  41. def register(connection):
  42. create_deterministic_function = functools.partial(
  43. connection.create_function,
  44. deterministic=True,
  45. )
  46. create_deterministic_function("django_date_extract", 2, _sqlite_datetime_extract)
  47. create_deterministic_function("django_date_trunc", 4, _sqlite_date_trunc)
  48. create_deterministic_function(
  49. "django_datetime_cast_date", 3, _sqlite_datetime_cast_date
  50. )
  51. create_deterministic_function(
  52. "django_datetime_cast_time", 3, _sqlite_datetime_cast_time
  53. )
  54. create_deterministic_function(
  55. "django_datetime_extract", 4, _sqlite_datetime_extract
  56. )
  57. create_deterministic_function("django_datetime_trunc", 4, _sqlite_datetime_trunc)
  58. create_deterministic_function("django_time_extract", 2, _sqlite_time_extract)
  59. create_deterministic_function("django_time_trunc", 4, _sqlite_time_trunc)
  60. create_deterministic_function("django_time_diff", 2, _sqlite_time_diff)
  61. create_deterministic_function("django_timestamp_diff", 2, _sqlite_timestamp_diff)
  62. create_deterministic_function("django_format_dtdelta", 3, _sqlite_format_dtdelta)
  63. create_deterministic_function("regexp", 2, _sqlite_regexp)
  64. create_deterministic_function("BITXOR", 2, _sqlite_bitxor)
  65. create_deterministic_function("COT", 1, _sqlite_cot)
  66. create_deterministic_function("LPAD", 3, _sqlite_lpad)
  67. create_deterministic_function("MD5", 1, _sqlite_md5)
  68. create_deterministic_function("REPEAT", 2, _sqlite_repeat)
  69. create_deterministic_function("REVERSE", 1, _sqlite_reverse)
  70. create_deterministic_function("RPAD", 3, _sqlite_rpad)
  71. create_deterministic_function("SHA1", 1, _sqlite_sha1)
  72. create_deterministic_function("SHA224", 1, _sqlite_sha224)
  73. create_deterministic_function("SHA256", 1, _sqlite_sha256)
  74. create_deterministic_function("SHA384", 1, _sqlite_sha384)
  75. create_deterministic_function("SHA512", 1, _sqlite_sha512)
  76. create_deterministic_function("SIGN", 1, _sqlite_sign)
  77. # Don't use the built-in RANDOM() function because it returns a value
  78. # in the range [-1 * 2^63, 2^63 - 1] instead of [0, 1).
  79. connection.create_function("RAND", 0, random.random)
  80. connection.create_aggregate("STDDEV_POP", 1, StdDevPop)
  81. connection.create_aggregate("STDDEV_SAMP", 1, StdDevSamp)
  82. connection.create_aggregate("VAR_POP", 1, VarPop)
  83. connection.create_aggregate("VAR_SAMP", 1, VarSamp)
  84. connection.create_aggregate("ANY_VALUE", 1, AnyValue)
  85. connection.create_aggregate("BIT_AND", 1, BitAnd)
  86. connection.create_aggregate("BIT_OR", 1, BitOr)
  87. connection.create_aggregate("BIT_XOR", 1, BitXor)
  88. connection.create_function("UUIDV4", 0, _sqlite_uuid4)
  89. if PY314:
  90. connection.create_function("UUIDV7", 0, _sqlite_uuid7)
  91. # Some math functions are enabled by default in SQLite 3.35+.
  92. sql = "select sqlite_compileoption_used('ENABLE_MATH_FUNCTIONS')"
  93. if not connection.execute(sql).fetchone()[0]:
  94. create_deterministic_function("ACOS", 1, _sqlite_acos)
  95. create_deterministic_function("ASIN", 1, _sqlite_asin)
  96. create_deterministic_function("ATAN", 1, _sqlite_atan)
  97. create_deterministic_function("ATAN2", 2, _sqlite_atan2)
  98. create_deterministic_function("CEILING", 1, _sqlite_ceiling)
  99. create_deterministic_function("COS", 1, _sqlite_cos)
  100. create_deterministic_function("DEGREES", 1, _sqlite_degrees)
  101. create_deterministic_function("EXP", 1, _sqlite_exp)
  102. create_deterministic_function("FLOOR", 1, _sqlite_floor)
  103. create_deterministic_function("LN", 1, _sqlite_ln)
  104. create_deterministic_function("LOG", 2, _sqlite_log)
  105. create_deterministic_function("MOD", 2, _sqlite_mod)
  106. create_deterministic_function("PI", 0, _sqlite_pi)
  107. create_deterministic_function("POWER", 2, _sqlite_power)
  108. create_deterministic_function("RADIANS", 1, _sqlite_radians)
  109. create_deterministic_function("SIN", 1, _sqlite_sin)
  110. create_deterministic_function("SQRT", 1, _sqlite_sqrt)
  111. create_deterministic_function("TAN", 1, _sqlite_tan)
  112. def _sqlite_datetime_parse(dt, tzname=None, conn_tzname=None):
  113. if dt is None:
  114. return None
  115. try:
  116. dt = typecast_timestamp(dt)
  117. except (TypeError, ValueError):
  118. return None
  119. if conn_tzname:
  120. dt = dt.replace(tzinfo=zoneinfo.ZoneInfo(conn_tzname))
  121. if tzname is not None and tzname != conn_tzname:
  122. tzname, sign, offset = split_tzname_delta(tzname)
  123. if offset:
  124. hours, minutes = offset.split(":")
  125. offset_delta = timedelta(hours=int(hours), minutes=int(minutes))
  126. dt += offset_delta if sign == "+" else -offset_delta
  127. # The tzname may originally be just the offset e.g. "+3:00",
  128. # which becomes an empty string after splitting the sign and offset.
  129. # In this case, use the conn_tzname as fallback.
  130. dt = timezone.localtime(dt, zoneinfo.ZoneInfo(tzname or conn_tzname))
  131. return dt
  132. def _sqlite_date_trunc(lookup_type, dt, tzname, conn_tzname):
  133. dt = _sqlite_datetime_parse(dt, tzname, conn_tzname)
  134. if dt is None:
  135. return None
  136. if lookup_type == "year":
  137. return f"{dt.year:04d}-01-01"
  138. elif lookup_type == "quarter":
  139. month_in_quarter = dt.month - (dt.month - 1) % 3
  140. return f"{dt.year:04d}-{month_in_quarter:02d}-01"
  141. elif lookup_type == "month":
  142. return f"{dt.year:04d}-{dt.month:02d}-01"
  143. elif lookup_type == "week":
  144. dt -= timedelta(days=dt.weekday())
  145. return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d}"
  146. elif lookup_type == "day":
  147. return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d}"
  148. raise ValueError(f"Unsupported lookup type: {lookup_type!r}")
  149. def _sqlite_time_trunc(lookup_type, dt, tzname, conn_tzname):
  150. if dt is None:
  151. return None
  152. dt_parsed = _sqlite_datetime_parse(dt, tzname, conn_tzname)
  153. if dt_parsed is None:
  154. try:
  155. dt = typecast_time(dt)
  156. except (ValueError, TypeError):
  157. return None
  158. else:
  159. dt = dt_parsed
  160. if lookup_type == "hour":
  161. return f"{dt.hour:02d}:00:00"
  162. elif lookup_type == "minute":
  163. return f"{dt.hour:02d}:{dt.minute:02d}:00"
  164. elif lookup_type == "second":
  165. return f"{dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}"
  166. raise ValueError(f"Unsupported lookup type: {lookup_type!r}")
  167. def _sqlite_datetime_cast_date(dt, tzname, conn_tzname):
  168. dt = _sqlite_datetime_parse(dt, tzname, conn_tzname)
  169. if dt is None:
  170. return None
  171. return dt.date().isoformat()
  172. def _sqlite_datetime_cast_time(dt, tzname, conn_tzname):
  173. dt = _sqlite_datetime_parse(dt, tzname, conn_tzname)
  174. if dt is None:
  175. return None
  176. return dt.time().isoformat()
  177. def _sqlite_datetime_extract(lookup_type, dt, tzname=None, conn_tzname=None):
  178. dt = _sqlite_datetime_parse(dt, tzname, conn_tzname)
  179. if dt is None:
  180. return None
  181. if lookup_type == "week_day":
  182. return (dt.isoweekday() % 7) + 1
  183. elif lookup_type == "iso_week_day":
  184. return dt.isoweekday()
  185. elif lookup_type == "week":
  186. return dt.isocalendar().week
  187. elif lookup_type == "quarter":
  188. return ceil(dt.month / 3)
  189. elif lookup_type == "iso_year":
  190. return dt.isocalendar().year
  191. else:
  192. return getattr(dt, lookup_type)
  193. def _sqlite_datetime_trunc(lookup_type, dt, tzname, conn_tzname):
  194. dt = _sqlite_datetime_parse(dt, tzname, conn_tzname)
  195. if dt is None:
  196. return None
  197. if lookup_type == "year":
  198. return f"{dt.year:04d}-01-01 00:00:00"
  199. elif lookup_type == "quarter":
  200. month_in_quarter = dt.month - (dt.month - 1) % 3
  201. return f"{dt.year:04d}-{month_in_quarter:02d}-01 00:00:00"
  202. elif lookup_type == "month":
  203. return f"{dt.year:04d}-{dt.month:02d}-01 00:00:00"
  204. elif lookup_type == "week":
  205. dt -= timedelta(days=dt.weekday())
  206. return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} 00:00:00"
  207. elif lookup_type == "day":
  208. return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} 00:00:00"
  209. elif lookup_type == "hour":
  210. return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} {dt.hour:02d}:00:00"
  211. elif lookup_type == "minute":
  212. return (
  213. f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} "
  214. f"{dt.hour:02d}:{dt.minute:02d}:00"
  215. )
  216. elif lookup_type == "second":
  217. return (
  218. f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} "
  219. f"{dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}"
  220. )
  221. raise ValueError(f"Unsupported lookup type: {lookup_type!r}")
  222. def _sqlite_time_extract(lookup_type, dt):
  223. if dt is None:
  224. return None
  225. try:
  226. dt = typecast_time(dt)
  227. except (ValueError, TypeError):
  228. return None
  229. return getattr(dt, lookup_type)
  230. def _sqlite_prepare_dtdelta_param(conn, param):
  231. if conn in ["+", "-"]:
  232. if isinstance(param, int):
  233. return timedelta(0, 0, param)
  234. else:
  235. return typecast_timestamp(param)
  236. return param
  237. def _sqlite_format_dtdelta(connector, lhs, rhs):
  238. """
  239. LHS and RHS can be either:
  240. - An integer number of microseconds
  241. - A string representing a datetime
  242. - A scalar value, e.g. float
  243. """
  244. if connector is None or lhs is None or rhs is None:
  245. return None
  246. connector = connector.strip()
  247. try:
  248. real_lhs = _sqlite_prepare_dtdelta_param(connector, lhs)
  249. real_rhs = _sqlite_prepare_dtdelta_param(connector, rhs)
  250. except (ValueError, TypeError):
  251. return None
  252. if connector == "+":
  253. # typecast_timestamp() returns a date or a datetime without timezone.
  254. # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
  255. out = str(real_lhs + real_rhs)
  256. elif connector == "-":
  257. out = str(real_lhs - real_rhs)
  258. elif connector == "*":
  259. out = real_lhs * real_rhs
  260. else:
  261. out = real_lhs / real_rhs
  262. return out
  263. def _sqlite_time_diff(lhs, rhs):
  264. if lhs is None or rhs is None:
  265. return None
  266. left = typecast_time(lhs)
  267. right = typecast_time(rhs)
  268. return (
  269. (left.hour * 60 * 60 * 1000000)
  270. + (left.minute * 60 * 1000000)
  271. + (left.second * 1000000)
  272. + (left.microsecond)
  273. - (right.hour * 60 * 60 * 1000000)
  274. - (right.minute * 60 * 1000000)
  275. - (right.second * 1000000)
  276. - (right.microsecond)
  277. )
  278. def _sqlite_timestamp_diff(lhs, rhs):
  279. if lhs is None or rhs is None:
  280. return None
  281. left = typecast_timestamp(lhs)
  282. right = typecast_timestamp(rhs)
  283. return duration_microseconds(left - right)
  284. def _sqlite_regexp(pattern, string):
  285. if pattern is None or string is None:
  286. return None
  287. if not isinstance(string, str):
  288. string = str(string)
  289. return bool(re_search(pattern, string))
  290. def _sqlite_acos(x):
  291. if x is None:
  292. return None
  293. return acos(x)
  294. def _sqlite_asin(x):
  295. if x is None:
  296. return None
  297. return asin(x)
  298. def _sqlite_atan(x):
  299. if x is None:
  300. return None
  301. return atan(x)
  302. def _sqlite_atan2(y, x):
  303. if y is None or x is None:
  304. return None
  305. return atan2(y, x)
  306. def _sqlite_bitxor(x, y):
  307. if x is None or y is None:
  308. return None
  309. return x ^ y
  310. def _sqlite_ceiling(x):
  311. if x is None:
  312. return None
  313. return ceil(x)
  314. def _sqlite_cos(x):
  315. if x is None:
  316. return None
  317. return cos(x)
  318. def _sqlite_cot(x):
  319. if x is None:
  320. return None
  321. return 1 / tan(x)
  322. def _sqlite_degrees(x):
  323. if x is None:
  324. return None
  325. return degrees(x)
  326. def _sqlite_exp(x):
  327. if x is None:
  328. return None
  329. return exp(x)
  330. def _sqlite_floor(x):
  331. if x is None:
  332. return None
  333. return floor(x)
  334. def _sqlite_ln(x):
  335. if x is None:
  336. return None
  337. return log(x)
  338. def _sqlite_log(base, x):
  339. if base is None or x is None:
  340. return None
  341. # Arguments reversed to match SQL standard.
  342. return log(x, base)
  343. def _sqlite_lpad(text, length, fill_text):
  344. if text is None or length is None or fill_text is None:
  345. return None
  346. delta = length - len(text)
  347. if delta <= 0:
  348. return text[:length]
  349. return (fill_text * length)[:delta] + text
  350. def _sqlite_md5(text):
  351. if text is None:
  352. return None
  353. return md5(text.encode()).hexdigest()
  354. def _sqlite_mod(x, y):
  355. if x is None or y is None:
  356. return None
  357. return fmod(x, y)
  358. def _sqlite_pi():
  359. return pi
  360. def _sqlite_power(x, y):
  361. if x is None or y is None:
  362. return None
  363. return x**y
  364. def _sqlite_radians(x):
  365. if x is None:
  366. return None
  367. return radians(x)
  368. def _sqlite_repeat(text, count):
  369. if text is None or count is None:
  370. return None
  371. return text * count
  372. def _sqlite_reverse(text):
  373. if text is None:
  374. return None
  375. return text[::-1]
  376. def _sqlite_rpad(text, length, fill_text):
  377. if text is None or length is None or fill_text is None:
  378. return None
  379. return (text + fill_text * length)[:length]
  380. def _sqlite_sha1(text):
  381. if text is None:
  382. return None
  383. return sha1(text.encode()).hexdigest()
  384. def _sqlite_sha224(text):
  385. if text is None:
  386. return None
  387. return sha224(text.encode()).hexdigest()
  388. def _sqlite_sha256(text):
  389. if text is None:
  390. return None
  391. return sha256(text.encode()).hexdigest()
  392. def _sqlite_sha384(text):
  393. if text is None:
  394. return None
  395. return sha384(text.encode()).hexdigest()
  396. def _sqlite_sha512(text):
  397. if text is None:
  398. return None
  399. return sha512(text.encode()).hexdigest()
  400. def _sqlite_sign(x):
  401. if x is None:
  402. return None
  403. return (x > 0) - (x < 0)
  404. def _sqlite_sin(x):
  405. if x is None:
  406. return None
  407. return sin(x)
  408. def _sqlite_sqrt(x):
  409. if x is None:
  410. return None
  411. return sqrt(x)
  412. def _sqlite_tan(x):
  413. if x is None:
  414. return None
  415. return tan(x)
  416. def _sqlite_uuid4():
  417. return uuid4().hex
  418. def _sqlite_uuid7():
  419. return uuid7().hex
  420. class ListAggregate(list):
  421. step = list.append
  422. class StdDevPop(ListAggregate):
  423. finalize = statistics.pstdev
  424. class StdDevSamp(ListAggregate):
  425. finalize = statistics.stdev
  426. class VarPop(ListAggregate):
  427. finalize = statistics.pvariance
  428. class VarSamp(ListAggregate):
  429. finalize = statistics.variance
  430. class AnyValue(ListAggregate):
  431. def finalize(self):
  432. return self[0]
  433. class BitAggregate(ListAggregate):
  434. bit_operator = None
  435. def finalize(self):
  436. items = (item for item in self if item is not None)
  437. try:
  438. return functools.reduce(self.bit_operator, items)
  439. except TypeError:
  440. # items may be an empty iterator when all elements are None.
  441. return None
  442. class BitAnd(BitAggregate):
  443. bit_operator = operator.and_
  444. class BitOr(BitAggregate):
  445. bit_operator = operator.or_
  446. class BitXor(BitAggregate):
  447. bit_operator = operator.xor