Opened 7 years ago
Closed 7 years ago
#28371 closed Bug (fixed)
Cast generates invalid SQL for SQLite, PostgreSQL, and Oracle if max_length isn't provide to CharField
Reported by: | James Doherty | Owned by: | Mariusz Felisiak |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Mariusz Felisiak | Triage Stage: | Accepted |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
I have a nullable IntegerField. When trying to cast it to a char, SQLite and PostgreSQL error due to invalid SQL:
class Numbers(models.Model): number = models.IntegerField(null=True)
The following code causes the error.
Numbers.objects.annotate(as_string=Cast('number', CharField()))
PostgreSQL
ProgrammingError: syntax error at or near "None" LINE 1: ...mbers"."number", "demo_numbers"."number"::varchar(None) AS "... SELECT "demo_numbers"."id", "demo_numbers"."number", "demo_numbers"."number"::varchar(None) AS "as_string" FROM "demo_numbers"
Removing the '(None)' from the SQL makes this work.
SQLite
OperationalError: near "None": syntax error SELECT "demo_numbers"."id", "demo_numbers"."number", CAST("demo_numbers"."number" AS varchar(None)) AS "as_string" FROM "demo_numbers"
According to the SQLite documentation, varchar is not a valid type for SQLite: http://www.sqlite.org/lang_expr.html#castexpr
Changing the SQL to 'CAST("demo_numbers"."number" AS TEXT)' succeeds. It's worth noting that it is possible to give SQLite an invalid cast type that doesn't cause an error (eg, try 'CAST("demo_numbers"."number" AS BOGUS)' )
Change History (8)
comment:1 by , 7 years ago
Cc: | added |
---|---|
Version: | 1.11 → master |
comment:2 by , 7 years ago
comment:3 by , 7 years ago
Summary: | Cast generating invalid SQL for SQLite and PostgreSQL → Cast generates invalid SQL for SQLite and PostgreSQL if max_length isn't provide to CharField |
---|---|
Triage Stage: | Unreviewed → Accepted |
For Cast
, I'm not sure if max_length
matters. If not too complicated, I think it wouldn't be unreasonable to allow this to work -- or at least a more helpful error message should be provided.
comment:4 by , 7 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
comment:5 by , 7 years ago
Summary: | Cast generates invalid SQL for SQLite and PostgreSQL if max_length isn't provide to CharField → Cast generates invalid SQL for SQLite, PostgreSQL, and Oracle if max_length isn't provide to CharField |
---|
I confirm that if you use
Cast
withCharField()
withoutmax_length
argument then SQL is invalid. On the other hand I'm not convinced that it's a bug becausemax_length
is required forCharField
's.