tests.py 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  1. import datetime
  2. import itertools
  3. import unittest
  4. from copy import copy
  5. from django.db import (
  6. DatabaseError, IntegrityError, OperationalError, connection,
  7. )
  8. from django.db.models import Model
  9. from django.db.models.deletion import CASCADE
  10. from django.db.models.fields import (
  11. AutoField, BigIntegerField, BinaryField, BooleanField, CharField,
  12. DateField, DateTimeField, IntegerField, PositiveIntegerField, SlugField,
  13. TextField, TimeField,
  14. )
  15. from django.db.models.fields.related import (
  16. ForeignKey, ForeignObject, ManyToManyField, OneToOneField,
  17. )
  18. from django.db.transaction import atomic
  19. from django.test import (
  20. TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature,
  21. )
  22. from .fields import (
  23. CustomManyToManyField, InheritedManyToManyField, MediumBlobField,
  24. )
  25. from .models import (
  26. Author, AuthorWithDefaultHeight, AuthorWithEvenLongerName, Book,
  27. BookForeignObj, BookWeak, BookWithLongName, BookWithO2O, BookWithoutAuthor,
  28. BookWithSlug, IntegerPK, Node, Note, NoteRename, Tag, TagIndexed,
  29. TagM2MTest, TagUniqueRename, Thing, UniqueTest, new_apps,
  30. )
  31. class SchemaTests(TransactionTestCase):
  32. """
  33. Tests that the schema-alteration code works correctly.
  34. Be aware that these tests are more liable than most to false results,
  35. as sometimes the code to check if a test has worked is almost as complex
  36. as the code it is testing.
  37. """
  38. available_apps = []
  39. models = [
  40. Author, AuthorWithDefaultHeight, AuthorWithEvenLongerName, Book,
  41. BookWeak, BookWithLongName, BookWithO2O, BookWithSlug, IntegerPK, Note,
  42. Tag, TagIndexed, TagM2MTest, TagUniqueRename, Thing, UniqueTest,
  43. ]
  44. # Utility functions
  45. def setUp(self):
  46. # local_models should contain test dependent model classes that will be
  47. # automatically removed from the app cache on test tear down.
  48. self.local_models = []
  49. def tearDown(self):
  50. # Delete any tables made for our models
  51. self.delete_tables()
  52. new_apps.clear_cache()
  53. for model in new_apps.get_models():
  54. model._meta._expire_cache()
  55. if 'schema' in new_apps.all_models:
  56. for model in self.local_models:
  57. for many_to_many in model._meta.many_to_many:
  58. through = many_to_many.remote_field.through
  59. if through and through._meta.auto_created:
  60. del new_apps.all_models['schema'][through._meta.model_name]
  61. del new_apps.all_models['schema'][model._meta.model_name]
  62. def delete_tables(self):
  63. "Deletes all model tables for our models for a clean test environment"
  64. converter = connection.introspection.table_name_converter
  65. with atomic():
  66. connection.disable_constraint_checking()
  67. table_names = connection.introspection.table_names()
  68. for model in itertools.chain(SchemaTests.models, self.local_models):
  69. tbl = converter(model._meta.db_table)
  70. if tbl in table_names:
  71. with connection.schema_editor() as editor:
  72. editor.delete_model(model)
  73. table_names.remove(tbl)
  74. connection.enable_constraint_checking()
  75. def column_classes(self, model):
  76. with connection.cursor() as cursor:
  77. columns = {
  78. d[0]: (connection.introspection.get_field_type(d[1], d), d)
  79. for d in connection.introspection.get_table_description(
  80. cursor,
  81. model._meta.db_table,
  82. )
  83. }
  84. # SQLite has a different format for field_type
  85. for name, (type, desc) in columns.items():
  86. if isinstance(type, tuple):
  87. columns[name] = (type[0], desc)
  88. # SQLite also doesn't error properly
  89. if not columns:
  90. raise DatabaseError("Table does not exist (empty pragma)")
  91. return columns
  92. def get_indexes(self, table):
  93. """
  94. Get the indexes on the table using a new cursor.
  95. """
  96. with connection.cursor() as cursor:
  97. return connection.introspection.get_indexes(cursor, table)
  98. def get_constraints(self, table):
  99. """
  100. Get the constraints on a table using a new cursor.
  101. """
  102. with connection.cursor() as cursor:
  103. return connection.introspection.get_constraints(cursor, table)
  104. def get_constraints_for_column(self, model, column_name):
  105. constraints = self.get_constraints(model._meta.db_table)
  106. constraints_for_column = []
  107. for name, details in constraints.items():
  108. if details['columns'] == [column_name]:
  109. constraints_for_column.append(name)
  110. return sorted(constraints_for_column)
  111. # Tests
  112. def test_creation_deletion(self):
  113. """
  114. Tries creating a model's table, and then deleting it.
  115. """
  116. # Create the table
  117. with connection.schema_editor() as editor:
  118. editor.create_model(Author)
  119. # Check that it's there
  120. list(Author.objects.all())
  121. # Clean up that table
  122. with connection.schema_editor() as editor:
  123. editor.delete_model(Author)
  124. # Check that it's gone
  125. with self.assertRaises(DatabaseError):
  126. list(Author.objects.all())
  127. @skipUnlessDBFeature('supports_foreign_keys')
  128. def test_fk(self):
  129. "Tests that creating tables out of FK order, then repointing, works"
  130. # Create the table
  131. with connection.schema_editor() as editor:
  132. editor.create_model(Book)
  133. editor.create_model(Author)
  134. editor.create_model(Tag)
  135. # Check that initial tables are there
  136. list(Author.objects.all())
  137. list(Book.objects.all())
  138. # Make sure the FK constraint is present
  139. with self.assertRaises(IntegrityError):
  140. Book.objects.create(
  141. author_id=1,
  142. title="Much Ado About Foreign Keys",
  143. pub_date=datetime.datetime.now(),
  144. )
  145. # Repoint the FK constraint
  146. old_field = Book._meta.get_field("author")
  147. new_field = ForeignKey(Tag, CASCADE)
  148. new_field.set_attributes_from_name("author")
  149. with connection.schema_editor() as editor:
  150. editor.alter_field(Book, old_field, new_field, strict=True)
  151. # Make sure the new FK constraint is present
  152. constraints = self.get_constraints(Book._meta.db_table)
  153. for name, details in constraints.items():
  154. if details['columns'] == ["author_id"] and details['foreign_key']:
  155. self.assertEqual(details['foreign_key'], ('schema_tag', 'id'))
  156. break
  157. else:
  158. self.fail("No FK constraint for author_id found")
  159. @skipUnlessDBFeature('supports_foreign_keys')
  160. def test_fk_to_proxy(self):
  161. "Tests that creating a FK to a proxy model creates database constraints."
  162. class AuthorProxy(Author):
  163. class Meta:
  164. app_label = 'schema'
  165. apps = new_apps
  166. proxy = True
  167. class AuthorRef(Model):
  168. author = ForeignKey(AuthorProxy, on_delete=CASCADE)
  169. class Meta:
  170. app_label = 'schema'
  171. apps = new_apps
  172. self.local_models = [AuthorProxy, AuthorRef]
  173. # Create the table
  174. with connection.schema_editor() as editor:
  175. editor.create_model(Author)
  176. editor.create_model(AuthorRef)
  177. constraints = self.get_constraints(AuthorRef._meta.db_table)
  178. for details in constraints.values():
  179. if details['columns'] == ['author_id'] and details['foreign_key']:
  180. self.assertEqual(details['foreign_key'], ('schema_author', 'id'))
  181. break
  182. else:
  183. self.fail('No FK constraint for author_id found')
  184. @skipUnlessDBFeature('supports_foreign_keys')
  185. def test_fk_db_constraint(self):
  186. "Tests that the db_constraint parameter is respected"
  187. # Create the table
  188. with connection.schema_editor() as editor:
  189. editor.create_model(Tag)
  190. editor.create_model(Author)
  191. editor.create_model(BookWeak)
  192. # Check that initial tables are there
  193. list(Author.objects.all())
  194. list(Tag.objects.all())
  195. list(BookWeak.objects.all())
  196. # Check that BookWeak doesn't have an FK constraint
  197. constraints = self.get_constraints(BookWeak._meta.db_table)
  198. for name, details in constraints.items():
  199. if details['columns'] == ["author_id"] and details['foreign_key']:
  200. self.fail("FK constraint for author_id found")
  201. # Make a db_constraint=False FK
  202. new_field = ForeignKey(Tag, CASCADE, db_constraint=False)
  203. new_field.set_attributes_from_name("tag")
  204. with connection.schema_editor() as editor:
  205. editor.add_field(Author, new_field)
  206. # Make sure no FK constraint is present
  207. constraints = self.get_constraints(Author._meta.db_table)
  208. for name, details in constraints.items():
  209. if details['columns'] == ["tag_id"] and details['foreign_key']:
  210. self.fail("FK constraint for tag_id found")
  211. # Alter to one with a constraint
  212. new_field2 = ForeignKey(Tag, CASCADE)
  213. new_field2.set_attributes_from_name("tag")
  214. with connection.schema_editor() as editor:
  215. editor.alter_field(Author, new_field, new_field2, strict=True)
  216. # Make sure the new FK constraint is present
  217. constraints = self.get_constraints(Author._meta.db_table)
  218. for name, details in constraints.items():
  219. if details['columns'] == ["tag_id"] and details['foreign_key']:
  220. self.assertEqual(details['foreign_key'], ('schema_tag', 'id'))
  221. break
  222. else:
  223. self.fail("No FK constraint for tag_id found")
  224. # Alter to one without a constraint again
  225. new_field2 = ForeignKey(Tag, CASCADE)
  226. new_field2.set_attributes_from_name("tag")
  227. with connection.schema_editor() as editor:
  228. editor.alter_field(Author, new_field2, new_field, strict=True)
  229. # Make sure no FK constraint is present
  230. constraints = self.get_constraints(Author._meta.db_table)
  231. for name, details in constraints.items():
  232. if details['columns'] == ["tag_id"] and details['foreign_key']:
  233. self.fail("FK constraint for tag_id found")
  234. def _test_m2m_db_constraint(self, M2MFieldClass):
  235. class LocalAuthorWithM2M(Model):
  236. name = CharField(max_length=255)
  237. class Meta:
  238. app_label = 'schema'
  239. apps = new_apps
  240. self.local_models = [LocalAuthorWithM2M]
  241. # Create the table
  242. with connection.schema_editor() as editor:
  243. editor.create_model(Tag)
  244. editor.create_model(LocalAuthorWithM2M)
  245. # Check that initial tables are there
  246. list(LocalAuthorWithM2M.objects.all())
  247. list(Tag.objects.all())
  248. # Make a db_constraint=False FK
  249. new_field = M2MFieldClass(Tag, related_name="authors", db_constraint=False)
  250. new_field.contribute_to_class(LocalAuthorWithM2M, "tags")
  251. # Add the field
  252. with connection.schema_editor() as editor:
  253. editor.add_field(LocalAuthorWithM2M, new_field)
  254. # Make sure no FK constraint is present
  255. constraints = self.get_constraints(new_field.remote_field.through._meta.db_table)
  256. for name, details in constraints.items():
  257. if details['columns'] == ["tag_id"] and details['foreign_key']:
  258. self.fail("FK constraint for tag_id found")
  259. @skipUnlessDBFeature('supports_foreign_keys')
  260. def test_m2m_db_constraint(self):
  261. self._test_m2m_db_constraint(ManyToManyField)
  262. @skipUnlessDBFeature('supports_foreign_keys')
  263. def test_m2m_db_constraint_custom(self):
  264. self._test_m2m_db_constraint(CustomManyToManyField)
  265. @skipUnlessDBFeature('supports_foreign_keys')
  266. def test_m2m_db_constraint_inherited(self):
  267. self._test_m2m_db_constraint(InheritedManyToManyField)
  268. def test_add_field(self):
  269. """
  270. Tests adding fields to models
  271. """
  272. # Create the table
  273. with connection.schema_editor() as editor:
  274. editor.create_model(Author)
  275. # Ensure there's no age field
  276. columns = self.column_classes(Author)
  277. self.assertNotIn("age", columns)
  278. # Add the new field
  279. new_field = IntegerField(null=True)
  280. new_field.set_attributes_from_name("age")
  281. with connection.schema_editor() as editor:
  282. editor.add_field(Author, new_field)
  283. # Ensure the field is right afterwards
  284. columns = self.column_classes(Author)
  285. self.assertEqual(columns['age'][0], "IntegerField")
  286. self.assertEqual(columns['age'][1][6], True)
  287. def test_add_field_temp_default(self):
  288. """
  289. Tests adding fields to models with a temporary default
  290. """
  291. # Create the table
  292. with connection.schema_editor() as editor:
  293. editor.create_model(Author)
  294. # Ensure there's no age field
  295. columns = self.column_classes(Author)
  296. self.assertNotIn("age", columns)
  297. # Add some rows of data
  298. Author.objects.create(name="Andrew", height=30)
  299. Author.objects.create(name="Andrea")
  300. # Add a not-null field
  301. new_field = CharField(max_length=30, default="Godwin")
  302. new_field.set_attributes_from_name("surname")
  303. with connection.schema_editor() as editor:
  304. editor.add_field(Author, new_field)
  305. # Ensure the field is right afterwards
  306. columns = self.column_classes(Author)
  307. self.assertEqual(columns['surname'][0], "CharField")
  308. self.assertEqual(columns['surname'][1][6],
  309. connection.features.interprets_empty_strings_as_nulls)
  310. def test_add_field_temp_default_boolean(self):
  311. """
  312. Tests adding fields to models with a temporary default where
  313. the default is False. (#21783)
  314. """
  315. # Create the table
  316. with connection.schema_editor() as editor:
  317. editor.create_model(Author)
  318. # Ensure there's no age field
  319. columns = self.column_classes(Author)
  320. self.assertNotIn("age", columns)
  321. # Add some rows of data
  322. Author.objects.create(name="Andrew", height=30)
  323. Author.objects.create(name="Andrea")
  324. # Add a not-null field
  325. new_field = BooleanField(default=False)
  326. new_field.set_attributes_from_name("awesome")
  327. with connection.schema_editor() as editor:
  328. editor.add_field(Author, new_field)
  329. # Ensure the field is right afterwards
  330. columns = self.column_classes(Author)
  331. # BooleanField are stored as TINYINT(1) on MySQL.
  332. field_type = columns['awesome'][0]
  333. self.assertEqual(
  334. field_type,
  335. connection.features.introspected_boolean_field_type(new_field, created_separately=True)
  336. )
  337. def test_add_field_default_transform(self):
  338. """
  339. Tests adding fields to models with a default that is not directly
  340. valid in the database (#22581)
  341. """
  342. class TestTransformField(IntegerField):
  343. # Weird field that saves the count of items in its value
  344. def get_default(self):
  345. return self.default
  346. def get_prep_value(self, value):
  347. if value is None:
  348. return 0
  349. return len(value)
  350. # Create the table
  351. with connection.schema_editor() as editor:
  352. editor.create_model(Author)
  353. # Add some rows of data
  354. Author.objects.create(name="Andrew", height=30)
  355. Author.objects.create(name="Andrea")
  356. # Add the field with a default it needs to cast (to string in this case)
  357. new_field = TestTransformField(default={1: 2})
  358. new_field.set_attributes_from_name("thing")
  359. with connection.schema_editor() as editor:
  360. editor.add_field(Author, new_field)
  361. # Ensure the field is there
  362. columns = self.column_classes(Author)
  363. field_type, field_info = columns['thing']
  364. self.assertEqual(field_type, 'IntegerField')
  365. # Make sure the values were transformed correctly
  366. self.assertEqual(Author.objects.extra(where=["thing = 1"]).count(), 2)
  367. def test_add_field_binary(self):
  368. """
  369. Tests binary fields get a sane default (#22851)
  370. """
  371. # Create the table
  372. with connection.schema_editor() as editor:
  373. editor.create_model(Author)
  374. # Add the new field
  375. new_field = BinaryField(blank=True)
  376. new_field.set_attributes_from_name("bits")
  377. with connection.schema_editor() as editor:
  378. editor.add_field(Author, new_field)
  379. # Ensure the field is right afterwards
  380. columns = self.column_classes(Author)
  381. # MySQL annoyingly uses the same backend, so it'll come back as one of
  382. # these two types.
  383. self.assertIn(columns['bits'][0], ("BinaryField", "TextField"))
  384. @unittest.skipUnless(connection.vendor == 'mysql', "MySQL specific")
  385. def test_add_binaryfield_mediumblob(self):
  386. """
  387. Test adding a custom-sized binary field on MySQL (#24846).
  388. """
  389. # Create the table
  390. with connection.schema_editor() as editor:
  391. editor.create_model(Author)
  392. # Add the new field with default
  393. new_field = MediumBlobField(blank=True, default=b'123')
  394. new_field.set_attributes_from_name('bits')
  395. with connection.schema_editor() as editor:
  396. editor.add_field(Author, new_field)
  397. columns = self.column_classes(Author)
  398. # Introspection treats BLOBs as TextFields
  399. self.assertEqual(columns['bits'][0], "TextField")
  400. def test_alter(self):
  401. """
  402. Tests simple altering of fields
  403. """
  404. # Create the table
  405. with connection.schema_editor() as editor:
  406. editor.create_model(Author)
  407. # Ensure the field is right to begin with
  408. columns = self.column_classes(Author)
  409. self.assertEqual(columns['name'][0], "CharField")
  410. self.assertEqual(bool(columns['name'][1][6]), bool(connection.features.interprets_empty_strings_as_nulls))
  411. # Alter the name field to a TextField
  412. old_field = Author._meta.get_field("name")
  413. new_field = TextField(null=True)
  414. new_field.set_attributes_from_name("name")
  415. with connection.schema_editor() as editor:
  416. editor.alter_field(Author, old_field, new_field, strict=True)
  417. # Ensure the field is right afterwards
  418. columns = self.column_classes(Author)
  419. self.assertEqual(columns['name'][0], "TextField")
  420. self.assertEqual(columns['name'][1][6], True)
  421. # Change nullability again
  422. new_field2 = TextField(null=False)
  423. new_field2.set_attributes_from_name("name")
  424. with connection.schema_editor() as editor:
  425. editor.alter_field(Author, new_field, new_field2, strict=True)
  426. # Ensure the field is right afterwards
  427. columns = self.column_classes(Author)
  428. self.assertEqual(columns['name'][0], "TextField")
  429. self.assertEqual(bool(columns['name'][1][6]), bool(connection.features.interprets_empty_strings_as_nulls))
  430. def test_alter_text_field(self):
  431. # Regression for "BLOB/TEXT column 'info' can't have a default value")
  432. # on MySQL.
  433. # Create the table
  434. with connection.schema_editor() as editor:
  435. editor.create_model(Note)
  436. old_field = Note._meta.get_field("info")
  437. new_field = TextField(blank=True)
  438. new_field.set_attributes_from_name("info")
  439. with connection.schema_editor() as editor:
  440. editor.alter_field(Note, old_field, new_field, strict=True)
  441. def test_alter_text_field_to_date_field(self):
  442. """
  443. #25002 - Test conversion of text field to date field.
  444. """
  445. with connection.schema_editor() as editor:
  446. editor.create_model(Note)
  447. Note.objects.create(info='1988-05-05')
  448. old_field = Note._meta.get_field('info')
  449. new_field = DateField(blank=True)
  450. new_field.set_attributes_from_name('info')
  451. with connection.schema_editor() as editor:
  452. editor.alter_field(Note, old_field, new_field, strict=True)
  453. # Make sure the field isn't nullable
  454. columns = self.column_classes(Note)
  455. self.assertFalse(columns['info'][1][6])
  456. def test_alter_text_field_to_datetime_field(self):
  457. """
  458. #25002 - Test conversion of text field to datetime field.
  459. """
  460. with connection.schema_editor() as editor:
  461. editor.create_model(Note)
  462. Note.objects.create(info='1988-05-05 3:16:17.4567')
  463. old_field = Note._meta.get_field('info')
  464. new_field = DateTimeField(blank=True)
  465. new_field.set_attributes_from_name('info')
  466. with connection.schema_editor() as editor:
  467. editor.alter_field(Note, old_field, new_field, strict=True)
  468. # Make sure the field isn't nullable
  469. columns = self.column_classes(Note)
  470. self.assertFalse(columns['info'][1][6])
  471. def test_alter_text_field_to_time_field(self):
  472. """
  473. #25002 - Test conversion of text field to time field.
  474. """
  475. with connection.schema_editor() as editor:
  476. editor.create_model(Note)
  477. Note.objects.create(info='3:16:17.4567')
  478. old_field = Note._meta.get_field('info')
  479. new_field = TimeField(blank=True)
  480. new_field.set_attributes_from_name('info')
  481. with connection.schema_editor() as editor:
  482. editor.alter_field(Note, old_field, new_field, strict=True)
  483. # Make sure the field isn't nullable
  484. columns = self.column_classes(Note)
  485. self.assertFalse(columns['info'][1][6])
  486. @skipIfDBFeature('interprets_empty_strings_as_nulls')
  487. def test_alter_textual_field_keep_null_status(self):
  488. """
  489. Changing a field type shouldn't affect the not null status.
  490. """
  491. with connection.schema_editor() as editor:
  492. editor.create_model(Note)
  493. with self.assertRaises(IntegrityError):
  494. Note.objects.create(info=None)
  495. old_field = Note._meta.get_field("info")
  496. new_field = CharField(max_length=50)
  497. new_field.set_attributes_from_name("info")
  498. with connection.schema_editor() as editor:
  499. editor.alter_field(Note, old_field, new_field, strict=True)
  500. with self.assertRaises(IntegrityError):
  501. Note.objects.create(info=None)
  502. def test_alter_numeric_field_keep_null_status(self):
  503. """
  504. Changing a field type shouldn't affect the not null status.
  505. """
  506. with connection.schema_editor() as editor:
  507. editor.create_model(UniqueTest)
  508. with self.assertRaises(IntegrityError):
  509. UniqueTest.objects.create(year=None, slug='aaa')
  510. old_field = UniqueTest._meta.get_field("year")
  511. new_field = BigIntegerField()
  512. new_field.set_attributes_from_name("year")
  513. with connection.schema_editor() as editor:
  514. editor.alter_field(UniqueTest, old_field, new_field, strict=True)
  515. with self.assertRaises(IntegrityError):
  516. UniqueTest.objects.create(year=None, slug='bbb')
  517. def test_alter_null_to_not_null(self):
  518. """
  519. #23609 - Tests handling of default values when altering from NULL to NOT NULL.
  520. """
  521. # Create the table
  522. with connection.schema_editor() as editor:
  523. editor.create_model(Author)
  524. # Ensure the field is right to begin with
  525. columns = self.column_classes(Author)
  526. self.assertTrue(columns['height'][1][6])
  527. # Create some test data
  528. Author.objects.create(name='Not null author', height=12)
  529. Author.objects.create(name='Null author')
  530. # Verify null value
  531. self.assertEqual(Author.objects.get(name='Not null author').height, 12)
  532. self.assertIsNone(Author.objects.get(name='Null author').height)
  533. # Alter the height field to NOT NULL with default
  534. old_field = Author._meta.get_field("height")
  535. new_field = PositiveIntegerField(default=42)
  536. new_field.set_attributes_from_name("height")
  537. with connection.schema_editor() as editor:
  538. editor.alter_field(Author, old_field, new_field)
  539. # Ensure the field is right afterwards
  540. columns = self.column_classes(Author)
  541. self.assertFalse(columns['height'][1][6])
  542. # Verify default value
  543. self.assertEqual(Author.objects.get(name='Not null author').height, 12)
  544. self.assertEqual(Author.objects.get(name='Null author').height, 42)
  545. def test_alter_charfield_to_null(self):
  546. """
  547. #24307 - Should skip an alter statement on databases with
  548. interprets_empty_strings_as_null when changing a CharField to null.
  549. """
  550. # Create the table
  551. with connection.schema_editor() as editor:
  552. editor.create_model(Author)
  553. # Change the CharField to null
  554. old_field = Author._meta.get_field('name')
  555. new_field = copy(old_field)
  556. new_field.null = True
  557. with connection.schema_editor() as editor:
  558. editor.alter_field(Author, old_field, new_field)
  559. def test_alter_textfield_to_null(self):
  560. """
  561. #24307 - Should skip an alter statement on databases with
  562. interprets_empty_strings_as_null when changing a TextField to null.
  563. """
  564. # Create the table
  565. with connection.schema_editor() as editor:
  566. editor.create_model(Note)
  567. # Change the TextField to null
  568. old_field = Note._meta.get_field('info')
  569. new_field = copy(old_field)
  570. new_field.null = True
  571. with connection.schema_editor() as editor:
  572. editor.alter_field(Note, old_field, new_field)
  573. @skipUnlessDBFeature('supports_combined_alters')
  574. def test_alter_null_to_not_null_keeping_default(self):
  575. """
  576. #23738 - Can change a nullable field with default to non-nullable
  577. with the same default.
  578. """
  579. # Create the table
  580. with connection.schema_editor() as editor:
  581. editor.create_model(AuthorWithDefaultHeight)
  582. # Ensure the field is right to begin with
  583. columns = self.column_classes(AuthorWithDefaultHeight)
  584. self.assertTrue(columns['height'][1][6])
  585. # Alter the height field to NOT NULL keeping the previous default
  586. old_field = AuthorWithDefaultHeight._meta.get_field("height")
  587. new_field = PositiveIntegerField(default=42)
  588. new_field.set_attributes_from_name("height")
  589. with connection.schema_editor() as editor:
  590. editor.alter_field(AuthorWithDefaultHeight, old_field, new_field)
  591. # Ensure the field is right afterwards
  592. columns = self.column_classes(AuthorWithDefaultHeight)
  593. self.assertFalse(columns['height'][1][6])
  594. @skipUnlessDBFeature('supports_foreign_keys')
  595. def test_alter_fk(self):
  596. """
  597. Tests altering of FKs
  598. """
  599. # Create the table
  600. with connection.schema_editor() as editor:
  601. editor.create_model(Author)
  602. editor.create_model(Book)
  603. # Ensure the field is right to begin with
  604. columns = self.column_classes(Book)
  605. self.assertEqual(columns['author_id'][0], "IntegerField")
  606. # Make sure the FK constraint is present
  607. constraints = self.get_constraints(Book._meta.db_table)
  608. for name, details in constraints.items():
  609. if details['columns'] == ["author_id"] and details['foreign_key']:
  610. self.assertEqual(details['foreign_key'], ('schema_author', 'id'))
  611. break
  612. else:
  613. self.fail("No FK constraint for author_id found")
  614. # Alter the FK
  615. old_field = Book._meta.get_field("author")
  616. new_field = ForeignKey(Author, CASCADE, editable=False)
  617. new_field.set_attributes_from_name("author")
  618. with connection.schema_editor() as editor:
  619. editor.alter_field(Book, old_field, new_field, strict=True)
  620. # Ensure the field is right afterwards
  621. columns = self.column_classes(Book)
  622. self.assertEqual(columns['author_id'][0], "IntegerField")
  623. # Make sure the FK constraint is present
  624. constraints = self.get_constraints(Book._meta.db_table)
  625. for name, details in constraints.items():
  626. if details['columns'] == ["author_id"] and details['foreign_key']:
  627. self.assertEqual(details['foreign_key'], ('schema_author', 'id'))
  628. break
  629. else:
  630. self.fail("No FK constraint for author_id found")
  631. @skipUnlessDBFeature('supports_foreign_keys')
  632. def test_alter_to_fk(self):
  633. """
  634. #24447 - Tests adding a FK constraint for an existing column
  635. """
  636. class LocalBook(Model):
  637. author = IntegerField()
  638. title = CharField(max_length=100, db_index=True)
  639. pub_date = DateTimeField()
  640. class Meta:
  641. app_label = 'schema'
  642. apps = new_apps
  643. self.local_models = [LocalBook]
  644. # Create the tables
  645. with connection.schema_editor() as editor:
  646. editor.create_model(Author)
  647. editor.create_model(LocalBook)
  648. # Ensure no FK constraint exists
  649. constraints = self.get_constraints(LocalBook._meta.db_table)
  650. for name, details in constraints.items():
  651. if details['foreign_key']:
  652. self.fail('Found an unexpected FK constraint to %s' % details['columns'])
  653. old_field = LocalBook._meta.get_field("author")
  654. new_field = ForeignKey(Author, CASCADE)
  655. new_field.set_attributes_from_name("author")
  656. with connection.schema_editor() as editor:
  657. editor.alter_field(LocalBook, old_field, new_field, strict=True)
  658. constraints = self.get_constraints(LocalBook._meta.db_table)
  659. # Ensure FK constraint exists
  660. for name, details in constraints.items():
  661. if details['foreign_key'] and details['columns'] == ["author_id"]:
  662. self.assertEqual(details['foreign_key'], ('schema_author', 'id'))
  663. break
  664. else:
  665. self.fail("No FK constraint for author_id found")
  666. @skipUnlessDBFeature('supports_foreign_keys')
  667. def test_alter_o2o_to_fk(self):
  668. """
  669. #24163 - Tests altering of OneToOneField to ForeignKey
  670. """
  671. # Create the table
  672. with connection.schema_editor() as editor:
  673. editor.create_model(Author)
  674. editor.create_model(BookWithO2O)
  675. # Ensure the field is right to begin with
  676. columns = self.column_classes(BookWithO2O)
  677. self.assertEqual(columns['author_id'][0], "IntegerField")
  678. # Ensure the field is unique
  679. author = Author.objects.create(name="Joe")
  680. BookWithO2O.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now())
  681. with self.assertRaises(IntegrityError):
  682. BookWithO2O.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now())
  683. BookWithO2O.objects.all().delete()
  684. # Make sure the FK constraint is present
  685. constraints = self.get_constraints(BookWithO2O._meta.db_table)
  686. author_is_fk = False
  687. for name, details in constraints.items():
  688. if details['columns'] == ['author_id']:
  689. if details['foreign_key'] and details['foreign_key'] == ('schema_author', 'id'):
  690. author_is_fk = True
  691. self.assertTrue(author_is_fk, "No FK constraint for author_id found")
  692. # Alter the OneToOneField to ForeignKey
  693. old_field = BookWithO2O._meta.get_field("author")
  694. new_field = ForeignKey(Author, CASCADE)
  695. new_field.set_attributes_from_name("author")
  696. with connection.schema_editor() as editor:
  697. editor.alter_field(BookWithO2O, old_field, new_field, strict=True)
  698. # Ensure the field is right afterwards
  699. columns = self.column_classes(Book)
  700. self.assertEqual(columns['author_id'][0], "IntegerField")
  701. # Ensure the field is not unique anymore
  702. Book.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now())
  703. Book.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now())
  704. # Make sure the FK constraint is still present
  705. constraints = self.get_constraints(Book._meta.db_table)
  706. author_is_fk = False
  707. for name, details in constraints.items():
  708. if details['columns'] == ['author_id']:
  709. if details['foreign_key'] and details['foreign_key'] == ('schema_author', 'id'):
  710. author_is_fk = True
  711. self.assertTrue(author_is_fk, "No FK constraint for author_id found")
  712. @skipUnlessDBFeature('supports_foreign_keys')
  713. def test_alter_fk_to_o2o(self):
  714. """
  715. #24163 - Tests altering of ForeignKey to OneToOneField
  716. """
  717. # Create the table
  718. with connection.schema_editor() as editor:
  719. editor.create_model(Author)
  720. editor.create_model(Book)
  721. # Ensure the field is right to begin with
  722. columns = self.column_classes(Book)
  723. self.assertEqual(columns['author_id'][0], "IntegerField")
  724. # Ensure the field is not unique
  725. author = Author.objects.create(name="Joe")
  726. Book.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now())
  727. Book.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now())
  728. Book.objects.all().delete()
  729. # Make sure the FK constraint is present
  730. constraints = self.get_constraints(Book._meta.db_table)
  731. author_is_fk = False
  732. for name, details in constraints.items():
  733. if details['columns'] == ['author_id']:
  734. if details['foreign_key'] and details['foreign_key'] == ('schema_author', 'id'):
  735. author_is_fk = True
  736. self.assertTrue(author_is_fk, "No FK constraint for author_id found")
  737. # Alter the ForeignKey to OneToOneField
  738. old_field = Book._meta.get_field("author")
  739. new_field = OneToOneField(Author, CASCADE)
  740. new_field.set_attributes_from_name("author")
  741. with connection.schema_editor() as editor:
  742. editor.alter_field(Book, old_field, new_field, strict=True)
  743. # Ensure the field is right afterwards
  744. columns = self.column_classes(BookWithO2O)
  745. self.assertEqual(columns['author_id'][0], "IntegerField")
  746. # Ensure the field is unique now
  747. BookWithO2O.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now())
  748. with self.assertRaises(IntegrityError):
  749. BookWithO2O.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now())
  750. # Make sure the FK constraint is present
  751. constraints = self.get_constraints(BookWithO2O._meta.db_table)
  752. author_is_fk = False
  753. for name, details in constraints.items():
  754. if details['columns'] == ['author_id']:
  755. if details['foreign_key'] and details['foreign_key'] == ('schema_author', 'id'):
  756. author_is_fk = True
  757. self.assertTrue(author_is_fk, "No FK constraint for author_id found")
  758. def test_alter_implicit_id_to_explicit(self):
  759. """
  760. Should be able to convert an implicit "id" field to an explicit "id"
  761. primary key field.
  762. """
  763. with connection.schema_editor() as editor:
  764. editor.create_model(Author)
  765. old_field = Author._meta.get_field("id")
  766. new_field = AutoField(primary_key=True)
  767. new_field.set_attributes_from_name("id")
  768. new_field.model = Author
  769. with connection.schema_editor() as editor:
  770. editor.alter_field(Author, old_field, new_field, strict=True)
  771. # This will fail if DROP DEFAULT is inadvertently executed on this
  772. # field which drops the id sequence, at least on PostgreSQL.
  773. Author.objects.create(name='Foo')
  774. Author.objects.create(name='Bar')
  775. def test_alter_int_pk_to_autofield_pk(self):
  776. """
  777. Should be able to rename an IntegerField(primary_key=True) to
  778. AutoField(primary_key=True).
  779. """
  780. with connection.schema_editor() as editor:
  781. editor.create_model(IntegerPK)
  782. old_field = IntegerPK._meta.get_field('i')
  783. new_field = AutoField(primary_key=True)
  784. new_field.model = IntegerPK
  785. new_field.set_attributes_from_name('i')
  786. with connection.schema_editor() as editor:
  787. editor.alter_field(IntegerPK, old_field, new_field, strict=True)
  788. def test_alter_int_pk_to_int_unique(self):
  789. """
  790. Should be able to rename an IntegerField(primary_key=True) to
  791. IntegerField(unique=True).
  792. """
  793. class IntegerUnique(Model):
  794. i = IntegerField(unique=True)
  795. j = IntegerField(primary_key=True)
  796. class Meta:
  797. app_label = 'schema'
  798. apps = new_apps
  799. db_table = 'INTEGERPK'
  800. with connection.schema_editor() as editor:
  801. editor.create_model(IntegerPK)
  802. # model requires a new PK
  803. old_field = IntegerPK._meta.get_field('j')
  804. new_field = IntegerField(primary_key=True)
  805. new_field.model = IntegerPK
  806. new_field.set_attributes_from_name('j')
  807. with connection.schema_editor() as editor:
  808. editor.alter_field(IntegerPK, old_field, new_field, strict=True)
  809. old_field = IntegerPK._meta.get_field('i')
  810. new_field = IntegerField(unique=True)
  811. new_field.model = IntegerPK
  812. new_field.set_attributes_from_name('i')
  813. with connection.schema_editor() as editor:
  814. editor.alter_field(IntegerPK, old_field, new_field, strict=True)
  815. # Ensure unique constraint works.
  816. IntegerUnique.objects.create(i=1, j=1)
  817. with self.assertRaises(IntegrityError):
  818. IntegerUnique.objects.create(i=1, j=2)
  819. def test_rename(self):
  820. """
  821. Tests simple altering of fields
  822. """
  823. # Create the table
  824. with connection.schema_editor() as editor:
  825. editor.create_model(Author)
  826. # Ensure the field is right to begin with
  827. columns = self.column_classes(Author)
  828. self.assertEqual(columns['name'][0], "CharField")
  829. self.assertNotIn("display_name", columns)
  830. # Alter the name field's name
  831. old_field = Author._meta.get_field("name")
  832. new_field = CharField(max_length=254)
  833. new_field.set_attributes_from_name("display_name")
  834. with connection.schema_editor() as editor:
  835. editor.alter_field(Author, old_field, new_field, strict=True)
  836. # Ensure the field is right afterwards
  837. columns = self.column_classes(Author)
  838. self.assertEqual(columns['display_name'][0], "CharField")
  839. self.assertNotIn("name", columns)
  840. @skipIfDBFeature('interprets_empty_strings_as_nulls')
  841. def test_rename_keep_null_status(self):
  842. """
  843. Renaming a field shouldn't affect the not null status.
  844. """
  845. with connection.schema_editor() as editor:
  846. editor.create_model(Note)
  847. with self.assertRaises(IntegrityError):
  848. Note.objects.create(info=None)
  849. old_field = Note._meta.get_field("info")
  850. new_field = TextField()
  851. new_field.set_attributes_from_name("detail_info")
  852. with connection.schema_editor() as editor:
  853. editor.alter_field(Note, old_field, new_field, strict=True)
  854. columns = self.column_classes(Note)
  855. self.assertEqual(columns['detail_info'][0], "TextField")
  856. self.assertNotIn("info", columns)
  857. with self.assertRaises(IntegrityError):
  858. NoteRename.objects.create(detail_info=None)
  859. def _test_m2m_create(self, M2MFieldClass):
  860. """
  861. Tests M2M fields on models during creation
  862. """
  863. class LocalBookWithM2M(Model):
  864. author = ForeignKey(Author, CASCADE)
  865. title = CharField(max_length=100, db_index=True)
  866. pub_date = DateTimeField()
  867. tags = M2MFieldClass("TagM2MTest", related_name="books")
  868. class Meta:
  869. app_label = 'schema'
  870. apps = new_apps
  871. self.local_models = [LocalBookWithM2M]
  872. # Create the tables
  873. with connection.schema_editor() as editor:
  874. editor.create_model(Author)
  875. editor.create_model(TagM2MTest)
  876. editor.create_model(LocalBookWithM2M)
  877. # Ensure there is now an m2m table there
  878. columns = self.column_classes(LocalBookWithM2M._meta.get_field("tags").remote_field.through)
  879. self.assertEqual(columns['tagm2mtest_id'][0], "IntegerField")
  880. def test_m2m_create(self):
  881. self._test_m2m_create(ManyToManyField)
  882. def test_m2m_create_custom(self):
  883. self._test_m2m_create(CustomManyToManyField)
  884. def test_m2m_create_inherited(self):
  885. self._test_m2m_create(InheritedManyToManyField)
  886. def _test_m2m_create_through(self, M2MFieldClass):
  887. """
  888. Tests M2M fields on models during creation with through models
  889. """
  890. class LocalTagThrough(Model):
  891. book = ForeignKey("schema.LocalBookWithM2MThrough", CASCADE)
  892. tag = ForeignKey("schema.TagM2MTest", CASCADE)
  893. class Meta:
  894. app_label = 'schema'
  895. apps = new_apps
  896. class LocalBookWithM2MThrough(Model):
  897. tags = M2MFieldClass("TagM2MTest", related_name="books", through=LocalTagThrough)
  898. class Meta:
  899. app_label = 'schema'
  900. apps = new_apps
  901. self.local_models = [LocalTagThrough, LocalBookWithM2MThrough]
  902. # Create the tables
  903. with connection.schema_editor() as editor:
  904. editor.create_model(LocalTagThrough)
  905. editor.create_model(TagM2MTest)
  906. editor.create_model(LocalBookWithM2MThrough)
  907. # Ensure there is now an m2m table there
  908. columns = self.column_classes(LocalTagThrough)
  909. self.assertEqual(columns['book_id'][0], "IntegerField")
  910. self.assertEqual(columns['tag_id'][0], "IntegerField")
  911. def test_m2m_create_through(self):
  912. self._test_m2m_create_through(ManyToManyField)
  913. def test_m2m_create_through_custom(self):
  914. self._test_m2m_create_through(CustomManyToManyField)
  915. def test_m2m_create_through_inherited(self):
  916. self._test_m2m_create_through(InheritedManyToManyField)
  917. def _test_m2m(self, M2MFieldClass):
  918. """
  919. Tests adding/removing M2M fields on models
  920. """
  921. class LocalAuthorWithM2M(Model):
  922. name = CharField(max_length=255)
  923. class Meta:
  924. app_label = 'schema'
  925. apps = new_apps
  926. self.local_models = [LocalAuthorWithM2M]
  927. # Create the tables
  928. with connection.schema_editor() as editor:
  929. editor.create_model(LocalAuthorWithM2M)
  930. editor.create_model(TagM2MTest)
  931. # Create an M2M field
  932. new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors")
  933. new_field.contribute_to_class(LocalAuthorWithM2M, "tags")
  934. # Ensure there's no m2m table there
  935. with self.assertRaises(DatabaseError):
  936. self.column_classes(new_field.remote_field.through)
  937. # Add the field
  938. with connection.schema_editor() as editor:
  939. editor.add_field(LocalAuthorWithM2M, new_field)
  940. # Ensure there is now an m2m table there
  941. columns = self.column_classes(new_field.remote_field.through)
  942. self.assertEqual(columns['tagm2mtest_id'][0], "IntegerField")
  943. # "Alter" the field. This should not rename the DB table to itself.
  944. with connection.schema_editor() as editor:
  945. editor.alter_field(LocalAuthorWithM2M, new_field, new_field)
  946. # Remove the M2M table again
  947. with connection.schema_editor() as editor:
  948. editor.remove_field(LocalAuthorWithM2M, new_field)
  949. # Ensure there's no m2m table there
  950. with self.assertRaises(DatabaseError):
  951. self.column_classes(new_field.remote_field.through)
  952. # Make sure the model state is coherent with the table one now that
  953. # we've removed the tags field.
  954. opts = LocalAuthorWithM2M._meta
  955. opts.local_many_to_many.remove(new_field)
  956. del new_apps.all_models['schema'][new_field.remote_field.through._meta.model_name]
  957. opts._expire_cache()
  958. def test_m2m(self):
  959. self._test_m2m(ManyToManyField)
  960. def test_m2m_custom(self):
  961. self._test_m2m(CustomManyToManyField)
  962. def test_m2m_inherited(self):
  963. self._test_m2m(InheritedManyToManyField)
  964. def _test_m2m_through_alter(self, M2MFieldClass):
  965. """
  966. Tests altering M2Ms with explicit through models (should no-op)
  967. """
  968. class LocalAuthorTag(Model):
  969. author = ForeignKey("schema.LocalAuthorWithM2MThrough", CASCADE)
  970. tag = ForeignKey("schema.TagM2MTest", CASCADE)
  971. class Meta:
  972. app_label = 'schema'
  973. apps = new_apps
  974. class LocalAuthorWithM2MThrough(Model):
  975. name = CharField(max_length=255)
  976. tags = M2MFieldClass("schema.TagM2MTest", related_name="authors", through=LocalAuthorTag)
  977. class Meta:
  978. app_label = 'schema'
  979. apps = new_apps
  980. self.local_models = [LocalAuthorTag, LocalAuthorWithM2MThrough]
  981. # Create the tables
  982. with connection.schema_editor() as editor:
  983. editor.create_model(LocalAuthorTag)
  984. editor.create_model(LocalAuthorWithM2MThrough)
  985. editor.create_model(TagM2MTest)
  986. # Ensure the m2m table is there
  987. self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3)
  988. # "Alter" the field's blankness. This should not actually do anything.
  989. old_field = LocalAuthorWithM2MThrough._meta.get_field("tags")
  990. new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors", through=LocalAuthorTag)
  991. new_field.contribute_to_class(LocalAuthorWithM2MThrough, "tags")
  992. with connection.schema_editor() as editor:
  993. editor.alter_field(LocalAuthorWithM2MThrough, old_field, new_field)
  994. # Ensure the m2m table is still there
  995. self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3)
  996. def test_m2m_through_alter(self):
  997. self._test_m2m_through_alter(ManyToManyField)
  998. def test_m2m_through_alter_custom(self):
  999. self._test_m2m_through_alter(CustomManyToManyField)
  1000. def test_m2m_through_alter_inherited(self):
  1001. self._test_m2m_through_alter(InheritedManyToManyField)
  1002. def _test_m2m_repoint(self, M2MFieldClass):
  1003. """
  1004. Tests repointing M2M fields
  1005. """
  1006. class LocalBookWithM2M(Model):
  1007. author = ForeignKey(Author, CASCADE)
  1008. title = CharField(max_length=100, db_index=True)
  1009. pub_date = DateTimeField()
  1010. tags = M2MFieldClass("TagM2MTest", related_name="books")
  1011. class Meta:
  1012. app_label = 'schema'
  1013. apps = new_apps
  1014. self.local_models = [LocalBookWithM2M]
  1015. # Create the tables
  1016. with connection.schema_editor() as editor:
  1017. editor.create_model(Author)
  1018. editor.create_model(LocalBookWithM2M)
  1019. editor.create_model(TagM2MTest)
  1020. editor.create_model(UniqueTest)
  1021. # Ensure the M2M exists and points to TagM2MTest
  1022. constraints = self.get_constraints(
  1023. LocalBookWithM2M._meta.get_field("tags").remote_field.through._meta.db_table
  1024. )
  1025. if connection.features.supports_foreign_keys:
  1026. for name, details in constraints.items():
  1027. if details['columns'] == ["tagm2mtest_id"] and details['foreign_key']:
  1028. self.assertEqual(details['foreign_key'], ('schema_tagm2mtest', 'id'))
  1029. break
  1030. else:
  1031. self.fail("No FK constraint for tagm2mtest_id found")
  1032. # Repoint the M2M
  1033. old_field = LocalBookWithM2M._meta.get_field("tags")
  1034. new_field = M2MFieldClass(UniqueTest)
  1035. new_field.contribute_to_class(LocalBookWithM2M, "uniques")
  1036. with connection.schema_editor() as editor:
  1037. editor.alter_field(LocalBookWithM2M, old_field, new_field)
  1038. # Ensure old M2M is gone
  1039. with self.assertRaises(DatabaseError):
  1040. self.column_classes(LocalBookWithM2M._meta.get_field("tags").remote_field.through)
  1041. # This model looks like the new model and is used for teardown.
  1042. opts = LocalBookWithM2M._meta
  1043. opts.local_many_to_many.remove(old_field)
  1044. # Ensure the new M2M exists and points to UniqueTest
  1045. constraints = self.get_constraints(new_field.remote_field.through._meta.db_table)
  1046. if connection.features.supports_foreign_keys:
  1047. for name, details in constraints.items():
  1048. if details['columns'] == ["uniquetest_id"] and details['foreign_key']:
  1049. self.assertEqual(details['foreign_key'], ('schema_uniquetest', 'id'))
  1050. break
  1051. else:
  1052. self.fail("No FK constraint for uniquetest_id found")
  1053. def test_m2m_repoint(self):
  1054. self._test_m2m_repoint(ManyToManyField)
  1055. def test_m2m_repoint_custom(self):
  1056. self._test_m2m_repoint(CustomManyToManyField)
  1057. def test_m2m_repoint_inherited(self):
  1058. self._test_m2m_repoint(InheritedManyToManyField)
  1059. @skipUnlessDBFeature('supports_column_check_constraints')
  1060. def test_check_constraints(self):
  1061. """
  1062. Tests creating/deleting CHECK constraints
  1063. """
  1064. # Create the tables
  1065. with connection.schema_editor() as editor:
  1066. editor.create_model(Author)
  1067. # Ensure the constraint exists
  1068. constraints = self.get_constraints(Author._meta.db_table)
  1069. for name, details in constraints.items():
  1070. if details['columns'] == ["height"] and details['check']:
  1071. break
  1072. else:
  1073. self.fail("No check constraint for height found")
  1074. # Alter the column to remove it
  1075. old_field = Author._meta.get_field("height")
  1076. new_field = IntegerField(null=True, blank=True)
  1077. new_field.set_attributes_from_name("height")
  1078. with connection.schema_editor() as editor:
  1079. editor.alter_field(Author, old_field, new_field, strict=True)
  1080. constraints = self.get_constraints(Author._meta.db_table)
  1081. for name, details in constraints.items():
  1082. if details['columns'] == ["height"] and details['check']:
  1083. self.fail("Check constraint for height found")
  1084. # Alter the column to re-add it
  1085. new_field2 = Author._meta.get_field("height")
  1086. with connection.schema_editor() as editor:
  1087. editor.alter_field(Author, new_field, new_field2, strict=True)
  1088. constraints = self.get_constraints(Author._meta.db_table)
  1089. for name, details in constraints.items():
  1090. if details['columns'] == ["height"] and details['check']:
  1091. break
  1092. else:
  1093. self.fail("No check constraint for height found")
  1094. def test_unique(self):
  1095. """
  1096. Tests removing and adding unique constraints to a single column.
  1097. """
  1098. # Create the table
  1099. with connection.schema_editor() as editor:
  1100. editor.create_model(Tag)
  1101. # Ensure the field is unique to begin with
  1102. Tag.objects.create(title="foo", slug="foo")
  1103. with self.assertRaises(IntegrityError):
  1104. Tag.objects.create(title="bar", slug="foo")
  1105. Tag.objects.all().delete()
  1106. # Alter the slug field to be non-unique
  1107. old_field = Tag._meta.get_field("slug")
  1108. new_field = SlugField(unique=False)
  1109. new_field.set_attributes_from_name("slug")
  1110. with connection.schema_editor() as editor:
  1111. editor.alter_field(Tag, old_field, new_field, strict=True)
  1112. # Ensure the field is no longer unique
  1113. Tag.objects.create(title="foo", slug="foo")
  1114. Tag.objects.create(title="bar", slug="foo")
  1115. Tag.objects.all().delete()
  1116. # Alter the slug field to be unique
  1117. new_field2 = SlugField(unique=True)
  1118. new_field2.set_attributes_from_name("slug")
  1119. with connection.schema_editor() as editor:
  1120. editor.alter_field(Tag, new_field, new_field2, strict=True)
  1121. # Ensure the field is unique again
  1122. Tag.objects.create(title="foo", slug="foo")
  1123. with self.assertRaises(IntegrityError):
  1124. Tag.objects.create(title="bar", slug="foo")
  1125. Tag.objects.all().delete()
  1126. # Rename the field
  1127. new_field3 = SlugField(unique=True)
  1128. new_field3.set_attributes_from_name("slug2")
  1129. with connection.schema_editor() as editor:
  1130. editor.alter_field(Tag, new_field2, new_field3, strict=True)
  1131. # Ensure the field is still unique
  1132. TagUniqueRename.objects.create(title="foo", slug2="foo")
  1133. with self.assertRaises(IntegrityError):
  1134. TagUniqueRename.objects.create(title="bar", slug2="foo")
  1135. Tag.objects.all().delete()
  1136. def test_unique_together(self):
  1137. """
  1138. Tests removing and adding unique_together constraints on a model.
  1139. """
  1140. # Create the table
  1141. with connection.schema_editor() as editor:
  1142. editor.create_model(UniqueTest)
  1143. # Ensure the fields are unique to begin with
  1144. UniqueTest.objects.create(year=2012, slug="foo")
  1145. UniqueTest.objects.create(year=2011, slug="foo")
  1146. UniqueTest.objects.create(year=2011, slug="bar")
  1147. with self.assertRaises(IntegrityError):
  1148. UniqueTest.objects.create(year=2012, slug="foo")
  1149. UniqueTest.objects.all().delete()
  1150. # Alter the model to its non-unique-together companion
  1151. with connection.schema_editor() as editor:
  1152. editor.alter_unique_together(UniqueTest, UniqueTest._meta.unique_together, [])
  1153. # Ensure the fields are no longer unique
  1154. UniqueTest.objects.create(year=2012, slug="foo")
  1155. UniqueTest.objects.create(year=2012, slug="foo")
  1156. UniqueTest.objects.all().delete()
  1157. # Alter it back
  1158. new_field2 = SlugField(unique=True)
  1159. new_field2.set_attributes_from_name("slug")
  1160. with connection.schema_editor() as editor:
  1161. editor.alter_unique_together(UniqueTest, [], UniqueTest._meta.unique_together)
  1162. # Ensure the fields are unique again
  1163. UniqueTest.objects.create(year=2012, slug="foo")
  1164. with self.assertRaises(IntegrityError):
  1165. UniqueTest.objects.create(year=2012, slug="foo")
  1166. UniqueTest.objects.all().delete()
  1167. def test_unique_together_with_fk(self):
  1168. """
  1169. Tests removing and adding unique_together constraints that include
  1170. a foreign key.
  1171. """
  1172. # Create the table
  1173. with connection.schema_editor() as editor:
  1174. editor.create_model(Author)
  1175. editor.create_model(Book)
  1176. # Ensure the fields are unique to begin with
  1177. self.assertEqual(Book._meta.unique_together, ())
  1178. # Add the unique_together constraint
  1179. with connection.schema_editor() as editor:
  1180. editor.alter_unique_together(Book, [], [['author', 'title']])
  1181. # Alter it back
  1182. with connection.schema_editor() as editor:
  1183. editor.alter_unique_together(Book, [['author', 'title']], [])
  1184. def test_unique_together_with_fk_with_existing_index(self):
  1185. """
  1186. Tests removing and adding unique_together constraints that include
  1187. a foreign key, where the foreign key is added after the model is
  1188. created.
  1189. """
  1190. # Create the tables
  1191. with connection.schema_editor() as editor:
  1192. editor.create_model(Author)
  1193. editor.create_model(BookWithoutAuthor)
  1194. new_field = ForeignKey(Author, CASCADE)
  1195. new_field.set_attributes_from_name('author')
  1196. editor.add_field(BookWithoutAuthor, new_field)
  1197. # Ensure the fields aren't unique to begin with
  1198. self.assertEqual(Book._meta.unique_together, ())
  1199. # Add the unique_together constraint
  1200. with connection.schema_editor() as editor:
  1201. editor.alter_unique_together(Book, [], [['author', 'title']])
  1202. # Alter it back
  1203. with connection.schema_editor() as editor:
  1204. editor.alter_unique_together(Book, [['author', 'title']], [])
  1205. def test_index_together(self):
  1206. """
  1207. Tests removing and adding index_together constraints on a model.
  1208. """
  1209. # Create the table
  1210. with connection.schema_editor() as editor:
  1211. editor.create_model(Tag)
  1212. # Ensure there's no index on the year/slug columns first
  1213. self.assertEqual(
  1214. False,
  1215. any(
  1216. c["index"]
  1217. for c in self.get_constraints("schema_tag").values()
  1218. if c['columns'] == ["slug", "title"]
  1219. ),
  1220. )
  1221. # Alter the model to add an index
  1222. with connection.schema_editor() as editor:
  1223. editor.alter_index_together(Tag, [], [("slug", "title")])
  1224. # Ensure there is now an index
  1225. self.assertEqual(
  1226. True,
  1227. any(
  1228. c["index"]
  1229. for c in self.get_constraints("schema_tag").values()
  1230. if c['columns'] == ["slug", "title"]
  1231. ),
  1232. )
  1233. # Alter it back
  1234. new_field2 = SlugField(unique=True)
  1235. new_field2.set_attributes_from_name("slug")
  1236. with connection.schema_editor() as editor:
  1237. editor.alter_index_together(Tag, [("slug", "title")], [])
  1238. # Ensure there's no index
  1239. self.assertEqual(
  1240. False,
  1241. any(
  1242. c["index"]
  1243. for c in self.get_constraints("schema_tag").values()
  1244. if c['columns'] == ["slug", "title"]
  1245. ),
  1246. )
  1247. def test_index_together_with_fk(self):
  1248. """
  1249. Tests removing and adding index_together constraints that include
  1250. a foreign key.
  1251. """
  1252. # Create the table
  1253. with connection.schema_editor() as editor:
  1254. editor.create_model(Author)
  1255. editor.create_model(Book)
  1256. # Ensure the fields are unique to begin with
  1257. self.assertEqual(Book._meta.index_together, ())
  1258. # Add the unique_together constraint
  1259. with connection.schema_editor() as editor:
  1260. editor.alter_index_together(Book, [], [['author', 'title']])
  1261. # Alter it back
  1262. with connection.schema_editor() as editor:
  1263. editor.alter_index_together(Book, [['author', 'title']], [])
  1264. def test_create_index_together(self):
  1265. """
  1266. Tests creating models with index_together already defined
  1267. """
  1268. # Create the table
  1269. with connection.schema_editor() as editor:
  1270. editor.create_model(TagIndexed)
  1271. # Ensure there is an index
  1272. self.assertEqual(
  1273. True,
  1274. any(
  1275. c["index"]
  1276. for c in self.get_constraints("schema_tagindexed").values()
  1277. if c['columns'] == ["slug", "title"]
  1278. ),
  1279. )
  1280. def test_db_table(self):
  1281. """
  1282. Tests renaming of the table
  1283. """
  1284. # Create the table
  1285. with connection.schema_editor() as editor:
  1286. editor.create_model(Author)
  1287. # Ensure the table is there to begin with
  1288. columns = self.column_classes(Author)
  1289. self.assertEqual(columns['name'][0], "CharField")
  1290. # Alter the table
  1291. with connection.schema_editor() as editor:
  1292. editor.alter_db_table(Author, "schema_author", "schema_otherauthor")
  1293. # Ensure the table is there afterwards
  1294. Author._meta.db_table = "schema_otherauthor"
  1295. columns = self.column_classes(Author)
  1296. self.assertEqual(columns['name'][0], "CharField")
  1297. # Alter the table again
  1298. with connection.schema_editor() as editor:
  1299. editor.alter_db_table(Author, "schema_otherauthor", "schema_author")
  1300. # Ensure the table is still there
  1301. Author._meta.db_table = "schema_author"
  1302. columns = self.column_classes(Author)
  1303. self.assertEqual(columns['name'][0], "CharField")
  1304. def test_indexes(self):
  1305. """
  1306. Tests creation/altering of indexes
  1307. """
  1308. # Create the table
  1309. with connection.schema_editor() as editor:
  1310. editor.create_model(Author)
  1311. editor.create_model(Book)
  1312. # Ensure the table is there and has the right index
  1313. self.assertIn(
  1314. "title",
  1315. self.get_indexes(Book._meta.db_table),
  1316. )
  1317. # Alter to remove the index
  1318. old_field = Book._meta.get_field("title")
  1319. new_field = CharField(max_length=100, db_index=False)
  1320. new_field.set_attributes_from_name("title")
  1321. with connection.schema_editor() as editor:
  1322. editor.alter_field(Book, old_field, new_field, strict=True)
  1323. # Ensure the table is there and has no index
  1324. self.assertNotIn(
  1325. "title",
  1326. self.get_indexes(Book._meta.db_table),
  1327. )
  1328. # Alter to re-add the index
  1329. new_field2 = Book._meta.get_field("title")
  1330. with connection.schema_editor() as editor:
  1331. editor.alter_field(Book, new_field, new_field2, strict=True)
  1332. # Ensure the table is there and has the index again
  1333. self.assertIn(
  1334. "title",
  1335. self.get_indexes(Book._meta.db_table),
  1336. )
  1337. # Add a unique column, verify that creates an implicit index
  1338. new_field3 = BookWithSlug._meta.get_field("slug")
  1339. with connection.schema_editor() as editor:
  1340. editor.add_field(Book, new_field3)
  1341. self.assertIn(
  1342. "slug",
  1343. self.get_indexes(Book._meta.db_table),
  1344. )
  1345. # Remove the unique, check the index goes with it
  1346. new_field4 = CharField(max_length=20, unique=False)
  1347. new_field4.set_attributes_from_name("slug")
  1348. with connection.schema_editor() as editor:
  1349. editor.alter_field(BookWithSlug, new_field3, new_field4, strict=True)
  1350. self.assertNotIn(
  1351. "slug",
  1352. self.get_indexes(Book._meta.db_table),
  1353. )
  1354. def test_primary_key(self):
  1355. """
  1356. Tests altering of the primary key
  1357. """
  1358. # Create the table
  1359. with connection.schema_editor() as editor:
  1360. editor.create_model(Tag)
  1361. # Ensure the table is there and has the right PK
  1362. self.assertTrue(
  1363. self.get_indexes(Tag._meta.db_table)['id']['primary_key'],
  1364. )
  1365. # Alter to change the PK
  1366. id_field = Tag._meta.get_field("id")
  1367. old_field = Tag._meta.get_field("slug")
  1368. new_field = SlugField(primary_key=True)
  1369. new_field.set_attributes_from_name("slug")
  1370. new_field.model = Tag
  1371. with connection.schema_editor() as editor:
  1372. editor.remove_field(Tag, id_field)
  1373. editor.alter_field(Tag, old_field, new_field)
  1374. # Ensure the PK changed
  1375. self.assertNotIn(
  1376. 'id',
  1377. self.get_indexes(Tag._meta.db_table),
  1378. )
  1379. self.assertTrue(
  1380. self.get_indexes(Tag._meta.db_table)['slug']['primary_key'],
  1381. )
  1382. def test_context_manager_exit(self):
  1383. """
  1384. Ensures transaction is correctly closed when an error occurs
  1385. inside a SchemaEditor context.
  1386. """
  1387. class SomeError(Exception):
  1388. pass
  1389. try:
  1390. with connection.schema_editor():
  1391. raise SomeError
  1392. except SomeError:
  1393. self.assertFalse(connection.in_atomic_block)
  1394. @skipUnlessDBFeature('supports_foreign_keys')
  1395. def test_foreign_key_index_long_names_regression(self):
  1396. """
  1397. Regression test for #21497.
  1398. Only affects databases that supports foreign keys.
  1399. """
  1400. # Create the table
  1401. with connection.schema_editor() as editor:
  1402. editor.create_model(AuthorWithEvenLongerName)
  1403. editor.create_model(BookWithLongName)
  1404. # Find the properly shortened column name
  1405. column_name = connection.ops.quote_name("author_foreign_key_with_really_long_field_name_id")
  1406. column_name = column_name[1:-1].lower() # unquote, and, for Oracle, un-upcase
  1407. # Ensure the table is there and has an index on the column
  1408. self.assertIn(
  1409. column_name,
  1410. self.get_indexes(BookWithLongName._meta.db_table),
  1411. )
  1412. @skipUnlessDBFeature('supports_foreign_keys')
  1413. def test_add_foreign_key_long_names(self):
  1414. """
  1415. Regression test for #23009.
  1416. Only affects databases that supports foreign keys.
  1417. """
  1418. # Create the initial tables
  1419. with connection.schema_editor() as editor:
  1420. editor.create_model(AuthorWithEvenLongerName)
  1421. editor.create_model(BookWithLongName)
  1422. # Add a second FK, this would fail due to long ref name before the fix
  1423. new_field = ForeignKey(AuthorWithEvenLongerName, CASCADE, related_name="something")
  1424. new_field.set_attributes_from_name("author_other_really_long_named_i_mean_so_long_fk")
  1425. with connection.schema_editor() as editor:
  1426. editor.add_field(BookWithLongName, new_field)
  1427. def test_add_foreign_object(self):
  1428. with connection.schema_editor() as editor:
  1429. editor.create_model(BookForeignObj)
  1430. new_field = ForeignObject(Author, on_delete=CASCADE, from_fields=['author_id'], to_fields=['id'])
  1431. new_field.set_attributes_from_name('author')
  1432. with connection.schema_editor() as editor:
  1433. editor.add_field(BookForeignObj, new_field)
  1434. def test_creation_deletion_reserved_names(self):
  1435. """
  1436. Tries creating a model's table, and then deleting it when it has a
  1437. SQL reserved name.
  1438. """
  1439. # Create the table
  1440. with connection.schema_editor() as editor:
  1441. try:
  1442. editor.create_model(Thing)
  1443. except OperationalError as e:
  1444. self.fail("Errors when applying initial migration for a model "
  1445. "with a table named after an SQL reserved word: %s" % e)
  1446. # Check that it's there
  1447. list(Thing.objects.all())
  1448. # Clean up that table
  1449. with connection.schema_editor() as editor:
  1450. editor.delete_model(Thing)
  1451. # Check that it's gone
  1452. with self.assertRaises(DatabaseError):
  1453. list(Thing.objects.all())
  1454. @skipUnlessDBFeature('supports_foreign_keys')
  1455. def test_remove_constraints_capital_letters(self):
  1456. """
  1457. #23065 - Constraint names must be quoted if they contain capital letters.
  1458. """
  1459. def get_field(*args, **kwargs):
  1460. kwargs['db_column'] = "CamelCase"
  1461. field = kwargs.pop('field_class', IntegerField)(*args, **kwargs)
  1462. field.set_attributes_from_name("CamelCase")
  1463. return field
  1464. model = Author
  1465. field = get_field()
  1466. table = model._meta.db_table
  1467. column = field.column
  1468. with connection.schema_editor() as editor:
  1469. editor.create_model(model)
  1470. editor.add_field(model, field)
  1471. editor.execute(
  1472. editor.sql_create_index % {
  1473. "table": editor.quote_name(table),
  1474. "name": editor.quote_name("CamelCaseIndex"),
  1475. "columns": editor.quote_name(column),
  1476. "extra": "",
  1477. }
  1478. )
  1479. editor.alter_field(model, get_field(db_index=True), field)
  1480. editor.execute(
  1481. editor.sql_create_unique % {
  1482. "table": editor.quote_name(table),
  1483. "name": editor.quote_name("CamelCaseUniqConstraint"),
  1484. "columns": editor.quote_name(field.column),
  1485. }
  1486. )
  1487. editor.alter_field(model, get_field(unique=True), field)
  1488. editor.execute(
  1489. editor.sql_create_fk % {
  1490. "table": editor.quote_name(table),
  1491. "name": editor.quote_name("CamelCaseFKConstraint"),
  1492. "column": editor.quote_name(column),
  1493. "to_table": editor.quote_name(table),
  1494. "to_column": editor.quote_name(model._meta.auto_field.column),
  1495. }
  1496. )
  1497. editor.alter_field(model, get_field(Author, CASCADE, field_class=ForeignKey), field)
  1498. def test_add_field_use_effective_default(self):
  1499. """
  1500. #23987 - effective_default() should be used as the field default when
  1501. adding a new field.
  1502. """
  1503. # Create the table
  1504. with connection.schema_editor() as editor:
  1505. editor.create_model(Author)
  1506. # Ensure there's no surname field
  1507. columns = self.column_classes(Author)
  1508. self.assertNotIn("surname", columns)
  1509. # Create a row
  1510. Author.objects.create(name='Anonymous1')
  1511. # Add new CharField to ensure default will be used from effective_default
  1512. new_field = CharField(max_length=15, blank=True)
  1513. new_field.set_attributes_from_name("surname")
  1514. with connection.schema_editor() as editor:
  1515. editor.add_field(Author, new_field)
  1516. # Ensure field was added with the right default
  1517. with connection.cursor() as cursor:
  1518. cursor.execute("SELECT surname FROM schema_author;")
  1519. item = cursor.fetchall()[0]
  1520. self.assertEqual(item[0], None if connection.features.interprets_empty_strings_as_nulls else '')
  1521. def test_add_field_default_dropped(self):
  1522. # Create the table
  1523. with connection.schema_editor() as editor:
  1524. editor.create_model(Author)
  1525. # Ensure there's no surname field
  1526. columns = self.column_classes(Author)
  1527. self.assertNotIn("surname", columns)
  1528. # Create a row
  1529. Author.objects.create(name='Anonymous1')
  1530. # Add new CharField with a default
  1531. new_field = CharField(max_length=15, blank=True, default='surname default')
  1532. new_field.set_attributes_from_name("surname")
  1533. with connection.schema_editor() as editor:
  1534. editor.add_field(Author, new_field)
  1535. # Ensure field was added with the right default
  1536. with connection.cursor() as cursor:
  1537. cursor.execute("SELECT surname FROM schema_author;")
  1538. item = cursor.fetchall()[0]
  1539. self.assertEqual(item[0], 'surname default')
  1540. # And that the default is no longer set in the database.
  1541. field = next(
  1542. f for f in connection.introspection.get_table_description(cursor, "schema_author")
  1543. if f.name == "surname"
  1544. )
  1545. if connection.features.can_introspect_default:
  1546. self.assertIsNone(field.default)
  1547. def test_alter_field_default_dropped(self):
  1548. # Create the table
  1549. with connection.schema_editor() as editor:
  1550. editor.create_model(Author)
  1551. # Create a row
  1552. Author.objects.create(name='Anonymous1')
  1553. self.assertEqual(Author.objects.get().height, None)
  1554. old_field = Author._meta.get_field('height')
  1555. # The default from the new field is used in updating existing rows.
  1556. new_field = IntegerField(blank=True, default=42)
  1557. new_field.set_attributes_from_name('height')
  1558. with connection.schema_editor() as editor:
  1559. editor.alter_field(Author, old_field, new_field)
  1560. self.assertEqual(Author.objects.get().height, 42)
  1561. # The database default should be removed.
  1562. with connection.cursor() as cursor:
  1563. field = next(
  1564. f for f in connection.introspection.get_table_description(cursor, "schema_author")
  1565. if f.name == "height"
  1566. )
  1567. if connection.features.can_introspect_default:
  1568. self.assertIsNone(field.default)
  1569. def test_add_textfield_unhashable_default(self):
  1570. # Create the table
  1571. with connection.schema_editor() as editor:
  1572. editor.create_model(Author)
  1573. # Create a row
  1574. Author.objects.create(name='Anonymous1')
  1575. # Create a field that has an unhashable default
  1576. new_field = TextField(default={})
  1577. new_field.set_attributes_from_name("info")
  1578. with connection.schema_editor() as editor:
  1579. editor.add_field(Author, new_field)
  1580. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  1581. def test_alter_field_add_index_to_charfield(self):
  1582. # Create the table and verify no initial indexes.
  1583. with connection.schema_editor() as editor:
  1584. editor.create_model(Author)
  1585. self.assertEqual(self.get_constraints_for_column(Author, 'name'), [])
  1586. # Alter to add db_index=True and create 2 indexes.
  1587. old_field = Author._meta.get_field('name')
  1588. new_field = CharField(max_length=255, db_index=True)
  1589. new_field.set_attributes_from_name('name')
  1590. with connection.schema_editor() as editor:
  1591. editor.alter_field(Author, old_field, new_field, strict=True)
  1592. self.assertEqual(
  1593. self.get_constraints_for_column(Author, 'name'),
  1594. ['schema_author_name_1fbc5617_like', 'schema_author_name_1fbc5617_uniq']
  1595. )
  1596. # Remove db_index=True to drop both indexes.
  1597. with connection.schema_editor() as editor:
  1598. editor.alter_field(Author, new_field, old_field, strict=True)
  1599. self.assertEqual(self.get_constraints_for_column(Author, 'name'), [])
  1600. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  1601. def test_alter_field_add_index_to_textfield(self):
  1602. # Create the table and verify no initial indexes.
  1603. with connection.schema_editor() as editor:
  1604. editor.create_model(Note)
  1605. self.assertEqual(self.get_constraints_for_column(Note, 'info'), [])
  1606. # Alter to add db_index=True and create 2 indexes.
  1607. old_field = Note._meta.get_field('info')
  1608. new_field = TextField(db_index=True)
  1609. new_field.set_attributes_from_name('info')
  1610. with connection.schema_editor() as editor:
  1611. editor.alter_field(Note, old_field, new_field, strict=True)
  1612. self.assertEqual(
  1613. self.get_constraints_for_column(Note, 'info'),
  1614. ['schema_note_info_4b0ea695_like', 'schema_note_info_4b0ea695_uniq']
  1615. )
  1616. # Remove db_index=True to drop both indexes.
  1617. with connection.schema_editor() as editor:
  1618. editor.alter_field(Note, new_field, old_field, strict=True)
  1619. self.assertEqual(self.get_constraints_for_column(Note, 'info'), [])
  1620. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  1621. def test_alter_field_add_unique_to_charfield_with_db_index(self):
  1622. # Create the table and verify initial indexes.
  1623. with connection.schema_editor() as editor:
  1624. editor.create_model(BookWithoutAuthor)
  1625. self.assertEqual(
  1626. self.get_constraints_for_column(BookWithoutAuthor, 'title'),
  1627. ['schema_book_d5d3db17', 'schema_book_title_2dfb2dff_like']
  1628. )
  1629. # Alter to add unique=True (should add 1 index)
  1630. old_field = BookWithoutAuthor._meta.get_field('title')
  1631. new_field = CharField(max_length=100, db_index=True, unique=True)
  1632. new_field.set_attributes_from_name('title')
  1633. with connection.schema_editor() as editor:
  1634. editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True)
  1635. self.assertEqual(
  1636. self.get_constraints_for_column(BookWithoutAuthor, 'title'),
  1637. ['schema_book_d5d3db17', 'schema_book_title_2dfb2dff_like', 'schema_book_title_2dfb2dff_uniq']
  1638. )
  1639. # Alter to remove unique=True (should drop unique index) # XXX: bug!
  1640. old_field = BookWithoutAuthor._meta.get_field('title')
  1641. new_field = CharField(max_length=100, db_index=True)
  1642. new_field.set_attributes_from_name('title')
  1643. with connection.schema_editor() as editor:
  1644. editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True)
  1645. self.assertEqual(
  1646. self.get_constraints_for_column(BookWithoutAuthor, 'title'),
  1647. ['schema_book_d5d3db17', 'schema_book_title_2dfb2dff_like', 'schema_book_title_2dfb2dff_uniq']
  1648. )
  1649. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  1650. def test_alter_field_add_db_index_to_charfield_with_unique(self):
  1651. # Create the table and verify initial indexes.
  1652. with connection.schema_editor() as editor:
  1653. editor.create_model(Tag)
  1654. self.assertEqual(
  1655. self.get_constraints_for_column(Tag, 'slug'),
  1656. ['schema_tag_slug_2c418ba3_like', 'schema_tag_slug_key']
  1657. )
  1658. # Alter to add db_index=True
  1659. old_field = Tag._meta.get_field('slug')
  1660. new_field = SlugField(db_index=True, unique=True)
  1661. new_field.set_attributes_from_name('slug')
  1662. with connection.schema_editor() as editor:
  1663. editor.alter_field(Tag, old_field, new_field, strict=True)
  1664. self.assertEqual(
  1665. self.get_constraints_for_column(Tag, 'slug'),
  1666. ['schema_tag_slug_2c418ba3_like', 'schema_tag_slug_key']
  1667. )
  1668. # Alter to remove db_index=True
  1669. old_field = Tag._meta.get_field('slug')
  1670. new_field = SlugField(unique=True)
  1671. new_field.set_attributes_from_name('slug')
  1672. with connection.schema_editor() as editor:
  1673. editor.alter_field(Tag, old_field, new_field, strict=True)
  1674. self.assertEqual(
  1675. self.get_constraints_for_column(Tag, 'slug'),
  1676. ['schema_tag_slug_2c418ba3_like', 'schema_tag_slug_key']
  1677. )
  1678. def test_alter_pk_with_self_referential_field(self):
  1679. """
  1680. Changing the primary key field name of a model with a self-referential
  1681. foreign key (#26384).
  1682. """
  1683. if connection.vendor == 'mysql' and connection.mysql_version < (5, 6, 6):
  1684. self.skipTest('Skip known bug renaming primary keys on older MySQL versions (#24995).')
  1685. old_field = Node._meta.get_field('node_id')
  1686. new_field = AutoField(primary_key=True)
  1687. new_field.set_attributes_from_name('id')
  1688. with connection.schema_editor() as editor:
  1689. editor.alter_field(Node, old_field, new_field)