Пример #1
0
    def test_remove_field(self):
        """
        Tests remove fields from models
        """
        with DatabaseSchemaEditor(self.connection) as schema_editor:
            schema_editor.execute = mock.MagicMock()
            schema_editor._constraint_names = mock.MagicMock()
            remove_field = IntegerField(unique=True)
            remove_field.set_attributes_from_name("num")
            schema_editor.remove_field(Author, remove_field)

            schema_editor.execute.assert_called_once_with(
                "ALTER TABLE tests_author DROP COLUMN num"
            )

        if HAS_OPENTELEMETRY_INSTALLED:
            span_list = self.ot_exporter.get_finished_spans()
            self.assertEqual(len(span_list), 1)
            self.assertSpanAttributes(
                "CloudSpannerDjango.remove_field",
                attributes=dict(
                    BASE_ATTRIBUTES,
                    model_name="tests_author",
                    field="num",
                ),
                span=span_list[0],
            )
Пример #2
0
 def test_check_constraints(self):
     """
     Tests creating/deleting CHECK constraints
     """
     # Create the tables
     with connection.schema_editor() as editor:
         editor.create_model(Author)
     # Ensure the constraint exists
     constraints = connection.introspection.get_constraints(connection.cursor(), Author._meta.db_table)
     for name, details in constraints.items():
         if details["columns"] == ["height"] and details["check"]:
             break
     else:
         self.fail("No check constraint for height found")
     # Alter the column to remove it
     new_field = IntegerField(null=True, blank=True)
     new_field.set_attributes_from_name("height")
     with connection.schema_editor() as editor:
         editor.alter_field(Author, Author._meta.get_field_by_name("height")[0], new_field, strict=True)
     constraints = connection.introspection.get_constraints(connection.cursor(), Author._meta.db_table)
     for name, details in constraints.items():
         if details["columns"] == ["height"] and details["check"]:
             self.fail("Check constraint for height found")
     # Alter the column to re-add it
     with connection.schema_editor() as editor:
         editor.alter_field(Author, new_field, Author._meta.get_field_by_name("height")[0], strict=True)
     constraints = connection.introspection.get_constraints(connection.cursor(), Author._meta.db_table)
     for name, details in constraints.items():
         if details["columns"] == ["height"] and details["check"]:
             break
     else:
         self.fail("No check constraint for height found")
Пример #3
0
 def test_column_sql_nullable_field(self):
     """
     Tests column sql for nullable field
     """
     with DatabaseSchemaEditor(self.connection) as schema_editor:
         schema_editor.execute = mock.MagicMock()
         new_field = IntegerField(null=True)
         new_field.set_attributes_from_name("num")
         sql, params = schema_editor.column_sql(Author, new_field)
         self.assertEqual(sql, "INT64")
Пример #4
0
    def test_add_field(self):
        """
        Tests adding fields to models
        """
        with DatabaseSchemaEditor(self.connection) as schema_editor:
            schema_editor.execute = mock.MagicMock()
            new_field = IntegerField(null=True)
            new_field.set_attributes_from_name("age")
            schema_editor.add_field(Author, new_field)

            schema_editor.execute.assert_called_once_with(
                "ALTER TABLE tests_author ADD COLUMN age INT64", [])
Пример #5
0
    def test_alter_field(self):
        """
        Tests altering existing field in table
        """
        with DatabaseSchemaEditor(self.connection) as schema_editor:
            schema_editor.execute = mock.MagicMock()
            old_field = IntegerField()
            old_field.set_attributes_from_name("num")
            new_field = IntegerField()
            new_field.set_attributes_from_name("author_num")
            schema_editor.alter_field(Author, old_field, new_field)

            schema_editor.execute.assert_called_once_with(
                "ALTER TABLE tests_author RENAME COLUMN num TO author_num")
Пример #6
0
    def test_remove_field_with_index(self):
        """
        Tests remove fields from models
        """
        with DatabaseSchemaEditor(self.connection) as schema_editor:
            schema_editor.execute = mock.MagicMock()

            def delete_index_sql(*args, **kwargs):
                # Overriding Statement creation with sql string.
                return "DROP INDEX num_unique"

            def constraint_names(*args, **kwargs):
                return ["num_unique"]

            schema_editor._delete_index_sql = delete_index_sql
            schema_editor._constraint_names = constraint_names

            remove_field = IntegerField(unique=True)
            remove_field.set_attributes_from_name("num")
            schema_editor.remove_field(Author, remove_field)

            calls = [
                mock.call("DROP INDEX num_unique"),
                mock.call("ALTER TABLE tests_author DROP COLUMN num"),
            ]
            schema_editor.execute.assert_has_calls(calls)

        if HAS_OPENTELEMETRY_INSTALLED:
            span_list = self.ot_exporter.get_finished_spans()
            self.assertEqual(len(span_list), 2)
            self.assertSpanAttributes(
                "CloudSpannerDjango.remove_field.delete_index",
                attributes=dict(
                    BASE_ATTRIBUTES,
                    model_name="tests_author",
                    field="num",
                    index_name="num_unique",
                ),
                span=span_list[0],
            )
            self.assertSpanAttributes(
                "CloudSpannerDjango.remove_field",
                attributes=dict(
                    BASE_ATTRIBUTES,
                    model_name="tests_author",
                    field="num",
                ),
                span=span_list[1],
            )
