Skip to content

Commit

Permalink
Fixed #22626 -- Allow BinaryField defaults with SQlite.
Browse files Browse the repository at this point in the history
Also fixes a slight issue in sqlite3.schema._remake_table where
default values where quoted with "column name" quoting rules.

Reference for quoting: http://www.sqlite.org/lang_expr.html

Thanks Shai Berger for the review. Refs #22424.
  • Loading branch information
rbarrois authored and loic committed May 17, 2014
1 parent 268670a commit 6aacb4c
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions django/db/backends/sqlite3/schema.py
@@ -1,3 +1,5 @@
import codecs

from decimal import Decimal
from django.utils import six
from django.apps.registry import Apps
Expand Down Expand Up @@ -28,6 +30,16 @@ def quote_value(self, value):
return '"%s"' % six.text_type(value)
elif value is None:
return "NULL"
elif isinstance(value, (bytes, bytearray, six.memoryview)):
# Bytes are only allowed for BLOB fields, encoded as string
# literals containing hexadecimal data and preceded by a single "X"
# character:
# value = b'\x01\x02' => value_hex = b'0102' => return X'0102'
value = bytes(value)
hex_encoder = codecs.getencoder('hex_codec')
value_hex, _length = hex_encoder(value)
# Use 'ascii' encoding for b'01' => '01', no need to use force_text here.
return "X'%s'" % value_hex.decode('ascii')
else:
raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value)))

Expand All @@ -37,7 +49,9 @@ def _remake_table(self, model, create_fields=[], delete_fields=[], alter_fields=
"""
# Work out the new fields dict / mapping
body = dict((f.name, f) for f in model._meta.local_fields)
mapping = dict((f.column, f.column) for f in model._meta.local_fields)
# Since mapping might mix column names and default values,
# its values must be already quoted.
mapping = dict((f.column, self.quote_name(f.column)) for f in model._meta.local_fields)
# If any of the new or altered fields is introducing a new PK,
# remove the old one
restore_pk_field = None
Expand All @@ -62,7 +76,7 @@ def _remake_table(self, model, create_fields=[], delete_fields=[], alter_fields=
del body[old_field.name]
del mapping[old_field.column]
body[new_field.name] = new_field
mapping[new_field.column] = old_field.column
mapping[new_field.column] = self.quote_name(old_field.column)
# Remove any deleted fields
for field in delete_fields:
del body[field.name]
Expand Down Expand Up @@ -90,7 +104,7 @@ def _remake_table(self, model, create_fields=[], delete_fields=[], alter_fields=
self.execute("INSERT INTO %s (%s) SELECT %s FROM %s" % (
self.quote_name(temp_model._meta.db_table),
', '.join(self.quote_name(x) for x, y in field_maps),
', '.join(self.quote_name(y) for x, y in field_maps),
', '.join(y for x, y in field_maps),
self.quote_name(model._meta.db_table),
))
# Delete the old table (not using self.delete_model to avoid deleting
Expand Down

0 comments on commit 6aacb4c

Please sign in to comment.