Skip to content

Commit 1e9926c

Browse files
committed
django: fix Cast to CharField with max_length
fixes #258
1 parent 1262ef6 commit 1e9926c

2 files changed

Lines changed: 13 additions & 4 deletions

File tree

packages/django-google-spanner/spanner/django/features.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,9 +196,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):
196196
# null: https://github.com/orijtech/spanner-orm/issues/242
197197
'db_functions.text.test_concat.ConcatTests.test_basic',
198198
'db_functions.text.test_concat.ConcatTests.test_many',
199-
# Cast to CharField with max_length doesn't work:
200-
# https://github.com/orijtech/spanner-orm/issues/258
201-
'db_functions.comparison.test_cast.CastTests.test_cast_to_char_field_with_max_length',
202199
# casting DateField to DateTimeField adds an unexpected hour:
203200
# https://github.com/orijtech/spanner-orm/issues/260
204201
'db_functions.comparison.test_cast.CastTests.test_cast_from_db_date_to_datetime',

packages/django-google-spanner/spanner/django/functions.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,21 @@
77
import math
88

99
from django.db.models.functions import (
10-
Chr, Cot, Degrees, Left, Log, Ord, Pi, Radians, Right, StrIndex, Substr,
10+
Cast, Chr, Cot, Degrees, Left, Log, Ord, Pi, Radians, Right, StrIndex,
11+
Substr,
1112
)
1213

1314

15+
def cast(self, compiler, connection, **extra_context):
16+
# Account for a field's max_length using SUBSTR.
17+
max_length = getattr(self.output_field, 'max_length', None)
18+
if max_length is not None:
19+
template = 'SUBSTR(' + self.template + ', 0, %s)' % max_length
20+
else:
21+
template = self.template
22+
return self.as_sql(compiler, connection, template=template, **extra_context)
23+
24+
1425
def chr_(self, compiler, connection, **extra_context):
1526
return self.as_sql(compiler, connection, template='CODE_POINTS_TO_STRING([%(expressions)s])', **extra_context)
1627

@@ -64,6 +75,7 @@ def substr(self, compiler, connection, **extra_context):
6475

6576

6677
def register_functions():
78+
Cast.as_spanner = cast
6779
Chr.as_spanner = chr_
6880
Cot.as_spanner = cot
6981
Degrees.as_spanner = degrees

0 commit comments

Comments
 (0)