Fixed #33872 -- Deprecated django.contrib.postgres.fields.CIText/CICharField/CIEmailField/CITextField.

This commit is contained in:
Mariusz Felisiak 2022-08-03 11:42:51 +02:00 committed by GitHub
parent 09e837c5d9
commit cb791a2540
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 228 additions and 21 deletions

View File

@ -68,18 +68,35 @@ class ArrayField(CheckFieldDefaultMixin, Field):
) )
else: else:
# Remove the field name checks as they are not needed here. # Remove the field name checks as they are not needed here.
base_errors = self.base_field.check() base_checks = self.base_field.check()
if base_errors: if base_checks:
messages = "\n ".join( error_messages = "\n ".join(
"%s (%s)" % (error.msg, error.id) for error in base_errors "%s (%s)" % (base_check.msg, base_check.id)
for base_check in base_checks
if isinstance(base_check, checks.Error)
) )
errors.append( if error_messages:
checks.Error( errors.append(
"Base field for array has errors:\n %s" % messages, checks.Error(
obj=self, "Base field for array has errors:\n %s" % error_messages,
id="postgres.E001", obj=self,
id="postgres.E001",
)
) )
warning_messages = "\n ".join(
"%s (%s)" % (base_check.msg, base_check.id)
for base_check in base_checks
if isinstance(base_check, checks.Warning)
) )
if warning_messages:
errors.append(
checks.Warning(
"Base field for array has warnings:\n %s"
% warning_messages,
obj=self,
id="postgres.W004",
)
)
return errors return errors
def set_attributes_from_name(self, name): def set_attributes_from_name(self, name):

View File

@ -1,9 +1,22 @@
import warnings
from django.db.models import CharField, EmailField, TextField from django.db.models import CharField, EmailField, TextField
from django.test.utils import ignore_warnings
from django.utils.deprecation import RemovedInDjango51Warning
__all__ = ["CICharField", "CIEmailField", "CIText", "CITextField"] __all__ = ["CICharField", "CIEmailField", "CIText", "CITextField"]
# RemovedInDjango51Warning.
class CIText: class CIText:
def __init__(self, *args, **kwargs):
warnings.warn(
"django.contrib.postgres.fields.CIText mixin is deprecated.",
RemovedInDjango51Warning,
stacklevel=2,
)
super().__init__(*args, **kwargs)
def get_internal_type(self): def get_internal_type(self):
return "CI" + super().get_internal_type() return "CI" + super().get_internal_type()
@ -12,12 +25,54 @@ class CIText:
class CICharField(CIText, CharField): class CICharField(CIText, CharField):
pass system_check_deprecated_details = {
"msg": (
"django.contrib.postgres.fields.CICharField is deprecated. Support for it "
"(except in historical migrations) will be removed in Django 5.1."
),
"hint": (
'Use CharField(db_collation="") with a case-insensitive non-deterministic '
"collation instead."
),
"id": "fields.W905",
}
def __init__(self, *args, **kwargs):
with ignore_warnings(category=RemovedInDjango51Warning):
super().__init__(*args, **kwargs)
class CIEmailField(CIText, EmailField): class CIEmailField(CIText, EmailField):
pass system_check_deprecated_details = {
"msg": (
"django.contrib.postgres.fields.CIEmailField is deprecated. Support for it "
"(except in historical migrations) will be removed in Django 5.1."
),
"hint": (
'Use EmailField(db_collation="") with a case-insensitive '
"non-deterministic collation instead."
),
"id": "fields.W906",
}
def __init__(self, *args, **kwargs):
with ignore_warnings(category=RemovedInDjango51Warning):
super().__init__(*args, **kwargs)
class CITextField(CIText, TextField): class CITextField(CIText, TextField):
pass system_check_deprecated_details = {
"msg": (
"django.contrib.postgres.fields.CITextField is deprecated. Support for it "
"(except in historical migrations) will be removed in Django 5.1."
),
"hint": (
'Use TextField(db_collation="") with a case-insensitive non-deterministic '
"collation instead."
),
"id": "fields.W907",
}
def __init__(self, *args, **kwargs):
with ignore_warnings(category=RemovedInDjango51Warning):
super().__init__(*args, **kwargs)

View File