Пример #7
0
    def test_alter_field_change_null_with_multiple_index_error(self):
        """
        Tests altering nullability of field with multiple index not supported
        """
        with DatabaseSchemaEditor(self.connection) as schema_editor:
            schema_editor.execute = mock.MagicMock()

            def constraint_names(*args, **kwargs):
                return ["num_unique", "dummy_index"]

            schema_editor._constraint_names = constraint_names
            old_field = IntegerField(null=True, db_index=True)
            old_field.set_attributes_from_name("num")
            new_field = IntegerField()
            new_field.set_attributes_from_name("author_num")
            with self.assertRaises(NotSupportedError):
                schema_editor.alter_field(Author, old_field, new_field)
Пример #8
0
    def test_alter_field_nullability_change_raise_not_support_error(self):
        """
        Tests altering nullability of existing field in table
        """
        with DatabaseSchemaEditor(self.connection) as schema_editor:
            schema_editor.execute = mock.MagicMock()

            def constraint_names(*args, **kwargs):
                return ["num_unique"]

            schema_editor._constraint_names = constraint_names
            old_field = IntegerField(null=True)
            old_field.set_attributes_from_name("num")
            new_field = IntegerField()
            new_field.set_attributes_from_name("author_num")
            with self.assertRaises(NotSupportedError):
                schema_editor.alter_field(Author, old_field, new_field)
Пример #9
0
 def test_check_constraints(self):
     """
     Tests creating/deleting CHECK constraints
     """
     # Create the tables
     with connection.schema_editor() as editor:
         editor.create_model(Author)
     # Ensure the constraint exists
     constraints = connection.introspection.get_constraints(
         connection.cursor(), Author._meta.db_table)
     for name, details in constraints.items():
         if details['columns'] == ["height"] and details['check']:
             break
     else:
         self.fail("No check constraint for height found")
     # Alter the column to remove it
     new_field = IntegerField(null=True, blank=True)
     new_field.set_attributes_from_name("height")
     with connection.schema_editor() as editor:
         editor.alter_field(
             Author,
             Author._meta.get_field_by_name("height")[0],
             new_field,
             strict=True,
         )
     constraints = connection.introspection.get_constraints(
         connection.cursor(), Author._meta.db_table)
     for name, details in constraints.items():
         if details['columns'] == ["height"] and details['check']:
             self.fail("Check constraint for height found")
     # Alter the column to re-add it
     with connection.schema_editor() as editor:
         editor.alter_field(
             Author,
             new_field,
             Author._meta.get_field_by_name("height")[0],
             strict=True,
         )
     constraints = connection.introspection.get_constraints(
         connection.cursor(), Author._meta.db_table)
     for name, details in constraints.items():
         if details['columns'] == ["height"] and details['check']:
             break
     else:
         self.fail("No check constraint for height found")
Пример #10
0
    def test_alter_implicit_id_to_explicit(self):
        """
        Should be able to convert an implicit "id" field to an explicit "id"
        primary key field.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Author)

        new_field = IntegerField(primary_key=True)
        new_field.set_attributes_from_name("id")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(
                Author,
                Author._meta.get_field_by_name("id")[0],
                new_field,
                strict=True,
            )
Пример #11
0
    def test_alter_implicit_id_to_explicit(self):
        """
        Should be able to convert an implicit "id" field to an explicit "id"
        primary key field.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Author)

        new_field = IntegerField(primary_key=True)
        new_field.set_attributes_from_name("id")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(
                Author,
                Author._meta.get_field_by_name("id")[0],
                new_field,
                strict=True,
            )
