text.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. from django.db import NotSupportedError
  2. from django.db.models.expressions import Func, Value
  3. from django.db.models.fields import CharField, IntegerField, TextField
  4. from django.db.models.functions import Cast, Coalesce
  5. from django.db.models.lookups import Transform
  6. class MySQLSHA2Mixin:
  7. def as_mysql(self, compiler, connection, **extra_context):
  8. return super().as_sql(
  9. compiler,
  10. connection,
  11. template="SHA2(%%(expressions)s, %s)" % self.function[3:],
  12. **extra_context,
  13. )
  14. class OracleHashMixin:
  15. def as_oracle(self, compiler, connection, **extra_context):
  16. return super().as_sql(
  17. compiler,
  18. connection,
  19. template=(
  20. "LOWER(RAWTOHEX(STANDARD_HASH(UTL_I18N.STRING_TO_RAW("
  21. "%(expressions)s, 'AL32UTF8'), '%(function)s')))"
  22. ),
  23. **extra_context,
  24. )
  25. class PostgreSQLSHAMixin:
  26. def as_postgresql(self, compiler, connection, **extra_context):
  27. return super().as_sql(
  28. compiler,
  29. connection,
  30. template="ENCODE(DIGEST(%(expressions)s, '%(function)s'), 'hex')",
  31. function=self.function.lower(),
  32. **extra_context,
  33. )
  34. class Chr(Transform):
  35. function = "CHR"
  36. lookup_name = "chr"
  37. def as_mysql(self, compiler, connection, **extra_context):
  38. return super().as_sql(
  39. compiler,
  40. connection,
  41. function="CHAR",
  42. template="%(function)s(%(expressions)s USING utf16)",
  43. **extra_context,
  44. )
  45. def as_oracle(self, compiler, connection, **extra_context):
  46. return super().as_sql(
  47. compiler,
  48. connection,
  49. template="%(function)s(%(expressions)s USING NCHAR_CS)",
  50. **extra_context,
  51. )
  52. def as_sqlite(self, compiler, connection, **extra_context):
  53. return super().as_sql(compiler, connection, function="CHAR", **extra_context)
  54. class ConcatPair(Func):
  55. """
  56. Concatenate two arguments together. This is used by `Concat` because not
  57. all backend databases support more than two arguments.
  58. """
  59. function = "CONCAT"
  60. def as_sqlite(self, compiler, connection, **extra_context):
  61. coalesced = self.coalesce()
  62. return super(ConcatPair, coalesced).as_sql(
  63. compiler,
  64. connection,
  65. template="%(expressions)s",
  66. arg_joiner=" || ",
  67. **extra_context,
  68. )
  69. def as_postgresql(self, compiler, connection, **extra_context):
  70. copy = self.copy()
  71. copy.set_source_expressions(
  72. [
  73. Cast(expression, TextField())
  74. for expression in copy.get_source_expressions()
  75. ]
  76. )
  77. return super(ConcatPair, copy).as_sql(
  78. compiler,
  79. connection,
  80. **extra_context,
  81. )
  82. def as_mysql(self, compiler, connection, **extra_context):
  83. # Use CONCAT_WS with an empty separator so that NULLs are ignored.
  84. return super().as_sql(
  85. compiler,
  86. connection,
  87. function="CONCAT_WS",
  88. template="%(function)s('', %(expressions)s)",
  89. **extra_context,
  90. )
  91. def coalesce(self):
  92. # null on either side results in null for expression, wrap with coalesce
  93. c = self.copy()
  94. c.set_source_expressions(
  95. [
  96. Coalesce(expression, Value(""))
  97. for expression in c.get_source_expressions()
  98. ]
  99. )
  100. return c
  101. class Concat(Func):
  102. """
  103. Concatenate text fields together. Backends that result in an entire
  104. null expression when any arguments are null will wrap each argument in
  105. coalesce functions to ensure a non-null result.
  106. """
  107. function = None
  108. template = "%(expressions)s"
  109. def __init__(self, *expressions, **extra):
  110. if len(expressions) < 2:
  111. raise ValueError("Concat must take at least two expressions")
  112. paired = self._paired(expressions)
  113. super().__init__(paired, **extra)
  114. def _paired(self, expressions):
  115. # wrap pairs of expressions in successive concat functions
  116. # exp = [a, b, c, d]
  117. # -> ConcatPair(a, ConcatPair(b, ConcatPair(c, d))))
  118. if len(expressions) == 2:
  119. return ConcatPair(*expressions)
  120. return ConcatPair(expressions[0], self._paired(expressions[1:]))
  121. class Left(Func):
  122. function = "LEFT"
  123. arity = 2
  124. output_field = CharField()
  125. def __init__(self, expression, length, **extra):
  126. """
  127. expression: the name of a field, or an expression returning a string
  128. length: the number of characters to return from the start of the string
  129. """
  130. if not hasattr(length, "resolve_expression"):
  131. if length < 1:
  132. raise ValueError("'length' must be greater than 0.")
  133. super().__init__(expression, length, **extra)
  134. def get_substr(self):
  135. return Substr(self.source_expressions[0], Value(1), self.source_expressions[1])
  136. def as_oracle(self, compiler, connection, **extra_context):
  137. return self.get_substr().as_oracle(compiler, connection, **extra_context)
  138. def as_sqlite(self, compiler, connection, **extra_context):
  139. return self.get_substr().as_sqlite(compiler, connection, **extra_context)
  140. class Length(Transform):
  141. """Return the number of characters in the expression."""
  142. function = "LENGTH"
  143. lookup_name = "length"
  144. output_field = IntegerField()
  145. def as_mysql(self, compiler, connection, **extra_context):
  146. return super().as_sql(
  147. compiler, connection, function="CHAR_LENGTH", **extra_context
  148. )
  149. class Lower(Transform):
  150. function = "LOWER"
  151. lookup_name = "lower"
  152. class LPad(Func):
  153. function = "LPAD"
  154. output_field = CharField()
  155. def __init__(self, expression, length, fill_text=Value(" "), **extra):
  156. if (
  157. not hasattr(length, "resolve_expression")
  158. and length is not None
  159. and length < 0
  160. ):
  161. raise ValueError("'length' must be greater or equal to 0.")
  162. super().__init__(expression, length, fill_text, **extra)
  163. class LTrim(Transform):
  164. function = "LTRIM"
  165. lookup_name = "ltrim"
  166. class MD5(OracleHashMixin, Transform):
  167. function = "MD5"
  168. lookup_name = "md5"
  169. class Ord(Transform):
  170. function = "ASCII"
  171. lookup_name = "ord"
  172. output_field = IntegerField()
  173. def as_mysql(self, compiler, connection, **extra_context):
  174. return super().as_sql(compiler, connection, function="ORD", **extra_context)
  175. def as_sqlite(self, compiler, connection, **extra_context):
  176. return super().as_sql(compiler, connection, function="UNICODE", **extra_context)
  177. class Repeat(Func):
  178. function = "REPEAT"
  179. output_field = CharField()
  180. def __init__(self, expression, number, **extra):
  181. if (
  182. not hasattr(number, "resolve_expression")
  183. and number is not None
  184. and number < 0
  185. ):
  186. raise ValueError("'number' must be greater or equal to 0.")
  187. super().__init__(expression, number, **extra)
  188. def as_oracle(self, compiler, connection, **extra_context):
  189. expression, number = self.source_expressions
  190. length = None if number is None else Length(expression) * number
  191. rpad = RPad(expression, length, expression)
  192. return rpad.as_sql(compiler, connection, **extra_context)
  193. class Replace(Func):
  194. function = "REPLACE"
  195. def __init__(self, expression, text, replacement=Value(""), **extra):
  196. super().__init__(expression, text, replacement, **extra)
  197. class Reverse(Transform):
  198. function = "REVERSE"
  199. lookup_name = "reverse"
  200. def as_oracle(self, compiler, connection, **extra_context):
  201. # REVERSE in Oracle is undocumented and doesn't support multi-byte
  202. # strings. Use a special subquery instead.
  203. return super().as_sql(
  204. compiler,
  205. connection,
  206. template=(
  207. "(SELECT LISTAGG(s) WITHIN GROUP (ORDER BY n DESC) FROM "
  208. "(SELECT LEVEL n, SUBSTR(%(expressions)s, LEVEL, 1) s "
  209. "FROM DUAL CONNECT BY LEVEL <= LENGTH(%(expressions)s)) "
  210. "GROUP BY %(expressions)s)"
  211. ),
  212. **extra_context,
  213. )
  214. class Right(Left):
  215. function = "RIGHT"
  216. def get_substr(self):
  217. return Substr(
  218. self.source_expressions[0], self.source_expressions[1] * Value(-1)
  219. )
  220. class RPad(LPad):
  221. function = "RPAD"
  222. class RTrim(Transform):
  223. function = "RTRIM"
  224. lookup_name = "rtrim"
  225. class SHA1(OracleHashMixin, PostgreSQLSHAMixin, Transform):
  226. function = "SHA1"
  227. lookup_name = "sha1"
  228. class SHA224(MySQLSHA2Mixin, PostgreSQLSHAMixin, Transform):
  229. function = "SHA224"
  230. lookup_name = "sha224"
  231. def as_oracle(self, compiler, connection, **extra_context):
  232. raise NotSupportedError("SHA224 is not supported on Oracle.")
  233. class SHA256(MySQLSHA2Mixin, OracleHashMixin, PostgreSQLSHAMixin, Transform):
  234. function = "SHA256"
  235. lookup_name = "sha256"
  236. class SHA384(MySQLSHA2Mixin, OracleHashMixin, PostgreSQLSHAMixin, Transform):
  237. function = "SHA384"
  238. lookup_name = "sha384"
  239. class SHA512(MySQLSHA2Mixin, OracleHashMixin, PostgreSQLSHAMixin, Transform):
  240. function = "SHA512"
  241. lookup_name = "sha512"
  242. class StrIndex(Func):
  243. """
  244. Return a positive integer corresponding to the 1-indexed position of the
  245. first occurrence of a substring inside another string, or 0 if the
  246. substring is not found.
  247. """
  248. function = "INSTR"
  249. arity = 2
  250. output_field = IntegerField()
  251. def as_postgresql(self, compiler, connection, **extra_context):
  252. return super().as_sql(compiler, connection, function="STRPOS", **extra_context)
  253. class Substr(Func):
  254. function = "SUBSTRING"
  255. output_field = CharField()
  256. def __init__(self, expression, pos, length=None, **extra):
  257. """
  258. expression: the name of a field, or an expression returning a string
  259. pos: an integer > 0, or an expression returning an integer
  260. length: an optional number of characters to return
  261. """
  262. if not hasattr(pos, "resolve_expression"):
  263. if pos < 1:
  264. raise ValueError("'pos' must be greater than 0")
  265. expressions = [expression, pos]
  266. if length is not None:
  267. expressions.append(length)
  268. super().__init__(*expressions, **extra)
  269. def as_sqlite(self, compiler, connection, **extra_context):
  270. return super().as_sql(compiler, connection, function="SUBSTR", **extra_context)
  271. def as_oracle(self, compiler, connection, **extra_context):
  272. return super().as_sql(compiler, connection, function="SUBSTR", **extra_context)
  273. class Trim(Transform):
  274. function = "TRIM"
  275. lookup_name = "trim"
  276. class Upper(Transform):
  277. function = "UPPER"
  278. lookup_name = "upper"