@ -142,6 +142,7 @@ class DatabaseOperations(BaseDatabaseOperations):
): ):
if internal_type in ("IPAddressField", "GenericIPAddressField"): if internal_type in ("IPAddressField", "GenericIPAddressField"):
lookup = "HOST(%s)" lookup = "HOST(%s)"
# RemovedInDjango51Warning.
elif internal_type in ("CICharField", "CIEmailField", "CITextField"): elif internal_type in ("CICharField", "CIEmailField", "CITextField"):
lookup = "%s::citext" lookup = "%s::citext"
else: else:

View File

@ -25,6 +25,13 @@ details on these changes.
``django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher``, and ``django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher``, and
``django.contrib.auth.hashers.UnsaltedMD5PasswordHasher`` will be removed. ``django.contrib.auth.hashers.UnsaltedMD5PasswordHasher`` will be removed.
* The model ``django.contrib.postgres.fields.CICharField``,
``django.contrib.postgres.fields.CIEmailField``, and
``django.contrib.postgres.fields.CITextField`` will be removed. Stub fields
will remain for compatibility with historical migrations.
* The ``django.contrib.postgres.fields.CIText`` mixin will be removed.
.. _deprecation-removed-in-5.0: .. _deprecation-removed-in-5.0:
5.0 5.0

View File

@ -223,6 +223,15 @@ Model fields
4.0. *This check appeared in Django 3.1 and 3.2*. 4.0. *This check appeared in Django 3.1 and 3.2*.
* **fields.E904**: ``django.contrib.postgres.fields.JSONField`` is removed * **fields.E904**: ``django.contrib.postgres.fields.JSONField`` is removed
except for support in historical migrations. except for support in historical migrations.
* **fields.W905**: ``django.contrib.postgres.fields.CICharField`` is
deprecated. Support for it (except in historical migrations) will be removed
in Django 5.1.
* **fields.W906**: ``django.contrib.postgres.fields.CIEmailField`` is
deprecated. Support for it (except in historical migrations) will be removed
in Django 5.1.
* **fields.W907**: ``django.contrib.postgres.fields.CITextField`` is
deprecated. Support for it (except in historical migrations) will be removed
in Django 5.1.
File fields File fields
~~~~~~~~~~~ ~~~~~~~~~~~
@ -851,6 +860,7 @@ fields:
* **postgres.E003**: ``<field>`` default should be a callable instead of an * **postgres.E003**: ``<field>`` default should be a callable instead of an
instance so that it's not shared between all field instances. *This check was instance so that it's not shared between all field instances. *This check was
changed to* ``fields.E010`` *in Django 3.1*. changed to* ``fields.E010`` *in Django 3.1*.
* **postgres.W004**: Base field for array has warnings: ...
``sites`` ``sites``
--------- ---------

View File

@ -259,6 +259,8 @@ transform do not change. For example::
.. class:: CIText(**options) .. class:: CIText(**options)
.. deprecated:: 4.2
A mixin to create case-insensitive text fields backed by the citext_ type. A mixin to create case-insensitive text fields backed by the citext_ type.
Read about `the performance considerations`_ prior to using it. Read about `the performance considerations`_ prior to using it.
@ -274,9 +276,29 @@ transform do not change. For example::
Several fields that use the mixin are provided: Several fields that use the mixin are provided:
.. class:: CICharField(**options) .. class:: CICharField(**options)
.. deprecated:: 4.2
``CICharField`` is deprecated in favor of
``CharField(db_collation="…")`` with a case-insensitive
non-deterministic collation.
.. class:: CIEmailField(**options) .. class:: CIEmailField(**options)
.. deprecated:: 4.2
``CIEmailField`` is deprecated in favor of
``EmailField(db_collation="…")`` with a case-insensitive
non-deterministic collation.
.. class:: CITextField(**options) .. class:: CITextField(**options)
.. deprecated:: 4.2
``CITextField`` is deprecated in favor of
``TextField(db_collation="…")`` with a case-insensitive
non-deterministic collation.
These fields subclass :class:`~django.db.models.CharField`, These fields subclass :class:`~django.db.models.CharField`,
:class:`~django.db.models.EmailField`, and :class:`~django.db.models.EmailField`, and
:class:`~django.db.models.TextField`, respectively. :class:`~django.db.models.TextField`, respectively.

View File

