tests.py 96 KB

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