[Django] #33802: Using a Q object to match an empty string in CheckConstraint results in invalid SQL using MySQL

23 views
Skip to first unread message

Django

unread,
Jun 23, 2022, 10:46:52 AM6/23/22
to django-...@googlegroups.com
#33802: Using a Q object to match an empty string in CheckConstraint results in
invalid SQL using MySQL
-----------------------------------------+------------------------
Reporter: Phil Gyford | Owner: nobody
Type: Uncategorized | Status: new
Component: Migrations | Version: 4.0
Severity: Normal | Keywords:
Triage Stage: Unreviewed | Has patch: 0
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-----------------------------------------+------------------------
Using a constraint like that below results in a migration that generates
invalid SQL when using a MariaDB (v10.3) database. I think it's OK using
SQLite, but I haven't tried Postgresql.

{{{
from django.db import models
from django.db.models import Q

class Person(models.Model):
firstname = models.CharField(max_length=50, blank=True, null=False,
default="")

class Meta:
constraints = [
models.CheckConstraint(
name="%(app_label)s_%(class)s_firstname",
check=(Q(firstname__exact="")),
)
]
}}}

Running `manage.py makemigrations` results in a migration with this
operation:

{{{
constraint=models.CheckConstraint(
check=models.Q(("firstname__exact", "")),
name="myapp_person_firstname",
),
}}}

And running `manage.py sqlmigrate myapp 0002` shows this (note there
should be a pair of empty quotes between `=` and `)` at the end):

{{{
ALTER TABLE `Person` ADD CONSTRAINT `myapp_person_firstname` CHECK
(`firstname` = );
}}}

Unsurprisingly, running the migration results in:

{{{
django.db.utils.ProgrammingError: (1064, "1064 (42000): You have an error
in your SQL syntax; check the manual that corresponds to your MariaDB
server version for the right syntax to use near ')' at line 1", '42000')
}}}

--
Ticket URL: <https://code.djangoproject.com/ticket/33802>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

Reply all
Reply to author
Forward
0 new messages