123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203 |
- import datetime
- import unittest
- from django.test import TransactionTestCase
- from django.db import connection, DatabaseError, IntegrityError, OperationalError
- from django.db.models.fields import (BinaryField, BooleanField, CharField, IntegerField,
- PositiveIntegerField, SlugField, TextField)
- from django.db.models.fields.related import ManyToManyField, ForeignKey
- from django.db.transaction import atomic
- from .models import (Author, AuthorWithDefaultHeight, AuthorWithM2M, Book, BookWithLongName,
- BookWithSlug, BookWithM2M, Tag, TagIndexed, TagM2MTest, TagUniqueRename,
- UniqueTest, Thing, TagThrough, BookWithM2MThrough, AuthorTag, AuthorWithM2MThrough,
- AuthorWithEvenLongerName, BookWeak, Note)
- class SchemaTests(TransactionTestCase):
- """
- Tests that the schema-alteration code works correctly.
- Be aware that these tests are more liable than most to false results,
- as sometimes the code to check if a test has worked is almost as complex
- as the code it is testing.
- """
- available_apps = []
- models = [
- Author, AuthorWithM2M, Book, BookWithLongName, BookWithSlug,
- BookWithM2M, Tag, TagIndexed, TagM2MTest, TagUniqueRename, UniqueTest,
- Thing, TagThrough, BookWithM2MThrough, AuthorWithEvenLongerName,
- BookWeak,
- ]
-
- def tearDown(self):
-
- self.delete_tables()
- def delete_tables(self):
- "Deletes all model tables for our models for a clean test environment"
- with connection.cursor() as cursor:
- connection.disable_constraint_checking()
- table_names = connection.introspection.table_names(cursor)
- for model in self.models:
-
- for field in model._meta.local_many_to_many:
- with atomic():
- tbl = field.rel.through._meta.db_table
- if tbl in table_names:
- cursor.execute(connection.schema_editor().sql_delete_table % {
- "table": connection.ops.quote_name(tbl),
- })
- table_names.remove(tbl)
-
- with atomic():
- tbl = model._meta.db_table
- if tbl in table_names:
- cursor.execute(connection.schema_editor().sql_delete_table % {
- "table": connection.ops.quote_name(tbl),
- })
- table_names.remove(tbl)
- connection.enable_constraint_checking()
- def column_classes(self, model):
- with connection.cursor() as cursor:
- columns = {
- d[0]: (connection.introspection.get_field_type(d[1], d), d)
- for d in connection.introspection.get_table_description(
- cursor,
- model._meta.db_table,
- )
- }
-
- for name, (type, desc) in columns.items():
- if isinstance(type, tuple):
- columns[name] = (type[0], desc)
-
- if not columns:
- raise DatabaseError("Table does not exist (empty pragma)")
- return columns
- def get_indexes(self, table):
- """
- Get the indexes on the table using a new cursor.
- """
- with connection.cursor() as cursor:
- return connection.introspection.get_indexes(cursor, table)
- def get_constraints(self, table):
- """
- Get the constraints on a table using a new cursor.
- """
- with connection.cursor() as cursor:
- return connection.introspection.get_constraints(cursor, table)
-
- def test_creation_deletion(self):
- """
- Tries creating a model's table, and then deleting it.
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
-
- list(Author.objects.all())
-
- with connection.schema_editor() as editor:
- editor.delete_model(Author)
-
- self.assertRaises(
- DatabaseError,
- lambda: list(Author.objects.all()),
- )
- @unittest.skipUnless(connection.features.supports_foreign_keys, "No FK support")
- def test_fk(self):
- "Tests that creating tables out of FK order, then repointing, works"
-
- with connection.schema_editor() as editor:
- editor.create_model(Book)
- editor.create_model(Author)
- editor.create_model(Tag)
-
- list(Author.objects.all())
- list(Book.objects.all())
-
- with self.assertRaises(IntegrityError):
- Book.objects.create(
- author_id=1,
- title="Much Ado About Foreign Keys",
- pub_date=datetime.datetime.now(),
- )
-
- new_field = ForeignKey(Tag)
- new_field.set_attributes_from_name("author")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Book,
- Book._meta.get_field("author"),
- new_field,
- strict=True,
- )
-
- constraints = self.get_constraints(Book._meta.db_table)
- for name, details in constraints.items():
- if details['columns'] == ["author_id"] and details['foreign_key']:
- self.assertEqual(details['foreign_key'], ('schema_tag', 'id'))
- break
- else:
- self.fail("No FK constraint for author_id found")
- @unittest.skipUnless(connection.features.supports_foreign_keys, "No FK support")
- def test_fk_db_constraint(self):
- "Tests that the db_constraint parameter is respected"
-
- with connection.schema_editor() as editor:
- editor.create_model(Tag)
- editor.create_model(Author)
- editor.create_model(BookWeak)
-
- list(Author.objects.all())
- list(Tag.objects.all())
- list(BookWeak.objects.all())
-
- constraints = self.get_constraints(BookWeak._meta.db_table)
- for name, details in constraints.items():
- if details['columns'] == ["author_id"] and details['foreign_key']:
- self.fail("FK constraint for author_id found")
-
- new_field = ForeignKey(Tag, db_constraint=False)
- new_field.set_attributes_from_name("tag")
- with connection.schema_editor() as editor:
- editor.add_field(
- Author,
- new_field,
- )
-
- constraints = self.get_constraints(Author._meta.db_table)
- for name, details in constraints.items():
- if details['columns'] == ["tag_id"] and details['foreign_key']:
- self.fail("FK constraint for tag_id found")
-
- new_field_2 = ForeignKey(Tag)
- new_field_2.set_attributes_from_name("tag")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Author,
- new_field,
- new_field_2,
- strict=True,
- )
-
- constraints = self.get_constraints(Author._meta.db_table)
- for name, details in constraints.items():
- if details['columns'] == ["tag_id"] and details['foreign_key']:
- self.assertEqual(details['foreign_key'], ('schema_tag', 'id'))
- break
- else:
- self.fail("No FK constraint for tag_id found")
-
- new_field_2 = ForeignKey(Tag)
- new_field_2.set_attributes_from_name("tag")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Author,
- new_field_2,
- new_field,
- strict=True,
- )
-
- constraints = self.get_constraints(Author._meta.db_table)
- for name, details in constraints.items():
- if details['columns'] == ["tag_id"] and details['foreign_key']:
- self.fail("FK constraint for tag_id found")
- @unittest.skipUnless(connection.features.supports_foreign_keys, "No FK support")
- def test_m2m_db_constraint(self):
-
- with connection.schema_editor() as editor:
- editor.create_model(Tag)
- editor.create_model(Author)
-
- list(Author.objects.all())
- list(Tag.objects.all())
-
- new_field = ManyToManyField("schema.Tag", related_name="authors", db_constraint=False)
- new_field.contribute_to_class(Author, "tags")
-
- with connection.schema_editor() as editor:
- editor.add_field(
- Author,
- new_field,
- )
-
- constraints = self.get_constraints(new_field.rel.through._meta.db_table)
- for name, details in constraints.items():
- if details['columns'] == ["tag_id"] and details['foreign_key']:
- self.fail("FK constraint for tag_id found")
- def test_add_field(self):
- """
- Tests adding fields to models
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
-
- columns = self.column_classes(Author)
- self.assertNotIn("age", columns)
-
- new_field = IntegerField(null=True)
- new_field.set_attributes_from_name("age")
- with connection.schema_editor() as editor:
- editor.add_field(
- Author,
- new_field,
- )
-
- columns = self.column_classes(Author)
- self.assertEqual(columns['age'][0], "IntegerField")
- self.assertEqual(columns['age'][1][6], True)
- def test_add_field_temp_default(self):
- """
- Tests adding fields to models with a temporary default
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
-
- columns = self.column_classes(Author)
- self.assertNotIn("age", columns)
-
- Author.objects.create(name="Andrew", height=30)
- Author.objects.create(name="Andrea")
-
- new_field = CharField(max_length=30, default="Godwin")
- new_field.set_attributes_from_name("surname")
- with connection.schema_editor() as editor:
- editor.add_field(
- Author,
- new_field,
- )
-
- columns = self.column_classes(Author)
- self.assertEqual(columns['surname'][0], "CharField")
- self.assertEqual(columns['surname'][1][6],
- connection.features.interprets_empty_strings_as_nulls)
- def test_add_field_temp_default_boolean(self):
- """
- Tests adding fields to models with a temporary default where
- the default is False. (#21783)
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
-
- columns = self.column_classes(Author)
- self.assertNotIn("age", columns)
-
- Author.objects.create(name="Andrew", height=30)
- Author.objects.create(name="Andrea")
-
- new_field = BooleanField(default=False)
- new_field.set_attributes_from_name("awesome")
- with connection.schema_editor() as editor:
- editor.add_field(
- Author,
- new_field,
- )
-
- columns = self.column_classes(Author)
-
- field_type = columns['awesome'][0]
- self.assertEqual(field_type, connection.features.introspected_boolean_field_type(new_field, created_separately=True))
- def test_add_field_default_transform(self):
- """
- Tests adding fields to models with a default that is not directly
- valid in the database (#22581)
- """
- class TestTransformField(IntegerField):
-
- def get_default(self):
- return self.default
- def get_prep_value(self, value):
- if value is None:
- return 0
- return len(value)
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
-
- Author.objects.create(name="Andrew", height=30)
- Author.objects.create(name="Andrea")
-
- new_field = TestTransformField(default={1: 2})
- new_field.set_attributes_from_name("thing")
- with connection.schema_editor() as editor:
- editor.add_field(
- Author,
- new_field,
- )
-
- columns = self.column_classes(Author)
- field_type, field_info = columns['thing']
- self.assertEqual(field_type, 'IntegerField')
-
- self.assertEqual(Author.objects.extra(where=["thing = 1"]).count(), 2)
- def test_add_field_binary(self):
- """
- Tests binary fields get a sane default (#22851)
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
-
- new_field = BinaryField(blank=True)
- new_field.set_attributes_from_name("bits")
- with connection.schema_editor() as editor:
- editor.add_field(
- Author,
- new_field,
- )
-
- columns = self.column_classes(Author)
-
-
- self.assertIn(columns['bits'][0], ("BinaryField", "TextField"))
- def test_alter(self):
- """
- Tests simple altering of fields
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
-
- columns = self.column_classes(Author)
- self.assertEqual(columns['name'][0], "CharField")
- self.assertEqual(bool(columns['name'][1][6]), bool(connection.features.interprets_empty_strings_as_nulls))
-
- new_field = TextField(null=True)
- new_field.set_attributes_from_name("name")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Author,
- Author._meta.get_field("name"),
- new_field,
- strict=True,
- )
-
- columns = self.column_classes(Author)
- self.assertEqual(columns['name'][0], "TextField")
- self.assertEqual(columns['name'][1][6], True)
-
- new_field2 = TextField(null=False)
- new_field2.set_attributes_from_name("name")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Author,
- new_field,
- new_field2,
- strict=True,
- )
-
- columns = self.column_classes(Author)
- self.assertEqual(columns['name'][0], "TextField")
- self.assertEqual(bool(columns['name'][1][6]), False)
- def test_alter_text_field(self):
-
-
- new_field = TextField(blank=True)
- new_field.set_attributes_from_name("info")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Note,
- Note._meta.get_field("info"),
- new_field,
- strict=True,
- )
- def test_alter_null_to_not_null(self):
- """
- #23609 - Tests handling of default values when altering from NULL to NOT NULL.
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
-
- columns = self.column_classes(Author)
- self.assertTrue(columns['height'][1][6])
-
- Author.objects.create(name='Not null author', height=12)
- Author.objects.create(name='Null author')
-
- self.assertEqual(Author.objects.get(name='Not null author').height, 12)
- self.assertIsNone(Author.objects.get(name='Null author').height)
-
- new_field = PositiveIntegerField(default=42)
- new_field.set_attributes_from_name("height")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Author,
- Author._meta.get_field("height"),
- new_field
- )
-
- columns = self.column_classes(Author)
- self.assertFalse(columns['height'][1][6])
-
- self.assertEqual(Author.objects.get(name='Not null author').height, 12)
- self.assertEqual(Author.objects.get(name='Null author').height, 42)
- @unittest.skipUnless(connection.features.supports_combined_alters, "No combined ALTER support")
- def test_alter_null_to_not_null_keeping_default(self):
- """
- #23738 - Can change a nullable field with default to non-nullable
- with the same default.
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(AuthorWithDefaultHeight)
-
- columns = self.column_classes(AuthorWithDefaultHeight)
- self.assertTrue(columns['height'][1][6])
-
- new_field = PositiveIntegerField(default=42)
- new_field.set_attributes_from_name("height")
- with connection.schema_editor() as editor:
- editor.alter_field(
- AuthorWithDefaultHeight,
- AuthorWithDefaultHeight._meta.get_field("height"),
- new_field,
- )
-
- columns = self.column_classes(AuthorWithDefaultHeight)
- self.assertFalse(columns['height'][1][6])
- @unittest.skipUnless(connection.features.supports_foreign_keys, "No FK support")
- def test_alter_fk(self):
- """
- Tests altering of FKs
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
- editor.create_model(Book)
-
- columns = self.column_classes(Book)
- self.assertEqual(columns['author_id'][0], "IntegerField")
-
- constraints = self.get_constraints(Book._meta.db_table)
- for name, details in constraints.items():
- if details['columns'] == ["author_id"] and details['foreign_key']:
- self.assertEqual(details['foreign_key'], ('schema_author', 'id'))
- break
- else:
- self.fail("No FK constraint for author_id found")
-
- new_field = ForeignKey(Author, editable=False)
- new_field.set_attributes_from_name("author")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Book,
- Book._meta.get_field("author"),
- new_field,
- strict=True,
- )
-
- columns = self.column_classes(Book)
- self.assertEqual(columns['author_id'][0], "IntegerField")
-
- constraints = self.get_constraints(Book._meta.db_table)
- for name, details in constraints.items():
- if details['columns'] == ["author_id"] and details['foreign_key']:
- self.assertEqual(details['foreign_key'], ('schema_author', 'id'))
- break
- else:
- self.fail("No FK constraint for author_id found")
- 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,
- )
-
-
- Author.objects.create(name='Foo')
- def test_rename(self):
- """
- Tests simple altering of fields
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
-
- columns = self.column_classes(Author)
- self.assertEqual(columns['name'][0], "CharField")
- self.assertNotIn("display_name", columns)
-
- new_field = CharField(max_length=254)
- new_field.set_attributes_from_name("display_name")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Author,
- Author._meta.get_field("name"),
- new_field,
- strict=True,
- )
-
- columns = self.column_classes(Author)
- self.assertEqual(columns['display_name'][0], "CharField")
- self.assertNotIn("name", columns)
- def test_m2m_create(self):
- """
- Tests M2M fields on models during creation
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
- editor.create_model(TagM2MTest)
- editor.create_model(BookWithM2M)
-
- columns = self.column_classes(BookWithM2M._meta.get_field("tags").rel.through)
- self.assertEqual(columns['tagm2mtest_id'][0], "IntegerField")
- def test_m2m_create_through(self):
- """
- Tests M2M fields on models during creation with through models
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(TagThrough)
- editor.create_model(TagM2MTest)
- editor.create_model(BookWithM2MThrough)
-
- columns = self.column_classes(TagThrough)
- self.assertEqual(columns['book_id'][0], "IntegerField")
- self.assertEqual(columns['tag_id'][0], "IntegerField")
- def test_m2m(self):
- """
- Tests adding/removing M2M fields on models
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(AuthorWithM2M)
- editor.create_model(TagM2MTest)
-
- new_field = ManyToManyField("schema.TagM2MTest", related_name="authors")
- new_field.contribute_to_class(AuthorWithM2M, "tags")
- try:
-
- self.assertRaises(DatabaseError, self.column_classes, new_field.rel.through)
-
- with connection.schema_editor() as editor:
- editor.add_field(
- Author,
- new_field,
- )
-
- columns = self.column_classes(new_field.rel.through)
- self.assertEqual(columns['tagm2mtest_id'][0], "IntegerField")
-
- with connection.schema_editor() as editor:
- editor.alter_field(
- Author,
- new_field,
- new_field,
- )
-
- with connection.schema_editor() as editor:
- editor.remove_field(
- Author,
- new_field,
- )
-
- self.assertRaises(DatabaseError, self.column_classes, new_field.rel.through)
- finally:
-
- AuthorWithM2M._meta.local_many_to_many.remove(new_field)
- def test_m2m_through_alter(self):
- """
- Tests altering M2Ms with explicit through models (should no-op)
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(AuthorTag)
- editor.create_model(AuthorWithM2MThrough)
- editor.create_model(TagM2MTest)
-
- self.assertEqual(len(self.column_classes(AuthorTag)), 3)
-
- with connection.schema_editor() as editor:
- old_field = AuthorWithM2MThrough._meta.get_field("tags")
- new_field = ManyToManyField("schema.TagM2MTest", related_name="authors", through="AuthorTag")
- new_field.contribute_to_class(AuthorWithM2MThrough, "tags")
- editor.alter_field(
- Author,
- old_field,
- new_field,
- )
-
- self.assertEqual(len(self.column_classes(AuthorTag)), 3)
- def test_m2m_repoint(self):
- """
- Tests repointing M2M fields
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
- editor.create_model(BookWithM2M)
- editor.create_model(TagM2MTest)
- editor.create_model(UniqueTest)
-
- constraints = self.get_constraints(BookWithM2M._meta.get_field("tags").rel.through._meta.db_table)
- if connection.features.supports_foreign_keys:
- for name, details in constraints.items():
- if details['columns'] == ["tagm2mtest_id"] and details['foreign_key']:
- self.assertEqual(details['foreign_key'], ('schema_tagm2mtest', 'id'))
- break
- else:
- self.fail("No FK constraint for tagm2mtest_id found")
-
- new_field = ManyToManyField(UniqueTest)
- new_field.contribute_to_class(BookWithM2M, "uniques")
- try:
- with connection.schema_editor() as editor:
- editor.alter_field(
- Author,
- BookWithM2M._meta.get_field("tags"),
- new_field,
- )
-
- self.assertRaises(DatabaseError, self.column_classes, BookWithM2M._meta.get_field("tags").rel.through)
-
- constraints = self.get_constraints(new_field.rel.through._meta.db_table)
- if connection.features.supports_foreign_keys:
- for name, details in constraints.items():
- if details['columns'] == ["uniquetest_id"] and details['foreign_key']:
- self.assertEqual(details['foreign_key'], ('schema_uniquetest', 'id'))
- break
- else:
- self.fail("No FK constraint for uniquetest_id found")
- finally:
-
- with connection.schema_editor() as editor:
- editor.remove_field(BookWithM2M, BookWithM2M._meta.get_field("uniques"))
-
- BookWithM2M._meta.local_many_to_many.remove(new_field)
- BookWithM2M._meta._expire_cache()
- @unittest.skipUnless(connection.features.supports_column_check_constraints, "No check constraints")
- def test_check_constraints(self):
- """
- Tests creating/deleting CHECK constraints
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
-
- constraints = self.get_constraints(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")
-
- 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("height"),
- new_field,
- strict=True,
- )
- constraints = self.get_constraints(Author._meta.db_table)
- for name, details in constraints.items():
- if details['columns'] == ["height"] and details['check']:
- self.fail("Check constraint for height found")
-
- with connection.schema_editor() as editor:
- editor.alter_field(
- Author,
- new_field,
- Author._meta.get_field("height"),
- strict=True,
- )
- constraints = self.get_constraints(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")
- def test_unique(self):
- """
- Tests removing and adding unique constraints to a single column.
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Tag)
-
- Tag.objects.create(title="foo", slug="foo")
- self.assertRaises(IntegrityError, Tag.objects.create, title="bar", slug="foo")
- Tag.objects.all().delete()
-
- new_field = SlugField(unique=False)
- new_field.set_attributes_from_name("slug")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Tag,
- Tag._meta.get_field("slug"),
- new_field,
- strict=True,
- )
-
- Tag.objects.create(title="foo", slug="foo")
- Tag.objects.create(title="bar", slug="foo")
- Tag.objects.all().delete()
-
- new_new_field = SlugField(unique=True)
- new_new_field.set_attributes_from_name("slug")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Tag,
- new_field,
- new_new_field,
- strict=True,
- )
-
- Tag.objects.create(title="foo", slug="foo")
- self.assertRaises(IntegrityError, Tag.objects.create, title="bar", slug="foo")
- Tag.objects.all().delete()
-
- new_field = SlugField(unique=False)
- new_field.set_attributes_from_name("slug2")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Tag,
- Tag._meta.get_field("slug"),
- TagUniqueRename._meta.get_field("slug2"),
- strict=True,
- )
-
- TagUniqueRename.objects.create(title="foo", slug2="foo")
- self.assertRaises(IntegrityError, TagUniqueRename.objects.create, title="bar", slug2="foo")
- Tag.objects.all().delete()
- def test_unique_together(self):
- """
- Tests removing and adding unique_together constraints on a model.
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(UniqueTest)
-
- UniqueTest.objects.create(year=2012, slug="foo")
- UniqueTest.objects.create(year=2011, slug="foo")
- UniqueTest.objects.create(year=2011, slug="bar")
- self.assertRaises(IntegrityError, UniqueTest.objects.create, year=2012, slug="foo")
- UniqueTest.objects.all().delete()
-
- with connection.schema_editor() as editor:
- editor.alter_unique_together(
- UniqueTest,
- UniqueTest._meta.unique_together,
- [],
- )
-
- UniqueTest.objects.create(year=2012, slug="foo")
- UniqueTest.objects.create(year=2012, slug="foo")
- UniqueTest.objects.all().delete()
-
- new_new_field = SlugField(unique=True)
- new_new_field.set_attributes_from_name("slug")
- with connection.schema_editor() as editor:
- editor.alter_unique_together(
- UniqueTest,
- [],
- UniqueTest._meta.unique_together,
- )
-
- UniqueTest.objects.create(year=2012, slug="foo")
- self.assertRaises(IntegrityError, UniqueTest.objects.create, year=2012, slug="foo")
- UniqueTest.objects.all().delete()
- def test_index_together(self):
- """
- Tests removing and adding index_together constraints on a model.
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Tag)
-
- self.assertEqual(
- False,
- any(
- c["index"]
- for c in self.get_constraints("schema_tag").values()
- if c['columns'] == ["slug", "title"]
- ),
- )
-
- with connection.schema_editor() as editor:
- editor.alter_index_together(
- Tag,
- [],
- [("slug", "title")],
- )
-
- self.assertEqual(
- True,
- any(
- c["index"]
- for c in self.get_constraints("schema_tag").values()
- if c['columns'] == ["slug", "title"]
- ),
- )
-
- new_new_field = SlugField(unique=True)
- new_new_field.set_attributes_from_name("slug")
- with connection.schema_editor() as editor:
- editor.alter_index_together(
- Tag,
- [("slug", "title")],
- [],
- )
-
- self.assertEqual(
- False,
- any(
- c["index"]
- for c in self.get_constraints("schema_tag").values()
- if c['columns'] == ["slug", "title"]
- ),
- )
- def test_create_index_together(self):
- """
- Tests creating models with index_together already defined
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(TagIndexed)
-
- self.assertEqual(
- True,
- any(
- c["index"]
- for c in self.get_constraints("schema_tagindexed").values()
- if c['columns'] == ["slug", "title"]
- ),
- )
- def test_db_table(self):
- """
- Tests renaming of the table
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
-
- columns = self.column_classes(Author)
- self.assertEqual(columns['name'][0], "CharField")
-
- with connection.schema_editor() as editor:
- editor.alter_db_table(
- Author,
- "schema_author",
- "schema_otherauthor",
- )
-
- Author._meta.db_table = "schema_otherauthor"
- columns = self.column_classes(Author)
- self.assertEqual(columns['name'][0], "CharField")
-
- with connection.schema_editor() as editor:
- editor.alter_db_table(
- Author,
- "schema_otherauthor",
- "schema_author",
- )
-
- Author._meta.db_table = "schema_author"
- columns = self.column_classes(Author)
- self.assertEqual(columns['name'][0], "CharField")
- def test_indexes(self):
- """
- Tests creation/altering of indexes
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
- editor.create_model(Book)
-
- self.assertIn(
- "title",
- self.get_indexes(Book._meta.db_table),
- )
-
- new_field = CharField(max_length=100, db_index=False)
- new_field.set_attributes_from_name("title")
- with connection.schema_editor() as editor:
- editor.alter_field(
- Book,
- Book._meta.get_field("title"),
- new_field,
- strict=True,
- )
-
- self.assertNotIn(
- "title",
- self.get_indexes(Book._meta.db_table),
- )
-
- with connection.schema_editor() as editor:
- editor.alter_field(
- Book,
- new_field,
- Book._meta.get_field("title"),
- strict=True,
- )
-
- self.assertIn(
- "title",
- self.get_indexes(Book._meta.db_table),
- )
-
- with connection.schema_editor() as editor:
- editor.add_field(
- Book,
- BookWithSlug._meta.get_field("slug"),
- )
- self.assertIn(
- "slug",
- self.get_indexes(Book._meta.db_table),
- )
-
- new_field2 = CharField(max_length=20, unique=False)
- new_field2.set_attributes_from_name("slug")
- with connection.schema_editor() as editor:
- editor.alter_field(
- BookWithSlug,
- BookWithSlug._meta.get_field("slug"),
- new_field2,
- strict=True,
- )
- self.assertNotIn(
- "slug",
- self.get_indexes(Book._meta.db_table),
- )
- def test_primary_key(self):
- """
- Tests altering of the primary key
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Tag)
-
- self.assertTrue(
- self.get_indexes(Tag._meta.db_table)['id']['primary_key'],
- )
-
- new_field = SlugField(primary_key=True)
- new_field.set_attributes_from_name("slug")
- new_field.model = Tag
- with connection.schema_editor() as editor:
- editor.remove_field(Tag, Tag._meta.get_field("id"))
- editor.alter_field(
- Tag,
- Tag._meta.get_field("slug"),
- new_field,
- )
-
- self.assertNotIn(
- 'id',
- self.get_indexes(Tag._meta.db_table),
- )
- self.assertTrue(
- self.get_indexes(Tag._meta.db_table)['slug']['primary_key'],
- )
- def test_context_manager_exit(self):
- """
- Ensures transaction is correctly closed when an error occurs
- inside a SchemaEditor context.
- """
- class SomeError(Exception):
- pass
- try:
- with connection.schema_editor():
- raise SomeError
- except SomeError:
- self.assertFalse(connection.in_atomic_block)
- @unittest.skipUnless(connection.features.supports_foreign_keys, "No FK support")
- def test_foreign_key_index_long_names_regression(self):
- """
- Regression test for #21497.
- Only affects databases that supports foreign keys.
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(AuthorWithEvenLongerName)
- editor.create_model(BookWithLongName)
-
- column_name = connection.ops.quote_name("author_foreign_key_with_really_long_field_name_id")
- column_name = column_name[1:-1].lower()
-
- self.assertIn(
- column_name,
- self.get_indexes(BookWithLongName._meta.db_table),
- )
- @unittest.skipUnless(connection.features.supports_foreign_keys, "No FK support")
- def test_add_foreign_key_long_names(self):
- """
- Regression test for #23009.
- Only affects databases that supports foreign keys.
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(AuthorWithEvenLongerName)
- editor.create_model(BookWithLongName)
-
- new_field = ForeignKey(AuthorWithEvenLongerName, related_name="something")
- new_field.set_attributes_from_name("author_other_really_long_named_i_mean_so_long_fk")
- with connection.schema_editor() as editor:
- editor.add_field(
- BookWithLongName,
- new_field,
- )
- def test_creation_deletion_reserved_names(self):
- """
- Tries creating a model's table, and then deleting it when it has a
- SQL reserved name.
- """
-
- with connection.schema_editor() as editor:
- try:
- editor.create_model(Thing)
- except OperationalError as e:
- self.fail("Errors when applying initial migration for a model "
- "with a table named after a SQL reserved word: %s" % e)
-
- list(Thing.objects.all())
-
- with connection.schema_editor() as editor:
- editor.delete_model(Thing)
-
- self.assertRaises(
- DatabaseError,
- lambda: list(Thing.objects.all()),
- )
- @unittest.skipUnless(connection.features.supports_foreign_keys, "No FK support")
- def test_remove_constraints_capital_letters(self):
- """
- #23065 - Constraint names must be quoted if they contain capital letters.
- """
- def get_field(*args, **kwargs):
- kwargs['db_column'] = "CamelCase"
- field = kwargs.pop('field_class', IntegerField)(*args, **kwargs)
- field.set_attributes_from_name("CamelCase")
- return field
- model = Author
- field = get_field()
- table = model._meta.db_table
- column = field.column
- with connection.schema_editor() as editor:
- editor.create_model(model)
- editor.add_field(model, field)
- editor.execute(
- editor.sql_create_index % {
- "table": editor.quote_name(table),
- "name": editor.quote_name("CamelCaseIndex"),
- "columns": editor.quote_name(column),
- "extra": "",
- }
- )
- editor.alter_field(model, get_field(db_index=True), field)
- editor.execute(
- editor.sql_create_unique % {
- "table": editor.quote_name(table),
- "name": editor.quote_name("CamelCaseUniqConstraint"),
- "columns": editor.quote_name(field.column),
- }
- )
- editor.alter_field(model, get_field(unique=True), field)
- editor.execute(
- editor.sql_create_fk % {
- "table": editor.quote_name(table),
- "name": editor.quote_name("CamelCaseFKConstraint"),
- "column": editor.quote_name(column),
- "to_table": editor.quote_name(table),
- "to_column": editor.quote_name(model._meta.auto_field.column),
- }
- )
- editor.alter_field(model, get_field(Author, field_class=ForeignKey), field)
- def test_add_field_use_effective_default(self):
- """
- #23987 - effective_default() should be used as the field default when
- adding a new field.
- """
-
- with connection.schema_editor() as editor:
- editor.create_model(Author)
-
- columns = self.column_classes(Author)
- self.assertNotIn("surname", columns)
-
- Author.objects.create(name='Anonymous1')
-
- new_field = CharField(max_length=15, blank=True)
- new_field.set_attributes_from_name("surname")
- with connection.schema_editor() as editor:
- editor.add_field(Author, new_field)
-
- with connection.cursor() as cursor:
- cursor.execute("SELECT surname FROM schema_author;")
- item = cursor.fetchall()[0]
- self.assertEqual(item[0], None if connection.features.interprets_empty_strings_as_nulls else '')
|