Opened 3 hours ago

Last modified 18 minutes ago

#35839 new Bug

GeneratedField with db_comment causes syntax error

Reported by: Jason Christa Owned by:
Component: Migrations Version: 5.0
Severity: Normal Keywords:
Cc: Jason Christa, Mariusz Felisiak Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Adding a new GeneratedField with the db_comment argument cause invalid SQL to be generated for MySQL (maybe others but that is all I tested). Altering a GeneratedField with a db_comment seems to work fine.

Change History (3)

comment:1 by Simon Charette, 2 hours ago

Component: Database layer (models, ORM)Migrations
Triage Stage: UnreviewedAccepted

Reproduced with the following test

  • tests/schema/tests.py

    diff --git a/tests/schema/tests.py b/tests/schema/tests.py
    index 33a4bc527b..1dbbd5fe02 100644
    a b def test_add_db_comment_charfield(self):  
    48614861            comment,
    48624862        )
    48634863
     4864    @skipUnlessDBFeature("supports_comments")
     4865    def test_add_db_comment_generated_field(self):
     4866        comment = "Custom comment"
     4867        field = GeneratedField(
     4868            expression=Value(1),
     4869            db_persist=True,
     4870            output_field=IntegerField(),
     4871            db_comment=comment,
     4872        )
     4873        field.set_attributes_from_name("volume")
     4874        with connection.schema_editor() as editor:
     4875            editor.create_model(Author)
     4876            editor.add_field(Author, field)
     4877        self.assertEqual(
     4878            self.get_column_comment(Author._meta.db_table, "volume"),
     4879            comment,
     4880        )
     4881
    48644882    @skipUnlessDBFeature("supports_comments")
    48654883    def test_add_db_comment_and_default_charfield(self):
    48664884        comment = "Custom comment with default"

It appears that the problem is due to the order the the COMMENT and GENERATED clause in the generated SQL.

MySQL expects COMMENT to come after GENERATED while we do the opposite

ALTER TABLE `schema_author` ADD COLUMN `volume` integer COMMENT 'Custom comment' GENERATED ALWAYS AS (1) STORED

Crashes while

ALTER TABLE `schema_author` ADD COLUMN `volume` integer GENERATED ALWAYS AS (1) STORED COMMENT 'Custom comment' 

passes.

comment:2 by Simon Charette, 2 hours ago

Jason, If you're interested in submitting a patch it seems that the solution lies in changing the order of the generated SQL in _iter_column_sql.

comment:3 by Mariusz Felisiak, 18 minutes ago

Cc: Mariusz Felisiak added
Note: See TracTickets for help on using tickets.
Back to Top