@ -215,11 +215,11 @@ Minor features
parameter to specify a custom class to encode data types not supported by the parameter to specify a custom class to encode data types not supported by the
standard encoder. standard encoder.
* The new :class:`~django.contrib.postgres.fields.CIText` mixin and * The new ``CIText`` mixin and
:class:`~django.contrib.postgres.operations.CITextExtension` migration :class:`~django.contrib.postgres.operations.CITextExtension` migration
operation allow using PostgreSQL's ``citext`` extension for case-insensitive operation allow using PostgreSQL's ``citext`` extension for case-insensitive
lookups. Three fields are provided: :class:`.CICharField`, lookups. Three fields are provided: ``CICharField``, ``CIEmailField``, and
:class:`.CIEmailField`, and :class:`.CITextField`. ``CITextField``.
* The new :class:`~django.contrib.postgres.aggregates.JSONBAgg` allows * The new :class:`~django.contrib.postgres.aggregates.JSONBAgg` allows
aggregating values as a JSON array. aggregating values as a JSON array.

View File

@ -351,3 +351,17 @@ Miscellaneous
* ``django.contrib.auth.hashers.SHA1PasswordHasher``, * ``django.contrib.auth.hashers.SHA1PasswordHasher``,
``django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher``, and ``django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher``, and
``django.contrib.auth.hashers.UnsaltedMD5PasswordHasher`` are deprecated. ``django.contrib.auth.hashers.UnsaltedMD5PasswordHasher`` are deprecated.
* ``django.contrib.postgres.fields.CICharField`` is deprecated in favor of
``CharField(db_collation="…")`` with a case-insensitive non-deterministic
collation.
* ``django.contrib.postgres.fields.CIEmailField`` is deprecated in favor of
``EmailField(db_collation="…")`` with a case-insensitive non-deterministic
collation.
* ``django.contrib.postgres.fields.CITextField`` is deprecated in favor of
``TextField(db_collation="…")`` with a case-insensitive non-deterministic
collation.
* ``django.contrib.postgres.fields.CIText`` mixin is deprecated.

View File

@ -283,6 +283,7 @@ class Tests(TestCase):
for lookup in lookups: for lookup in lookups:
with self.subTest(lookup=lookup): with self.subTest(lookup=lookup):
self.assertIn("::text", do.lookup_cast(lookup)) self.assertIn("::text", do.lookup_cast(lookup))
# RemovedInDjango51Warning.
for lookup in lookups: for lookup in lookups:
for field_type in ("CICharField", "CIEmailField", "CITextField"): for field_type in ("CICharField", "CIEmailField", "CITextField"):
with self.subTest(lookup=lookup, field_type=field_type): with self.subTest(lookup=lookup, field_type=field_type):

View File

@ -85,3 +85,65 @@ class DeprecatedFieldsTests(SimpleTestCase):
), ),
], ],
) )
@skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL")
def test_postgres_ci_fields_deprecated(self):
from django.contrib.postgres.fields import (
ArrayField,
CICharField,
CIEmailField,
CITextField,
)
class PostgresCIFieldsModel(models.Model):
ci_char = CICharField(max_length=255)
ci_email = CIEmailField()
ci_text = CITextField()
array_ci_text = ArrayField(CITextField())
self.assertEqual(
PostgresCIFieldsModel.check(),
[
checks.Warning(
"django.contrib.postgres.fields.CICharField is deprecated. Support "
"for it (except in historical migrations) will be removed in "
"Django 5.1.",
hint=(
'Use CharField(db_collation="") with a case-insensitive '
"non-deterministic collation instead."
),
obj=PostgresCIFieldsModel._meta.get_field("ci_char"),
id="fields.W905",
),
checks.Warning(
"django.contrib.postgres.fields.CIEmailField is deprecated. "
"Support for it (except in historical migrations) will be removed "
"in Django 5.1.",
hint=(
'Use EmailField(db_collation="") with a case-insensitive '
"non-deterministic collation instead."
),
obj=PostgresCIFieldsModel._meta.get_field("ci_email"),
id="fields.W906",
),
checks.Warning(
"django.contrib.postgres.fields.CITextField is deprecated. Support "
"for it (except in historical migrations) will be removed in "
"Django 5.1.",
hint=(
'Use TextField(db_collation="") with a case-insensitive '
"non-deterministic collation instead."
),
obj=PostgresCIFieldsModel._meta.get_field("ci_text"),
id="fields.W907",
),
checks.Warning(
"Base field for array has warnings:\n"
" django.contrib.postgres.fields.CITextField is deprecated. "
"Support for it (except in historical migrations) will be removed "
"in Django 5.1. (fields.W907)",
obj=PostgresCIFieldsModel._meta.get_field("array_ci_text"),
id="postgres.W004",
),
],
)

