diff --git a/pony/orm/migrations/dbschema.py b/pony/orm/migrations/dbschema.py index 0a4ad7f4..5b8b28cd 100644 --- a/pony/orm/migrations/dbschema.py +++ b/pony/orm/migrations/dbschema.py @@ -226,6 +226,7 @@ def exists(self, provider, connection, case_sensitive=True): @classmethod def from_attr(cls, table, attr): + from pony.orm.ormtypes import Json schema = table.schema if not attr.converters: attr.converters = [schema.provider.get_converter_by_attr(attr)] @@ -241,8 +242,11 @@ def from_attr(cls, table, attr): col.nullable = attr.nullable or len(attr.entity.bases) != 0 col.auto = attr.auto col.sql_default = attr.sql_default - if not attr.is_required and isinstance(attr.py_type, type) and issubclass(attr.py_type, basestring): - col.sql_default = '' + if not attr.is_required and isinstance(attr.py_type, type): + if issubclass(attr.py_type, basestring): + col.sql_default = '' + elif issubclass(attr.py_type, Json): + col.sql_default = '{}' col.initial = attr.initial or attr.provided.initial col.sql_type = attr.sql_type or converter.get_sql_type() provided_cols = attr.provided.kwargs.get('columns', None) diff --git a/pony/orm/migrations/tests/test_schema_ops.py b/pony/orm/migrations/tests/test_schema_ops.py index 70d32989..66749fd6 100644 --- a/pony/orm/migrations/tests/test_schema_ops.py +++ b/pony/orm/migrations/tests/test_schema_ops.py @@ -1312,6 +1312,50 @@ class NewStudent(Student): self.assertEqual(len(migration.operations), 1) # ChangeDiscriminator self.assertEqual(expected_schema, actual_schema) + def test_add_optional_json(self): + self.db2 = db2 = Database(**self.db_params) + + class Department(db2.Entity): + number = PrimaryKey(int, auto=True) + name = Required(str, unique=True) + groups = Set("Group") + courses = Set("Course") + + class Group(db2.Entity): + number = PrimaryKey(int) + major = Required(str, index=True) + dept = Required("Department", fk_name='dept_fk') + students = Set("Student") + + class Course(db2.Entity): + name = Required(str, unique=True) + semester = Required(int) + lect_hours = Required(int, check='lect_hours > 0') + lab_hours = Required(int) + credits = Required(int, index=True) + dept = Required(Department) + students = Set("Student") + PrimaryKey(name, semester) + composite_index(lect_hours, lab_hours) + + class Student(db2.Entity): + name = Required(str) + dob = Required(date) + tel = Optional(str) + picture = Optional(buffer, lazy=True) + gpa = Required(float, default=0) + group = Required(Group) + courses = Set(Course) + composite_key(name, dob) + complex_info = Optional(Json) + + class NewStudent(Student): + avatar = Required(str) + + expected_schema, actual_schema, migration = self.apply_migrate() + self.assertEqual(len(migration.operations), 1) # ChangeDiscriminator + self.assertEqual(expected_schema, actual_schema) + class TestPostgresMigrations(AbstractTestMigrations): db_params = dict(provider='postgres', user='pony', password='pony', host='localhost', database='pony')