diff --git a/packages/django-google-spanner/django_spanner/base.py b/packages/django-google-spanner/django_spanner/base.py index 72b7670b9ce0..f8c4d2e1e3b6 100644 --- a/packages/django-google-spanner/django_spanner/base.py +++ b/packages/django-google-spanner/django_spanner/base.py @@ -62,48 +62,17 @@ class DatabaseWrapper(BaseDatabaseWrapper): } operators = { "exact": "= %s", - "iexact": "REGEXP_CONTAINS(%s, %%%%s)", - # contains uses REGEXP_CONTAINS instead of LIKE to allow - # DatabaseOperations.prep_for_like_query() to do regular expression - # escaping. prep_for_like_query() is called for all the lookups that - # use REGEXP_CONTAINS except regex/iregex (see - # django.db.models.lookups.PatternLookup). - "contains": "REGEXP_CONTAINS(%s, %%%%s)", - "icontains": "REGEXP_CONTAINS(%s, %%%%s)", + "iexact": "= UPPER(CAST(%s AS STRING))", + # Pattern lookups (contains, startswith, endswith, and case-insensitive + # variants) use function-based expressions in django_spanner.lookups. "gt": "> %s", "gte": ">= %s", "lt": "< %s", "lte": "<= %s", - # Using REGEXP_CONTAINS instead of STARTS_WITH and ENDS_WITH for the - # same reasoning as described above for 'contains'. - "startswith": "REGEXP_CONTAINS(%s, %%%%s)", - "endswith": "REGEXP_CONTAINS(%s, %%%%s)", - "istartswith": "REGEXP_CONTAINS(%s, %%%%s)", - "iendswith": "REGEXP_CONTAINS(%s, %%%%s)", "regex": "REGEXP_CONTAINS(%s, %%%%s)", "iregex": "REGEXP_CONTAINS(%s, %%%%s)", } - # pattern_esc is used to generate SQL pattern lookup clauses when the - # right-hand side of the lookup isn't a raw string (it might be an - # expression or the result of a bilateral transformation). In those cases, - # special characters for REGEXP_CONTAINS operators (e.g. \, *, _) must be - # escaped on database side. - pattern_esc = ( - r'REPLACE(REPLACE(REPLACE({}, "\\", "\\\\"), "%%", r"\%%"), "_", r"\_")' - ) - - # These are all no-ops in favor of using REGEXP_CONTAINS in the customized - # lookups. - pattern_ops = { - "contains": "", - "icontains": "", - "startswith": "", - "istartswith": "", - "endswith": "", - "iendswith": "", - } - data_type_check_constraints = { "PositiveBigIntegerField": "%(qn_column)s >= 0", "PositiveIntegerField": "%(qn_column)s >= 0", diff --git a/packages/django-google-spanner/django_spanner/features.py b/packages/django-google-spanner/django_spanner/features.py index 07118a344735..9d90e09401d7 100644 --- a/packages/django-google-spanner/django_spanner/features.py +++ b/packages/django-google-spanner/django_spanner/features.py @@ -35,7 +35,6 @@ def introspected_field_types(self): # TIMESTAMP. can_introspect_time_field = False closed_cursor_error_class = InterfaceError - # Spanner uses REGEXP_CONTAINS which is case-sensitive. has_case_insensitive_like = False # https://cloud.google.com/spanner/quotas#query_limits max_query_params = 900 diff --git a/packages/django-google-spanner/django_spanner/lookups.py b/packages/django-google-spanner/django_spanner/lookups.py index 3c44a6869a1e..cb695b5241b6 100644 --- a/packages/django-google-spanner/django_spanner/lookups.py +++ b/packages/django-google-spanner/django_spanner/lookups.py @@ -4,10 +4,13 @@ # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd +from typing import TYPE_CHECKING, Any, Tuple + from django.db.models.fields.json import ( HasKeyLookup, KeyTextTransform, KeyTransform, + KeyTransformIExact, ) from django.db.models.lookups import ( Contains, @@ -22,107 +25,104 @@ IStartsWith, LessThan, LessThanOrEqual, + Lookup, Regex, StartsWith, ) +if TYPE_CHECKING: + from django.db.backends.base.base import BaseDatabaseWrapper + from django.db.models.sql.compiler import SQLCompiler + + +def _pattern_lookup_sql( + lookup: "Lookup", + compiler: "SQLCompiler", + connection: "BaseDatabaseWrapper", + *, + strip_left: int, + strip_right: int, +) -> Tuple[str, str, Tuple[Any, ...]]: + """Compile a string pattern lookup using literal Spanner string functions. + + Django's PatternLookup.process_rhs wraps direct scalar values with leading + or trailing '%' wildcards. Strip those added wildcards when present and + cast the RHS expression to STRING (wrapped in UPPER for case-insensitive + lookups) so equality, STRPOS, STARTS_WITH, and ENDS_WITH treat all + characters literally. + """ + lhs_sql, lhs_params = lookup.process_lhs(compiler, connection) + # For plain and JSON iexact lookups, call Lookup.process_rhs directly: + # Spanner needs neither prep_for_iexact_query nor KeyTransformIExact's + # MySQL-only logic, and IExact.process_rhs crashes when a subquery returns + # tuple params and tries to assign params[0] in place. + if isinstance(lookup, IExact) and type(lookup).process_rhs in ( + IExact.process_rhs, + KeyTransformIExact.process_rhs, + ): + rhs_sql, rhs_params = Lookup.process_rhs(lookup, compiler, connection) + else: + rhs_sql, rhs_params = lookup.process_rhs(compiler, connection) + params = list(lhs_params) + params.extend(rhs_params) + # For direct Python values (e.g. float or Decimal), send str(val) so + # CAST(%s AS STRING) preserves formatting and works across parameter types, + # after stripping any '%' wildcards Django added. SQL expressions handle + # their own casts. + if lookup.rhs_is_direct_value() and rhs_params and not lookup.bilateral_transforms: + rhs_index = len(lhs_params) + value = str(params[rhs_index]) + end = -strip_right if strip_right else None + params[rhs_index] = value[strip_left:end] + rhs_cast = f"CAST({rhs_sql} AS STRING)" + if lookup.lookup_name.startswith("i"): + rhs_cast = f"UPPER({rhs_cast})" + return lhs_sql, rhs_cast, tuple(params) -def contains(self, compiler, connection): - """A method to extend Django Contains and IContains classes. - :type self: :class:`~django.db.models.lookups.Contains` or - :class:`~django.db.models.lookups.IContains` +def iexact(self, compiler, connection): + """A method to extend Django IExact class. + + :type self: :class:`~django.db.models.lookups.IExact` :param self: the instance of the class that owns this method. - :type compiler: :class:`~django_spanner.compiler.SQLCompilerst` + :type compiler: :class:`~django_spanner.compiler.SQLCompiler` :param compiler: The query compiler responsible for generating the query. - Must have a compile method, returning a (sql, [params]) - tuple. Calling compiler(value) will return a quoted - `value`. :type connection: :class:`~google.cloud.spanner_dbapi.connection.Connection` :param connection: The Spanner database connection used for the current query. - :rtype: tuple[str, str] + :rtype: tuple[str, tuple] :returns: A tuple of the SQL request and parameters. """ - lhs_sql, lhs_params = self.process_lhs(compiler, connection) - rhs_sql, rhs_params = self.process_rhs(compiler, connection) - params = list(lhs_params) - params.extend(rhs_params) - is_icontains = self.lookup_name.startswith("i") - if self.rhs_is_direct_value() and rhs_params and not self.bilateral_transforms: - rhs_sql = self.get_rhs_op(connection, rhs_sql) - rhs_idx = len(lhs_params) - # Chop the leading and trailing percent signs that Django adds to the - # param since this isn't a LIKE query as Django expects. - params[rhs_idx] = params[rhs_idx][1:-1] - # Add the case insensitive flag for icontains. - if is_icontains: - params[rhs_idx] = "(?i)" + params[rhs_idx] - # rhs_sql is REGEXP_CONTAINS(%s, %%s), and lhs_sql is the column name. - return rhs_sql % lhs_sql, tuple(params) - else: - # rhs_sql is the expression/column to use as the base of the regular - # expression. - if is_icontains: - rhs_sql = "CONCAT('(?i)', " + rhs_sql + ")" - return ( - "REGEXP_CONTAINS(%s, %s)" - % (lhs_sql, connection.pattern_esc.format(rhs_sql)), - tuple(params), - ) + lhs_sql, rhs_cast, params = _pattern_lookup_sql( + self, compiler, connection, strip_left=0, strip_right=0 + ) + return f"{lhs_sql} = {rhs_cast}", params -def iexact(self, compiler, connection): - """A method to extend Django IExact class. Case-insensitive exact match. - If the value provided for comparison is None, it will be interpreted as - an SQL NULL. +def contains(self, compiler, connection): + """A method to extend Django Contains and IContains classes. - :type self: :class:`~django.db.models.lookups.IExact` + :type self: :class:`~django.db.models.lookups.Contains` or + :class:`~django.db.models.lookups.IContains` :param self: the instance of the class that owns this method. - :type compiler: :class:`~django_spanner.compiler.SQLCompilerst` + :type compiler: :class:`~django_spanner.compiler.SQLCompiler` :param compiler: The query compiler responsible for generating the query. - Must have a compile method, returning a (sql, [params]) - tuple. Calling compiler(value) will return a quoted - `value`. :type connection: :class:`~google.cloud.spanner_dbapi.connection.Connection` :param connection: The Spanner database connection used for the current query. - :rtype: tuple[str, str] + :rtype: tuple[str, tuple] :returns: A tuple of the SQL request and parameters. """ - lhs_sql, lhs_params = self.process_lhs(compiler, connection) - rhs_sql, rhs_params = self.process_rhs(compiler, connection) - params = list(lhs_params) - params.extend(rhs_params) - rhs_sql = self.get_rhs_op(connection, rhs_sql) - # Wrap the parameter in ^ and $ to restrict the regex to an exact match. - if self.rhs_is_direct_value() and rhs_params and not self.bilateral_transforms: - rhs_idx = len(lhs_params) - params[rhs_idx] = "^(?i)%s$" % params[rhs_idx] - else: - # lhs_sql is the expression/column to use as the regular expression. - # Use concat to make the value case-insensitive. - lhs_sql = "CONCAT('^(?i)', " + lhs_sql + ", '$')" - if not self.rhs_is_direct_value(): - # If rhs is not a direct value - if not params: - # if params is not present, then we have only 1 formatable - # argument in rhs_sql. - rhs_sql = rhs_sql.replace("%%s", "%s") - else: - # If params is present and rhs_sql is to be replaced as well. - # Example: model_fields.test_uuid.TestQuerying.test_iexact. - rhs_sql = rhs_sql.replace("%%s", "__PLACEHOLDER_FOR_LHS_SQL__") - rhs_sql = rhs_sql.replace("%s", "%%s") - rhs_sql = rhs_sql.replace("__PLACEHOLDER_FOR_LHS_SQL__", "%s") - # rhs_sql is REGEXP_CONTAINS(%s, %%s), and lhs_sql is the column name. - return rhs_sql % lhs_sql, tuple(params) + lhs_sql, rhs_cast, params = _pattern_lookup_sql( + self, compiler, connection, strip_left=1, strip_right=1 + ) + return f"STRPOS({lhs_sql}, {rhs_cast}) > 0", params def regex(self, compiler, connection): @@ -132,17 +132,14 @@ def regex(self, compiler, connection): :class:`~django.db.models.lookups.IRegex` :param self: the instance of the class that owns this method. - :type compiler: :class:`~django_spanner.compiler.SQLCompilerst` + :type compiler: :class:`~django_spanner.compiler.SQLCompiler` :param compiler: The query compiler responsible for generating the query. - Must have a compile method, returning a (sql, [params]) - tuple. Calling compiler(value) will return a quoted - `value`. :type connection: :class:`~google.cloud.spanner_dbapi.connection.Connection` :param connection: The Spanner database connection used for the current query. - :rtype: tuple[str, str] + :rtype: tuple[str, tuple] :returns: A tuple of the SQL request and parameters. """ lhs_sql, lhs_params = self.process_lhs(compiler, connection) @@ -177,56 +174,26 @@ def startswith_endswith(self, compiler, connection): :class:`~django.db.models.lookups.IEndsWith` :param self: the instance of the class that owns this method. - :type compiler: :class:`~django_spanner.compiler.SQLCompilerst` + :type compiler: :class:`~django_spanner.compiler.SQLCompiler` :param compiler: The query compiler responsible for generating the query. - Must have a compile method, returning a (sql, [params]) - tuple. Calling compiler(value) will return a quoted - `value`. :type connection: :class:`~google.cloud.spanner_dbapi.connection.Connection` :param connection: The Spanner database connection used for the current query. - :rtype: tuple[str, str] + :rtype: tuple[str, tuple] :returns: A tuple of the SQL request and parameters. """ - lhs_sql, lhs_params = self.process_lhs(compiler, connection) - rhs_sql, rhs_params = self.process_rhs(compiler, connection) - params = list(lhs_params) - params.extend(rhs_params) - is_startswith = "startswith" in self.lookup_name is_endswith = "endswith" in self.lookup_name - is_insensitive = self.lookup_name.startswith("i") - # Chop the leading (endswith) or trailing (startswith) percent sign that - # Django adds to the param since this isn't a LIKE query as Django expects. - if self.rhs_is_direct_value() and rhs_params and not self.bilateral_transforms: - rhs_sql = self.get_rhs_op(connection, rhs_sql) - rhs_idx = len(lhs_params) - if is_endswith: - params[rhs_idx] = str(params[rhs_idx][1:]) + "$" - else: - params[rhs_idx] = "^" + str(params[rhs_idx][:-1]) - # Add the case insensitive flag for istartswith or iendswith. - if is_insensitive: - params[rhs_idx] = "(?i)" + params[rhs_idx] - # rhs_sql is REGEXP_CONTAINS(%s, %%s), and lhs_sql is the column name. - return rhs_sql % lhs_sql, tuple(params) - else: - # rhs_sql is the expression/column to use as the base of the regular - # expression. - sql = "CONCAT('" - if is_startswith: - sql += "^" - if is_insensitive: - sql += "(?i)" - sql += "', " + rhs_sql - if is_endswith: - sql += ", '$'" - sql += ")" - return ( - "REGEXP_CONTAINS(%s, %s)" % (lhs_sql, connection.pattern_esc.format(sql)), - tuple(params), - ) + lhs_sql, rhs_cast, params = _pattern_lookup_sql( + self, + compiler, + connection, + strip_left=1 if is_endswith else 0, + strip_right=0 if is_endswith else 1, + ) + function = "ENDS_WITH" if is_endswith else "STARTS_WITH" + return f"{function}({lhs_sql}, {rhs_cast})", params def cast_param_to_float(self, compiler, connection): diff --git a/packages/django-google-spanner/django_spanner/operations.py b/packages/django-google-spanner/django_spanner/operations.py index b19a111958ad..5f085c31b897 100644 --- a/packages/django-google-spanner/django_spanner/operations.py +++ b/packages/django-google-spanner/django_spanner/operations.py @@ -806,7 +806,8 @@ def combine_duration_expression(self, connector, sub_expressions): def lookup_cast(self, lookup_type, internal_type=None): """ - Cast text lookups to string to allow things like filter(x__contains=4). + Cast text lookups to string (and wrap case-insensitive non-regex + lookups in UPPER) to allow things like filter(x__contains=4). :type lookup_type: str :param lookup_type: A type of the lookup. @@ -821,28 +822,42 @@ def lookup_cast(self, lookup_type, internal_type=None): # filter(x__contains=4) if lookup_type in ( "contains", - "icontains", "startswith", - "istartswith", "endswith", - "iendswith", "regex", "iregex", - "iexact", ): return "CAST(%s AS STRING)" + # Wrap case-insensitive non-regex lookups in UPPER() here so BuiltinLookup + # and django_spanner.lookups emit: + # - iexact: UPPER(CAST(lhs AS STRING)) = UPPER(CAST(rhs AS STRING)) + # - icontains: STRPOS(UPPER(CAST(lhs AS STRING)), UPPER(CAST(rhs AS STRING))) > 0 + # - istartswith: STARTS_WITH(UPPER(CAST(lhs AS STRING)), UPPER(CAST(rhs AS STRING))) + # - iendswith: ENDS_WITH(UPPER(CAST(lhs AS STRING)), UPPER(CAST(rhs AS STRING))) + if lookup_type in ( + "iexact", + "icontains", + "istartswith", + "iendswith", + ): + return "UPPER(CAST(%s AS STRING))" return "%s" def prep_for_like_query(self, x): - """Lookups that use this method use REGEXP_CONTAINS instead of LIKE. + """Return the lookup value unchanged. - :type x: str - :param x: A query to prepare. + Django's PatternLookup and IExact pass direct parameter values through + this hook to escape LIKE wildcards. Because Spanner implements these + lookups using equality, STRPOS, STARTS_WITH, and ENDS_WITH (all of + which match strings literally), the value must be returned unmodified. - :rtype: str - :returns: A prepared query. + :type x: Any + :param x: A lookup value to prepare. + + :rtype: Any + :returns: The unmodified lookup value. """ - return re.escape(str(x)) + return x prep_for_iexact_query = prep_for_like_query diff --git a/packages/django-google-spanner/tests/system/django_spanner/test_check_constraint.py b/packages/django-google-spanner/tests/system/django_spanner/test_check_constraint.py index 3fbc20d225b2..dc5e690a1b64 100644 --- a/packages/django-google-spanner/tests/system/django_spanner/test_check_constraint.py +++ b/packages/django-google-spanner/tests/system/django_spanner/test_check_constraint.py @@ -235,6 +235,23 @@ class Meta: with self.assertRaisesRegex(ValidationError, "name_contains_ok"): name_constraint.validate(ValidationSample, ValidationSample(name="bad")) + literal_pattern_constraint = models.CheckConstraint( + condition=models.Q(name__startswith=models.Value(".*")) + & ~models.Q(name__iexact=".*forbidden"), + name="literal_pattern_name", + ) + literal_pattern_constraint.validate( + ValidationSample, ValidationSample(name=".*ok") + ) + with self.assertRaisesRegex(ValidationError, "literal_pattern_name"): + literal_pattern_constraint.validate( + ValidationSample, ValidationSample(name="ok") + ) + with self.assertRaisesRegex(ValidationError, "literal_pattern_name"): + literal_pattern_constraint.validate( + ValidationSample, ValidationSample(name=".*FORBIDDEN") + ) + # Date, DateTime, Time, Decimal, Duration, and UUID fields. date_val = datetime.date(2025, 1, 15) date_constraint = models.CheckConstraint( @@ -326,6 +343,22 @@ class Meta: ValidationSample, ValidationSample(uid=uuid.uuid4()) ) + uid_lookup_constraint = models.CheckConstraint( + condition=models.Q(uid__iexact="12345678-1234-5678-1234-567812345678") + & models.Q(uid__contains="1234-5678"), + name="uid_lookup", + ) + uid_lookup_constraint.validate( + ValidationSample, ValidationSample(uid=uid_val) + ) + with self.assertRaisesRegex(ValidationError, "uid_lookup"): + uid_lookup_constraint.validate( + ValidationSample, + ValidationSample( + uid=uuid.UUID("fedcba98-7654-3210-fedc-ba9876543210") + ), + ) + # Boolean expressions, GeneratedField, PK field, and validate_constraints(). expr_constraint = models.CheckConstraint( condition=models.ExpressionWrapper( diff --git a/packages/django-google-spanner/tests/system/django_spanner/test_queries.py b/packages/django-google-spanner/tests/system/django_spanner/test_queries.py index b9936f4df4ec..7d0de986a134 100644 --- a/packages/django-google-spanner/tests/system/django_spanner/test_queries.py +++ b/packages/django-google-spanner/tests/system/django_spanner/test_queries.py @@ -108,3 +108,355 @@ def test_typed_value_expressions_in_queries(self): ) finally: Author.objects.all().delete() + + def test_pattern_lookups_literal_metacharacters(self): + """Verify contains/startswith/endswith treat regex metacharacters literally.""" + from django.db import models + + class _UpperCaseTransform(models.Transform): + lookup_name = "upper" + function = "UPPER" + bilateral = True + + Author.objects.bulk_create( + [ + Author(first_name=".*", last_name=".*", rating=Decimal("1.0")), + Author( + first_name="Hello.*", + last_name="hello.*", + rating=Decimal("2.0"), + ), + Author( + first_name="50%_off", + last_name="50%_", + rating=Decimal("5.0"), + ), + Author( + first_name="[unclosed", + last_name="[", + rating=Decimal("4.0"), + ), + Author( + first_name="line1\nline2", + last_name="multiline", + rating=Decimal("6.0"), + ), + ] + ) + models.CharField.register_lookup(_UpperCaseTransform) + try: + + def first_names(queryset): + return set(queryset.values_list("first_name", flat=True)) + + self.assertEqual( + first_names(Author.objects.filter(first_name__contains=".*")), + {".*", "Hello.*"}, + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__contains=models.Value(".*")) + ), + {".*", "Hello.*"}, + ) + self.assertEqual( + first_names( + Author.objects.filter( + first_name__contains=models.Value("[unclosed") + ) + ), + {"[unclosed"}, + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__icontains=models.Value("HELLO.*")) + ), + {"Hello.*"}, + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__startswith=models.Value("50%_")) + ), + {"50%_off"}, + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__startswith=models.F("last_name")) + ), + {".*", "50%_off", "[unclosed"}, + ) + self.assertEqual( + first_names( + Author.objects.filter( + first_name__istartswith=models.Value("HELLO.*") + ) + ), + {"Hello.*"}, + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__endswith=models.Value(".*")) + ), + {".*", "Hello.*"}, + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__iendswith=models.F("last_name")) + ), + {".*", "Hello.*"}, + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__startswith=models.F("rating")) + ), + {"50%_off"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__upper__contains=".*")), + {".*", "Hello.*"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__icontains="hello.*")), + {"Hello.*"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__startswith="50%_")), + {"50%_off"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__endswith=".*")), + {".*", "Hello.*"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__contains="\n")), + {"line1\nline2"}, + ) + all_names = {".*", "Hello.*", "50%_off", "[unclosed", "line1\nline2"} + self.assertEqual( + first_names(Author.objects.filter(first_name__contains="")), + all_names, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__startswith="")), + all_names, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__endswith="")), + all_names, + ) + self.assertEqual( + first_names( + Author.objects.filter( + first_name__contains=models.Subquery( + Author.objects.filter(last_name="[").values("last_name")[:1] + ) + ) + ), + {"[unclosed"}, + ) + self.assertEqual( + first_names( + Author.objects.filter( + first_name__contains=models.Subquery( + Author.objects.none().values("last_name")[:1] + ) + ) + ), + set(), + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__contains=models.Value(None)) + ), + set(), + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__startswith=models.Value(None)) + ), + set(), + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__endswith=models.Value(None)) + ), + set(), + ) + finally: + models.CharField._unregister_lookup(_UpperCaseTransform) + Author.objects.all().delete() + + def test_iexact_and_regex_lookups(self): + """Verify iexact matches literally while regex and iregex evaluate patterns.""" + from django.db import models + + class _UpperCaseTransform(models.Transform): + lookup_name = "upper" + function = "UPPER" + bilateral = True + + Author.objects.bulk_create( + [ + Author(first_name=".*", last_name="other", rating=Decimal("1.0")), + Author( + first_name="Hello.*", + last_name="hello.*", + rating=Decimal("2.0"), + ), + Author( + first_name="HelloWorld", + last_name="world", + rating=Decimal("3.0"), + ), + Author( + first_name="[unclosed", + last_name="other", + rating=Decimal("4.0"), + ), + Author( + first_name="1.5", + last_name="float", + rating=Decimal("5.0"), + ), + Author( + first_name="1.50", + last_name="decimal", + rating=Decimal("6.0"), + ), + Author( + first_name=r"a\b", + last_name="backslash", + rating=Decimal("7.0"), + ), + Author( + first_name="Café", + last_name="unicode", + rating=Decimal("8.0"), + ), + Author( + first_name="line1\nline2", + last_name="multiline", + rating=Decimal("9.0"), + ), + Author( + first_name="Straße", + last_name="german", + rating=Decimal("10.0"), + ), + ] + ) + models.CharField.register_lookup(_UpperCaseTransform) + try: + + def first_names(queryset): + return set(queryset.values_list("first_name", flat=True)) + + self.assertEqual( + first_names(Author.objects.filter(first_name__iexact=".*")), + {".*"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__iexact="[UNCLOSED")), + {"[unclosed"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__iexact=1.5)), + {"1.5"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__iexact=Decimal("1.50"))), + {"1.50"}, + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__iexact=models.Value(1.5)) + ), + {"1.5"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__iexact=r"a\b")), + {r"a\b"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__iexact="CAFÉ")), + {"Café"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__iexact="LINE1\nLINE2")), + {"line1\nline2"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__iexact="")), + set(), + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__iexact=models.Value(None)) + ), + set(), + ) + self.assertEqual( + first_names( + Author.objects.filter( + first_name__iexact=models.Subquery( + Author.objects.filter(last_name="hello.*").values( + "last_name" + )[:1] + ) + ) + ), + {"Hello.*"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__iexact="STRASSE")), + {"Straße"}, + ) + self.assertEqual( + first_names( + Author.objects.filter( + first_name__iexact=models.Subquery( + Author.objects.none().values("last_name")[:1] + ) + ) + ), + set(), + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__in=[".*", "Hello.*"]).exclude( + first_name__iexact=".*" + ) + ), + {"Hello.*"}, + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__iexact=models.Value("HELLO.*")) + ), + {"Hello.*"}, + ) + self.assertEqual( + first_names( + Author.objects.filter(first_name__iexact=models.F("last_name")) + ), + {"Hello.*"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__upper__iexact="HELLO")), + set(), + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__upper__iexact="HELLO.*")), + {"Hello.*"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__regex=r"^Hello\.\*$")), + {"Hello.*"}, + ) + self.assertEqual( + first_names(Author.objects.filter(first_name__iregex=r"^hello")), + {"Hello.*", "HelloWorld"}, + ) + finally: + models.CharField._unregister_lookup(_UpperCaseTransform) + Author.objects.all().delete() diff --git a/packages/django-google-spanner/tests/unit/django_spanner/test_lookups.py b/packages/django-google-spanner/tests/unit/django_spanner/test_lookups.py index 3d53acc0dcc7..3c10b2b0d9b8 100644 --- a/packages/django-google-spanner/tests/unit/django_spanner/test_lookups.py +++ b/packages/django-google-spanner/tests/unit/django_spanner/test_lookups.py @@ -4,10 +4,13 @@ # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd +import uuid from decimal import Decimal -from django.db.models import F, Value +from django.db import models +from django.db.models import F, Subquery, Value from django.db.models.functions import Concat +from django.test.utils import isolate_apps from django_spanner.compiler import SQLCompiler from tests.unit.django_spanner.simple_test import SpannerSimpleTestClass @@ -70,9 +73,9 @@ def test_startswith_endswith_sql_query_with_startswith(self): self.assertEqual( sql_compiled, "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "STARTS_WITH(CAST(tests_author.name AS STRING), CAST(%s AS STRING))", ) - self.assertEqual(params, ("^abc",)) + self.assertEqual(params, ("abc",)) def test_startswith_endswith_sql_query_with_endswith(self): qs1 = Author.objects.filter(name__endswith="abc").values("num") @@ -81,9 +84,9 @@ def test_startswith_endswith_sql_query_with_endswith(self): self.assertEqual( sql_compiled, "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "ENDS_WITH(CAST(tests_author.name AS STRING), CAST(%s AS STRING))", ) - self.assertEqual(params, ("abc$",)) + self.assertEqual(params, ("abc",)) def test_startswith_endswith_sql_query_case_insensitive(self): qs1 = Author.objects.filter(name__istartswith="abc").values("num") @@ -92,9 +95,10 @@ def test_startswith_endswith_sql_query_case_insensitive(self): self.assertEqual( sql_compiled, "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "STARTS_WITH(UPPER(CAST(tests_author.name AS STRING)), " + "UPPER(CAST(%s AS STRING)))", ) - self.assertEqual(params, ("(?i)^abc",)) + self.assertEqual(params, ("abc",)) def test_startswith_endswith_sql_query_with_bileteral_transform(self): qs1 = Author.objects.filter(name__upper__startswith="abc").values("name") @@ -103,9 +107,8 @@ def test_startswith_endswith_sql_query_with_bileteral_transform(self): sql_compiled, params = compiler.as_sql() expected_sql = ( "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(UPPER(tests_author.name) AS STRING), " - + "REPLACE(REPLACE(REPLACE(CONCAT('^', (UPPER(%s))), " - + '"\\\\", "\\\\\\\\"), "%%", r"\\%%"), "_", r"\\_"))' + "STARTS_WITH(CAST(UPPER(tests_author.name) AS STRING), " + "CAST((UPPER(%s)) AS STRING))" ) self.assertEqual(sql_compiled, expected_sql) self.assertEqual(params, ("abc",)) @@ -117,9 +120,8 @@ def test_startswith_endswith_case_insensitive_transform_sql_query(self): sql_compiled, params = compiler.as_sql() expected_sql = ( "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(UPPER(tests_author.name) AS STRING), " - + "REPLACE(REPLACE(REPLACE(CONCAT('^(?i)', (UPPER(%s))), " - + '"\\\\", "\\\\\\\\"), "%%", r"\\%%"), "_", r"\\_"))' + "STARTS_WITH(UPPER(CAST(UPPER(tests_author.name) AS STRING)), " + "UPPER(CAST((UPPER(%s)) AS STRING)))" ) self.assertEqual(sql_compiled, expected_sql) self.assertEqual(params, ("abc",)) @@ -132,9 +134,8 @@ def test_startswith_endswith_endswith_sql_query_with_transform(self): expected_sql = ( "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(UPPER(tests_author.name) AS STRING), " - + "REPLACE(REPLACE(REPLACE(CONCAT('', (UPPER(%s)), '$'), " - + '"\\\\", "\\\\\\\\"), "%%", r"\\%%"), "_", r"\\_"))' + "ENDS_WITH(CAST(UPPER(tests_author.name) AS STRING), " + "CAST((UPPER(%s)) AS STRING))" ) self.assertEqual(sql_compiled, expected_sql) self.assertEqual(params, ("abc",)) @@ -194,9 +195,10 @@ def test_contains_sql_query_case_insensitive(self): self.assertEqual( sql_compiled, "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "STRPOS(UPPER(CAST(tests_author.name AS STRING)), " + "UPPER(CAST(%s AS STRING))) > 0", ) - self.assertEqual(params, ("(?i)abc",)) + self.assertEqual(params, ("abc",)) def test_contains_sql_query_case_sensitive(self): qs1 = Author.objects.filter(name__contains="abc").values("num") @@ -205,7 +207,7 @@ def test_contains_sql_query_case_sensitive(self): self.assertEqual( sql_compiled, "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "STRPOS(CAST(tests_author.name AS STRING), CAST(%s AS STRING)) > 0", ) self.assertEqual(params, ("abc",)) @@ -215,9 +217,8 @@ def test_contains_sql_query_case_insensitive_transform(self): sql_compiled, params = compiler.as_sql() expected_sql = ( "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(UPPER(tests_author.name) AS STRING), " - + "REPLACE(REPLACE(REPLACE(CONCAT('(?i)', (UPPER(%s))), " - + '"\\\\", "\\\\\\\\"), "%%", r"\\%%"), "_", r"\\_"))' + "STRPOS(UPPER(CAST(UPPER(tests_author.name) AS STRING)), " + "UPPER(CAST((UPPER(%s)) AS STRING))) > 0" ) self.assertEqual(sql_compiled, expected_sql) self.assertEqual(params, ("abc",)) @@ -228,9 +229,8 @@ def test_contains_sql_query_case_sensitive_transform(self): sql_compiled, params = compiler.as_sql() expected_sql = ( "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(UPPER(tests_author.name) AS STRING), " - + 'REPLACE(REPLACE(REPLACE((UPPER(%s)), "\\\\", "\\\\\\\\"), ' - + '"%%", r"\\%%"), "_", r"\\_"))' + "STRPOS(CAST(UPPER(tests_author.name) AS STRING), " + "CAST((UPPER(%s)) AS STRING)) > 0" ) self.assertEqual(sql_compiled, expected_sql) self.assertEqual(params, ("abc",)) @@ -243,9 +243,9 @@ def test_iexact_sql_query_case_insensitive(self): self.assertEqual( sql_compiled, "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "UPPER(CAST(tests_author.name AS STRING)) = UPPER(CAST(%s AS STRING))", ) - self.assertEqual(params, ("^(?i)abc$",)) + self.assertEqual(params, ("abc",)) def test_iexact_sql_query_case_insensitive_function_transform(self): qs1 = Author.objects.filter(name__upper__iexact=F("last_name")).values("name") @@ -254,8 +254,8 @@ def test_iexact_sql_query_case_insensitive_function_transform(self): expected_sql = ( "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS((UPPER(tests_author.last_name)), " - + "CONCAT('^(?i)', CAST(UPPER(tests_author.name) AS STRING), '$'))" + "UPPER(CAST(UPPER(tests_author.name) AS STRING)) = " + "UPPER(CAST((UPPER(tests_author.last_name)) AS STRING))" ) self.assertEqual(sql_compiled, expected_sql) self.assertEqual(params, ()) @@ -267,8 +267,8 @@ def test_iexact_sql_query_case_insensitive_value_match(self): expected_sql = ( "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS((UPPER(CONCAT('^(?i)', " - + "CAST(UPPER(tests_author.name) AS STRING), '$'))), %s)" + "UPPER(CAST(UPPER(tests_author.name) AS STRING)) = " + "UPPER(CAST((UPPER(%s)) AS STRING))" ) self.assertEqual(sql_compiled, expected_sql) self.assertEqual(params, ("abc",)) @@ -281,7 +281,8 @@ def test_icontains_with_lhs_params(self): ) compiler = SQLCompiler(qs.query, self.connection, "default") sql, params = compiler.as_sql() - self.assertEqual(params, ("User: ", "", "", "(?i)john")) + self.assertIn("STRPOS(", sql) + self.assertEqual(params, ("User: ", "", "", "john")) def test_iexact_with_lhs_params(self): qs = ( @@ -291,7 +292,8 @@ def test_iexact_with_lhs_params(self): ) compiler = SQLCompiler(qs.query, self.connection, "default") sql, params = compiler.as_sql() - self.assertEqual(params, ("User: ", "", "", "^(?i)john$")) + self.assertIn(" = UPPER(", sql) + self.assertEqual(params, ("User: ", "", "", "john")) def test_istartswith_with_lhs_params(self): qs = ( @@ -301,7 +303,8 @@ def test_istartswith_with_lhs_params(self): ) compiler = SQLCompiler(qs.query, self.connection, "default") sql, params = compiler.as_sql() - self.assertEqual(params, ("User: ", "", "", "(?i)^john")) + self.assertIn("STARTS_WITH(", sql) + self.assertEqual(params, ("User: ", "", "", "john")) def test_iendswith_with_lhs_params(self): qs = ( @@ -311,7 +314,8 @@ def test_iendswith_with_lhs_params(self): ) compiler = SQLCompiler(qs.query, self.connection, "default") sql, params = compiler.as_sql() - self.assertEqual(params, ("User: ", "", "", "(?i)john$")) + self.assertIn("ENDS_WITH(", sql) + self.assertEqual(params, ("User: ", "", "", "john")) def test_iregex_with_lhs_params(self): qs = ( @@ -323,6 +327,272 @@ def test_iregex_with_lhs_params(self): sql, params = compiler.as_sql() self.assertEqual(params, ("User: ", "", "", "(?i)^john")) + def _assert_where_clauses(self, cases, table="tests_author", column="num"): + for queryset, expected_where, expected_params in cases: + with self.subTest(expected_where=expected_where, params=expected_params): + compiler = SQLCompiler( + queryset.values(column).query, self.connection, "default" + ) + sql_compiled, params = compiler.as_sql() + self.assertEqual( + sql_compiled, + f"SELECT {table}.{column} AS {column} FROM {table} " + f"WHERE {expected_where}", + ) + self.assertEqual(params, expected_params) + + def test_pattern_lookups_with_expression_rhs_and_metacharacters(self): + metacharacters = r".*+?()[]{}\|^$%_" + self._assert_where_clauses( + [ + ( + Author.objects.filter(name__contains=Value(metacharacters)), + "STRPOS(CAST(tests_author.name AS STRING), CAST(%s AS STRING)) > 0", + (metacharacters,), + ), + ( + Author.objects.filter(name__icontains=Value(metacharacters)), + "STRPOS(UPPER(CAST(tests_author.name AS STRING)), " + "UPPER(CAST(%s AS STRING))) > 0", + (metacharacters,), + ), + ( + Author.objects.filter(name__startswith=Value(metacharacters)), + "STARTS_WITH(CAST(tests_author.name AS STRING), " + "CAST(%s AS STRING))", + (metacharacters,), + ), + ( + Author.objects.filter(name__istartswith=Value(metacharacters)), + "STARTS_WITH(UPPER(CAST(tests_author.name AS STRING)), " + "UPPER(CAST(%s AS STRING)))", + (metacharacters,), + ), + ( + Author.objects.filter(name__endswith=Value(metacharacters)), + "ENDS_WITH(CAST(tests_author.name AS STRING), CAST(%s AS STRING))", + (metacharacters,), + ), + ( + Author.objects.filter(name__iendswith=Value(metacharacters)), + "ENDS_WITH(UPPER(CAST(tests_author.name AS STRING)), " + "UPPER(CAST(%s AS STRING)))", + (metacharacters,), + ), + ( + Author.objects.filter(name__contains=F("last_name")), + "STRPOS(CAST(tests_author.name AS STRING), " + "CAST((tests_author.last_name) AS STRING)) > 0", + (), + ), + ( + Author.objects.filter(name__startswith=F("num")), + "STARTS_WITH(CAST(tests_author.name AS STRING), " + "CAST((tests_author.num) AS STRING))", + (), + ), + ( + Author.objects.filter(name__upper__contains=metacharacters), + "STRPOS(CAST(UPPER(tests_author.name) AS STRING), " + "CAST((UPPER(%s)) AS STRING)) > 0", + (metacharacters,), + ), + ( + Author.objects.filter(name__upper__iendswith=metacharacters), + "ENDS_WITH(UPPER(CAST(UPPER(tests_author.name) AS STRING)), " + "UPPER(CAST((UPPER(%s)) AS STRING)))", + (metacharacters,), + ), + ( + Author.objects.filter(name__contains=""), + "STRPOS(CAST(tests_author.name AS STRING), CAST(%s AS STRING)) > 0", + ("",), + ), + ( + Author.objects.filter(name__startswith="%"), + "STARTS_WITH(CAST(tests_author.name AS STRING), " + "CAST(%s AS STRING))", + ("%",), + ), + ( + Author.objects.filter(name__endswith="%"), + "ENDS_WITH(CAST(tests_author.name AS STRING), CAST(%s AS STRING))", + ("%",), + ), + ( + Author.objects.filter(name__contains=Value(None)), + "STRPOS(CAST(tests_author.name AS STRING), " + "CAST(NULL AS STRING)) > 0", + (), + ), + ( + Author.objects.filter(name__contains=4), + "STRPOS(CAST(tests_author.name AS STRING), CAST(%s AS STRING)) > 0", + ("4",), + ), + ] + ) + + def test_iexact_with_expression_rhs_and_metacharacters(self): + metacharacters = r".*+?()[]{}\|^$%_" + self._assert_where_clauses( + [ + ( + Author.objects.filter(name__iexact=metacharacters), + "UPPER(CAST(tests_author.name AS STRING)) = " + "UPPER(CAST(%s AS STRING))", + (metacharacters,), + ), + ( + Author.objects.filter(name__iexact=Value(metacharacters)), + "UPPER(CAST(tests_author.name AS STRING)) = " + "UPPER(CAST(%s AS STRING))", + (metacharacters,), + ), + ( + Author.objects.filter(name__iexact=F("last_name")), + "UPPER(CAST(tests_author.name AS STRING)) = " + "UPPER(CAST((tests_author.last_name) AS STRING))", + (), + ), + ( + Author.objects.filter(name__upper__iexact=metacharacters), + "UPPER(CAST(UPPER(tests_author.name) AS STRING)) = " + "UPPER(CAST((UPPER(%s)) AS STRING))", + (metacharacters,), + ), + ( + Author.objects.filter(name__iexact=Value(None)), + "UPPER(CAST(tests_author.name AS STRING)) = " + "UPPER(CAST(NULL AS STRING))", + (), + ), + ( + Author.objects.filter(name__iexact=4), + "UPPER(CAST(tests_author.name AS STRING)) = " + "UPPER(CAST(%s AS STRING))", + ("4",), + ), + ( + Author.objects.filter(name__iexact=1.5), + "UPPER(CAST(tests_author.name AS STRING)) = " + "UPPER(CAST(%s AS STRING))", + ("1.5",), + ), + ( + Author.objects.filter(name__iexact=Decimal("1.50")), + "UPPER(CAST(tests_author.name AS STRING)) = " + "UPPER(CAST(%s AS STRING))", + ("1.50",), + ), + ( + Author.objects.filter(name__iexact=Value(1.5)), + "UPPER(CAST(tests_author.name AS STRING)) = " + "UPPER(CAST(CAST(%s AS FLOAT64) AS STRING))", + (1.5,), + ), + ( + Author.objects.filter( + name__iexact=Subquery( + Author.objects.filter(last_name=".*").values("last_name")[ + :1 + ] + ) + ), + "UPPER(CAST(tests_author.name AS STRING)) = " + "UPPER(CAST((SELECT U0.last_name AS last_name " + "FROM tests_author U0 WHERE U0.last_name = %s LIMIT 1) AS STRING))", + (".*",), + ), + ] + ) + + @isolate_apps("tests") + def test_uuid_field_pattern_and_iexact_lookups(self): + class UuidLookupModel(models.Model): + token = models.UUIDField() + + class Meta: + app_label = "tests" + + uuid_string = "12345678-1234-5678-1234-567812345678" + uuid_value = uuid.UUID(uuid_string) + self._assert_where_clauses( + [ + ( + UuidLookupModel.objects.filter(token__iexact=uuid_value), + "UPPER(CAST(tests_uuidlookupmodel.token AS STRING)) = " + "UPPER(CAST((REPLACE(%s, %s, %s)) AS STRING))", + ("12345678123456781234567812345678", "-", ""), + ), + ( + UuidLookupModel.objects.filter(token__iexact=uuid_string), + "UPPER(CAST(tests_uuidlookupmodel.token AS STRING)) = " + "UPPER(CAST((REPLACE(%s, %s, %s)) AS STRING))", + (uuid_string, "-", ""), + ), + ( + UuidLookupModel.objects.filter(token__iexact=Value(None)), + "UPPER(CAST(tests_uuidlookupmodel.token AS STRING)) = " + "UPPER(CAST((REPLACE(NULL, %s, %s)) AS STRING))", + ("-", ""), + ), + ( + UuidLookupModel.objects.filter(token__contains=".*"), + "STRPOS(CAST(tests_uuidlookupmodel.token AS STRING), " + "CAST((REPLACE(%s, %s, %s)) AS STRING)) > 0", + (".*", "-", ""), + ), + ( + UuidLookupModel.objects.filter(token__istartswith="1234-56"), + "STARTS_WITH(UPPER(CAST(tests_uuidlookupmodel.token AS STRING)), " + "UPPER(CAST((REPLACE(%s, %s, %s)) AS STRING)))", + ("1234-56", "-", ""), + ), + ], + table="tests_uuidlookupmodel", + column="token", + ) + + @isolate_apps("tests") + def test_json_key_transform_pattern_and_iexact_lookups(self): + class JsonLookupModel(models.Model): + data = models.JSONField() + + class Meta: + app_label = "tests" + + self._assert_where_clauses( + [ + ( + JsonLookupModel.objects.filter(data__foo__iexact="Bar.*"), + "UPPER(CAST(JSON_VALUE(tests_jsonlookupmodel.data, '$.\"foo\"') AS STRING)) = " + "UPPER(CAST(%s AS STRING))", + ("Bar.*",), + ), + ( + JsonLookupModel.objects.filter(data__foo__icontains="Bar.*"), + "STRPOS(UPPER(CAST(JSON_VALUE(tests_jsonlookupmodel.data, '$.\"foo\"') AS STRING)), " + "UPPER(CAST(%s AS STRING))) > 0", + ("Bar.*",), + ), + ( + JsonLookupModel.objects.filter(data__foo__startswith="Bar.*"), + "STARTS_WITH(CAST(JSON_VALUE(tests_jsonlookupmodel.data, '$.\"foo\"') AS STRING), " + "CAST(%s AS STRING))", + ("Bar.*",), + ), + ( + JsonLookupModel.objects.filter(data__foo__endswith="Bar.*"), + "ENDS_WITH(CAST(JSON_VALUE(tests_jsonlookupmodel.data, '$.\"foo\"') AS STRING), " + "CAST(%s AS STRING))", + ("Bar.*",), + ), + ], + table="tests_jsonlookupmodel", + column="data", + ) + def test_json_key_transforms_and_has_key(self): from unittest.mock import MagicMock diff --git a/packages/django-google-spanner/tests/unit/django_spanner/test_operations.py b/packages/django-google-spanner/tests/unit/django_spanner/test_operations.py index ee71c56b8ad2..e542bb6a99a4 100644 --- a/packages/django-google-spanner/tests/unit/django_spanner/test_operations.py +++ b/packages/django-google-spanner/tests/unit/django_spanner/test_operations.py @@ -665,12 +665,18 @@ def test_combine_duration_expression_database_error(self): ) def test_lookup_cast_match_lookup_type(self): - self.assertEqual( - self.db_operations.lookup_cast( - "contains", - ), - "CAST(%s AS STRING)", - ) + for lookup_type in ("contains", "startswith", "endswith", "regex", "iregex"): + with self.subTest(lookup_type=lookup_type): + self.assertEqual( + self.db_operations.lookup_cast(lookup_type), + "CAST(%s AS STRING)", + ) + for lookup_type in ("iexact", "icontains", "istartswith", "iendswith"): + with self.subTest(lookup_type=lookup_type): + self.assertEqual( + self.db_operations.lookup_cast(lookup_type), + "UPPER(CAST(%s AS STRING))", + ) def test_lookup_cast_unmatched_lookup_type(self): self.assertEqual( @@ -721,12 +727,10 @@ def test_get_limit_offset_params(self): self.assertEqual(offset, 0) def test_prep_for_like_and_iexact_query(self): - self.assertEqual( - self.db_operations.prep_for_like_query("test.val*"), r"test\.val\*" - ) - self.assertEqual( - self.db_operations.prep_for_iexact_query("test.val*"), r"test\.val\*" - ) + for value in ("test.val*", r".*+?()[]{}\|^$%_", 4, None): + with self.subTest(value=value): + self.assertEqual(self.db_operations.prep_for_like_query(value), value) + self.assertEqual(self.db_operations.prep_for_iexact_query(value), value) def test_bulk_insert_sql(self): fields = [mock.MagicMock(column="col1"), mock.MagicMock(column="col2")]