View File

@ -7,12 +7,12 @@ import enum
from django.db import models from django.db import models
try: try:
from django.contrib.postgres.fields import CICharField # RemovedInDjango51Warning.
from django.contrib.postgres.fields import CIEmailField # RemovedInDjango51Warning.
from django.contrib.postgres.fields import CITextField # RemovedInDjango51Warning.
from django.contrib.postgres.fields import ( from django.contrib.postgres.fields import (
ArrayField, ArrayField,
BigIntegerRangeField, BigIntegerRangeField,
CICharField,
CIEmailField,
CITextField,
DateRangeField, DateRangeField,
DateTimeRangeField, DateTimeRangeField,
DecimalRangeField, DecimalRangeField,
@ -47,9 +47,9 @@ except ImportError:
ArrayField = DummyArrayField ArrayField = DummyArrayField
BigIntegerRangeField = models.Field BigIntegerRangeField = models.Field
CICharField = models.Field CICharField = models.Field # RemovedInDjango51Warning.
CIEmailField = models.Field CIEmailField = models.Field # RemovedInDjango51Warning.
CITextField = models.Field CITextField = models.Field # RemovedInDjango51Warning.
DateRangeField = models.Field DateRangeField = models.Field
DateTimeRangeField = DummyContinuousRangeField DateTimeRangeField = DummyContinuousRangeField
DecimalRangeField = DummyContinuousRangeField DecimalRangeField = DummyContinuousRangeField

View File

@ -291,6 +291,7 @@ class Migration(migrations.Migration):
options=None, options=None,
bases=None, bases=None,
), ),
# RemovedInDjango51Warning.
migrations.CreateModel( migrations.CreateModel(
name="CITestModel", name="CITestModel",
fields=[ fields=[

View File

@ -119,6 +119,7 @@ class Character(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
# RemovedInDjango51Warning.
class CITestModel(PostgreSQLModel): class CITestModel(PostgreSQLModel):
name = CICharField(primary_key=True, max_length=255) name = CICharField(primary_key=True, max_length=255)
email = CIEmailField() email = CIEmailField()

View File

@ -1,3 +1,4 @@
# RemovedInDjango51Warning.
""" """
The citext PostgreSQL extension supports indexing of case-insensitive text The citext PostgreSQL extension supports indexing of case-insensitive text
strings and thus eliminates the need for operations such as iexact and other strings and thus eliminates the need for operations such as iexact and other
@ -5,6 +6,7 @@ modifiers to enforce use of an index.
""" """
from django.db import IntegrityError from django.db import IntegrityError
from django.test.utils import modify_settings from django.test.utils import modify_settings
from django.utils.deprecation import RemovedInDjango51Warning
from . import PostgreSQLTestCase from . import PostgreSQLTestCase
from .models import CITestModel from .models import CITestModel
@ -82,3 +84,10 @@ class CITextTestCase(PostgreSQLTestCase):
self.assertSequenceEqual( self.assertSequenceEqual(
CITestModel.objects.filter(**query), [self.john] CITestModel.objects.filter(**query), [self.john]
) )
def test_citext_deprecated(self):
from django.contrib.postgres.fields import CIText
msg = "django.contrib.postgres.fields.CIText mixin is deprecated."
with self.assertRaisesMessage(RemovedInDjango51Warning, msg):
CIText()

View File

@ -244,6 +244,13 @@ def setup_collect_tests(start_at, start_after, test_labels=None):
settings.LOGGING = log_config settings.LOGGING = log_config
settings.SILENCED_SYSTEM_CHECKS = [ settings.SILENCED_SYSTEM_CHECKS = [
"fields.W342", # ForeignKey(unique=True) -> OneToOneField "fields.W342", # ForeignKey(unique=True) -> OneToOneField
# django.contrib.postgres.fields.CICharField deprecated.
"fields.W905",
"postgres.W004",
# django.contrib.postgres.fields.CIEmailField deprecated.
"fields.W906",
# django.contrib.postgres.fields.CITextField deprecated.
"fields.W907",
] ]
# RemovedInDjango50Warning # RemovedInDjango50Warning