Пример #12
0
 def test_add_field(self):
     """
     Tests adding fields to models
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Author)
     # Ensure there's no age field
     columns = self.column_classes(Author)
     self.assertNotIn("age", columns)
     # Add the new field
     new_field = IntegerField(null=True)
     new_field.set_attributes_from_name("age")
     with connection.schema_editor() as editor:
         editor.add_field(Author, new_field)
     # Ensure the field is right afterwards
     columns = self.column_classes(Author)
     self.assertEqual(columns["age"][0], "IntegerField")
     self.assertEqual(columns["age"][1][6], True)
Пример #13
0
 def test_add_field(self):
     """
     Tests adding fields to models
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Author)
     # Ensure there's no age field
     columns = self.column_classes(Author)
     self.assertNotIn("age", columns)
     # Alter the name field to a TextField
     new_field = IntegerField(null=True)
     new_field.set_attributes_from_name("age")
     with connection.schema_editor() as editor:
         editor.add_field(
             Author,
             new_field,
         )
     # Ensure the field is right afterwards
     columns = self.column_classes(Author)
     self.assertEqual(columns['age'][0], "IntegerField")
     self.assertEqual(columns['age'][1][6], True)
Пример #14
0
    def test_alter_implicit_id_to_explicit(self):
        """
        Should be able to convert an implicit "id" field to an explicit "id"
        primary key field.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Author)

        new_field = IntegerField(primary_key=True)
        new_field.set_attributes_from_name("id")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(
                Author,
                Author._meta.get_field_by_name("id")[0],
                new_field,
                strict=True,
            )

        # This will fail if DROP DEFAULT is inadvertently executed on this
        # field which drops the id sequence, at least on PostgreSQL.
        Author.objects.create(name='Foo')
Пример #15
0
    def test_alter_implicit_id_to_explicit(self):
        """
        Should be able to convert an implicit "id" field to an explicit "id"
        primary key field.
        """
        with connection.schema_editor() as editor:
            editor.create_model(Author)

        new_field = IntegerField(primary_key=True)
        new_field.set_attributes_from_name("id")
        new_field.model = Author
        with connection.schema_editor() as editor:
            editor.alter_field(
                Author,
                Author._meta.get_field("id"),
                new_field,
                strict=True,
            )

        # This will fail if DROP DEFAULT is inadvertently executed on this
        # field which drops the id sequence, at least on PostgreSQL.
        Author.objects.create(name='Foo')
Пример #16
0
    def test_alter_field_change_null_with_single_index(self):
        """
        Tests altering nullability of field with single index
        """
        with DatabaseSchemaEditor(self.connection) as schema_editor:
            schema_editor.execute = mock.MagicMock()

            def delete_index_sql(*args, **kwargs):
                # Overriding Statement creation with sql string.
                return "DROP INDEX num_unique"

            def create_index_sql(*args, **kwargs):
                # Overriding Statement creation with sql string.
                return "CREATE INDEX tests_author ON tests_author (author_num)"

            def constraint_names(*args, **kwargs):
                return ["num_unique"]

            schema_editor._delete_index_sql = delete_index_sql
            schema_editor._create_index_sql = create_index_sql
            schema_editor._constraint_names = constraint_names
            old_field = IntegerField(null=True, db_index=True)
            old_field.set_attributes_from_name("num")
            new_field = IntegerField(db_index=True)
            new_field.set_attributes_from_name("author_num")
            schema_editor.alter_field(Author, old_field, new_field)

            calls = [
                mock.call("DROP INDEX num_unique"),
                mock.call(
                    "ALTER TABLE tests_author RENAME COLUMN num TO author_num"
                ),
                mock.call(
                    "ALTER TABLE tests_author ALTER COLUMN author_num INT64 NOT NULL",
                    [],
                ),
                mock.call(
                    "CREATE INDEX tests_author ON tests_author (author_num)"
                ),
            ]
            schema_editor.execute.assert_has_calls(calls)
        if HAS_OPENTELEMETRY_INSTALLED:
            span_list = self.ot_exporter.get_finished_spans()
            self.assertEqual(len(span_list), 3)
            self.assertSpanAttributes(
                "CloudSpannerDjango.alter_field.delete_index",
                attributes=dict(
                    BASE_ATTRIBUTES,
                    model_name="tests_author",
                    index_name="num_unique",
                    alter_field="num",
                ),
                span=span_list[0],
            )
            self.assertSpanAttributes(
                "CloudSpannerDjango.alter_field",
                attributes=dict(
                    BASE_ATTRIBUTES,
                    model_name="tests_author",
                    alter_field="num",
                ),
                span=span_list[1],
            )
            self.assertSpanAttributes(
                "CloudSpannerDjango.alter_field.recreate_index",
                attributes=dict(
                    BASE_ATTRIBUTES,
                    model_name="tests_author",
                    alter_field="author_num",
                ),
                span=span_list[2],
            )