text.py 11 KB

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