Opened 8 months ago

Closed 8 months ago

Last modified 8 months ago

#34956 closed Cleanup/optimization (wontfix)

Migration should not be allowed for a non-deterministic GeneratedField

Reported by: Sarah Boyce Owned by: nobody
Component: Database layer (models, ORM) Version: 5.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hello hello
I didn't fully understand the GeneratedField and thought I would be able to do something with comparisons against Now (which I now know I cannot do).

from django.db import models
from django.db.models import Case, When, Value, Q
from django.db.models.functions import Now


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField("date published")
    closed_date = models.DateTimeField("date closed", null=True)
    status = models.GeneratedField(
        expression=Case(
            When(pub_date__lt=Now(), then=Value("unpublished")),
            When(Q(closed_date__isnull=False, closed_date__gt=Now()), then=Value("closed")),
            default=Value("active"),
        ),
        db_persist=False,
        output_field=models.TextField(),
    )

Django allowed me to make migrations and migrate here (I'm using SQLite) but then when I tried to create a Question object it got very angry.
The traceback is very long but the main thing is:

OperationalError: non-deterministic use of strftime() in a generated column

I learnt my lesson and won't do it again! But I'm wondering if we can bring this error earlier and prevent the user from being able to makemigrations/migrate? I can provide more details if needed

Change History (2)

comment:1 by Mariusz Felisiak, 8 months ago

Component: UncategorizedDatabase layer (models, ORM)
Resolution: wontfix
Status: newclosed
Type: UncategorizedCleanup/optimization

There are many functions that cannot be used of various databases, e.g. Random, SHA512, SHA384, SHA224, SHA1, MD5 cannot be used on Oracle. As far as I'm, is not feasible for us to curate the list of functions supported for each of database. This is also documented in Database limitations.

comment:2 by Simon Charette, 8 months ago

I know the exact same problem was discussed for indexes in the past (I just can't find where). An idea that as brought up was to flag expressions on whether they are deterministic or not but as Mariusz pointed out it's a lot of work to get right.

Note: See TracTickets for help on using tickets.
Back to Top