Opened 7 years ago

Closed 7 years ago

Last modified 19 months ago

#28329 closed Bug (fixed)

Cast() does not work with PositiveIntegerField on MySQL.

Reported by: Paolo D'Apice Owned by: Mariusz Felisiak
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

Hi,

I found that the wrong SQL is generated for MySQL 5.7 when using django.db.models.functions.Cast.

Suppose I have a model:

class Model(models.Model):
    id = models.AutoField()
    string = models.CharField()

This works correctly, cast a string to integer:

print Model.objects.annotate(as_int=functions.Cast('string', models.IntegerField())).query
SELECT `Model`.`id`, `Model`.`string`, CAST(`Model`.`string`) AS signed integer) AS `as_int` FROM `Model`

But if cast to unsigned integer (which is what I need):

print Model.objects.annotate(as_int=functions.Cast('string', models.PositiveIntegerField())).query
SELECT `Model`.`id`, `Model`.`string`, CAST(`Model`.`string`) AS integer UNSIGNED) AS `as_int` FROM `Model`

Here is the error:

Model.objects.annotate(as_int=functions.Cast('string', models.PositiveIntegerField()))
ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'integer UNSIGNED) AS `id_int` FROM `Model` at line 1")

So it seems that casting to IntegerField uses the correct MySQL type signed integer but casting to PositiveInteger uses the wrong type integer unsigned (it should be unsigned integer, see the MySQL documentation at https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html#function_cast).

Change History (5)

comment:1 by Mariusz Felisiak, 7 years ago

Summary: Wrong type conversion with MySQL 5.7Cast() does not work with PositiveIntegerField on MySQL.
Triage Stage: UnreviewedAccepted
Version: 1.10master

comment:2 by Mariusz Felisiak, 7 years ago

Easy pickings: set

comment:3 by Mariusz Felisiak, 7 years ago

Has patch: set
Owner: changed from nobody to Mariusz Felisiak
Status: newassigned

comment:4 by Tim Graham <timograham@…>, 7 years ago

Resolution: fixed
Status: assignedclosed

In 0f91ba1a:

Fixed #28329 -- Fixed Cast() with Big/Small/Positive/PositiveSmallIntegerField on MySQL.

comment:5 by Mariusz Felisiak <felisiak.mariusz@…>, 19 months ago

In de0c774:

Refs #28329 -- Fixed Cast() with ForeignKey to integer fields on MySQL.

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