_functions.py 14 KB

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