test_operations.py 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824
  1. from django.core.exceptions import FieldDoesNotExist
  2. from django.db import connection, migrations, models, transaction
  3. from django.db.migrations.migration import Migration
  4. from django.db.migrations.operations import CreateModel
  5. from django.db.migrations.operations.fields import FieldOperation
  6. from django.db.migrations.state import ModelState, ProjectState
  7. from django.db.models.fields import NOT_PROVIDED
  8. from django.db.transaction import atomic
  9. from django.db.utils import IntegrityError
  10. from django.test import SimpleTestCase, override_settings, skipUnlessDBFeature
  11. from .models import FoodManager, FoodQuerySet, UnicodeModel
  12. from .test_base import MigrationTestBase
  13. class Mixin:
  14. pass
  15. class OperationTestBase(MigrationTestBase):
  16. """
  17. Common functions to help test operations.
  18. """
  19. def apply_operations(self, app_label, project_state, operations, atomic=True):
  20. migration = Migration('name', app_label)
  21. migration.operations = operations
  22. with connection.schema_editor(atomic=atomic) as editor:
  23. return migration.apply(project_state, editor)
  24. def unapply_operations(self, app_label, project_state, operations, atomic=True):
  25. migration = Migration('name', app_label)
  26. migration.operations = operations
  27. with connection.schema_editor(atomic=atomic) as editor:
  28. return migration.unapply(project_state, editor)
  29. def make_test_state(self, app_label, operation, **kwargs):
  30. """
  31. Makes a test state using set_up_test_model and returns the
  32. original state and the state after the migration is applied.
  33. """
  34. project_state = self.set_up_test_model(app_label, **kwargs)
  35. new_state = project_state.clone()
  36. operation.state_forwards(app_label, new_state)
  37. return project_state, new_state
  38. def set_up_test_model(
  39. self, app_label, second_model=False, third_model=False, index=False, multicol_index=False,
  40. related_model=False, mti_model=False, proxy_model=False, manager_model=False,
  41. unique_together=False, options=False, db_table=None, index_together=False, constraints=None):
  42. """
  43. Creates a test model state and database table.
  44. """
  45. # Delete the tables if they already exist
  46. table_names = [
  47. # Start with ManyToMany tables
  48. '_pony_stables', '_pony_vans',
  49. # Then standard model tables
  50. '_pony', '_stable', '_van',
  51. ]
  52. tables = [(app_label + table_name) for table_name in table_names]
  53. with connection.cursor() as cursor:
  54. table_names = connection.introspection.table_names(cursor)
  55. connection.disable_constraint_checking()
  56. sql_delete_table = connection.schema_editor().sql_delete_table
  57. with transaction.atomic():
  58. for table in tables:
  59. if table in table_names:
  60. cursor.execute(sql_delete_table % {
  61. "table": connection.ops.quote_name(table),
  62. })
  63. connection.enable_constraint_checking()
  64. # Make the "current" state
  65. model_options = {
  66. "swappable": "TEST_SWAP_MODEL",
  67. "index_together": [["weight", "pink"]] if index_together else [],
  68. "unique_together": [["pink", "weight"]] if unique_together else [],
  69. }
  70. if options:
  71. model_options["permissions"] = [("can_groom", "Can groom")]
  72. if db_table:
  73. model_options["db_table"] = db_table
  74. operations = [migrations.CreateModel(
  75. "Pony",
  76. [
  77. ("id", models.AutoField(primary_key=True)),
  78. ("pink", models.IntegerField(default=3)),
  79. ("weight", models.FloatField()),
  80. ],
  81. options=model_options,
  82. )]
  83. if index:
  84. operations.append(migrations.AddIndex(
  85. "Pony",
  86. models.Index(fields=["pink"], name="pony_pink_idx")
  87. ))
  88. if multicol_index:
  89. operations.append(migrations.AddIndex(
  90. "Pony",
  91. models.Index(fields=["pink", "weight"], name="pony_test_idx")
  92. ))
  93. if constraints:
  94. for constraint in constraints:
  95. operations.append(migrations.AddConstraint(
  96. "Pony",
  97. constraint,
  98. ))
  99. if second_model:
  100. operations.append(migrations.CreateModel(
  101. "Stable",
  102. [
  103. ("id", models.AutoField(primary_key=True)),
  104. ]
  105. ))
  106. if third_model:
  107. operations.append(migrations.CreateModel(
  108. "Van",
  109. [
  110. ("id", models.AutoField(primary_key=True)),
  111. ]
  112. ))
  113. if related_model:
  114. operations.append(migrations.CreateModel(
  115. "Rider",
  116. [
  117. ("id", models.AutoField(primary_key=True)),
  118. ("pony", models.ForeignKey("Pony", models.CASCADE)),
  119. ("friend", models.ForeignKey("self", models.CASCADE))
  120. ],
  121. ))
  122. if mti_model:
  123. operations.append(migrations.CreateModel(
  124. "ShetlandPony",
  125. fields=[
  126. ('pony_ptr', models.OneToOneField(
  127. 'Pony',
  128. models.CASCADE,
  129. auto_created=True,
  130. parent_link=True,
  131. primary_key=True,
  132. to_field='id',
  133. serialize=False,
  134. )),
  135. ("cuteness", models.IntegerField(default=1)),
  136. ],
  137. bases=['%s.Pony' % app_label],
  138. ))
  139. if proxy_model:
  140. operations.append(migrations.CreateModel(
  141. "ProxyPony",
  142. fields=[],
  143. options={"proxy": True},
  144. bases=['%s.Pony' % app_label],
  145. ))
  146. if manager_model:
  147. operations.append(migrations.CreateModel(
  148. "Food",
  149. fields=[
  150. ("id", models.AutoField(primary_key=True)),
  151. ],
  152. managers=[
  153. ("food_qs", FoodQuerySet.as_manager()),
  154. ("food_mgr", FoodManager("a", "b")),
  155. ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)),
  156. ]
  157. ))
  158. return self.apply_operations(app_label, ProjectState(), operations)
  159. class OperationTests(OperationTestBase):
  160. """
  161. Tests running the operations and making sure they do what they say they do.
  162. Each test looks at their state changing, and then their database operation -
  163. both forwards and backwards.
  164. """
  165. def test_create_model(self):
  166. """
  167. Tests the CreateModel operation.
  168. Most other tests use this operation as part of setup, so check failures here first.
  169. """
  170. operation = migrations.CreateModel(
  171. "Pony",
  172. [
  173. ("id", models.AutoField(primary_key=True)),
  174. ("pink", models.IntegerField(default=1)),
  175. ],
  176. )
  177. self.assertEqual(operation.describe(), "Create model Pony")
  178. # Test the state alteration
  179. project_state = ProjectState()
  180. new_state = project_state.clone()
  181. operation.state_forwards("test_crmo", new_state)
  182. self.assertEqual(new_state.models["test_crmo", "pony"].name, "Pony")
  183. self.assertEqual(len(new_state.models["test_crmo", "pony"].fields), 2)
  184. # Test the database alteration
  185. self.assertTableNotExists("test_crmo_pony")
  186. with connection.schema_editor() as editor:
  187. operation.database_forwards("test_crmo", editor, project_state, new_state)
  188. self.assertTableExists("test_crmo_pony")
  189. # And test reversal
  190. with connection.schema_editor() as editor:
  191. operation.database_backwards("test_crmo", editor, new_state, project_state)
  192. self.assertTableNotExists("test_crmo_pony")
  193. # And deconstruction
  194. definition = operation.deconstruct()
  195. self.assertEqual(definition[0], "CreateModel")
  196. self.assertEqual(definition[1], [])
  197. self.assertEqual(sorted(definition[2]), ["fields", "name"])
  198. # And default manager not in set
  199. operation = migrations.CreateModel("Foo", fields=[], managers=[("objects", models.Manager())])
  200. definition = operation.deconstruct()
  201. self.assertNotIn('managers', definition[2])
  202. def test_create_model_with_duplicate_field_name(self):
  203. with self.assertRaisesMessage(ValueError, 'Found duplicate value pink in CreateModel fields argument.'):
  204. migrations.CreateModel(
  205. "Pony",
  206. [
  207. ("id", models.AutoField(primary_key=True)),
  208. ("pink", models.TextField()),
  209. ("pink", models.IntegerField(default=1)),
  210. ],
  211. )
  212. def test_create_model_with_duplicate_base(self):
  213. message = 'Found duplicate value test_crmo.pony in CreateModel bases argument.'
  214. with self.assertRaisesMessage(ValueError, message):
  215. migrations.CreateModel(
  216. "Pony",
  217. fields=[],
  218. bases=("test_crmo.Pony", "test_crmo.Pony",),
  219. )
  220. with self.assertRaisesMessage(ValueError, message):
  221. migrations.CreateModel(
  222. "Pony",
  223. fields=[],
  224. bases=("test_crmo.Pony", "test_crmo.pony",),
  225. )
  226. message = 'Found duplicate value migrations.unicodemodel in CreateModel bases argument.'
  227. with self.assertRaisesMessage(ValueError, message):
  228. migrations.CreateModel(
  229. "Pony",
  230. fields=[],
  231. bases=(UnicodeModel, UnicodeModel,),
  232. )
  233. with self.assertRaisesMessage(ValueError, message):
  234. migrations.CreateModel(
  235. "Pony",
  236. fields=[],
  237. bases=(UnicodeModel, 'migrations.unicodemodel',),
  238. )
  239. with self.assertRaisesMessage(ValueError, message):
  240. migrations.CreateModel(
  241. "Pony",
  242. fields=[],
  243. bases=(UnicodeModel, 'migrations.UnicodeModel',),
  244. )
  245. message = "Found duplicate value <class 'django.db.models.base.Model'> in CreateModel bases argument."
  246. with self.assertRaisesMessage(ValueError, message):
  247. migrations.CreateModel(
  248. "Pony",
  249. fields=[],
  250. bases=(models.Model, models.Model,),
  251. )
  252. message = "Found duplicate value <class 'migrations.test_operations.Mixin'> in CreateModel bases argument."
  253. with self.assertRaisesMessage(ValueError, message):
  254. migrations.CreateModel(
  255. "Pony",
  256. fields=[],
  257. bases=(Mixin, Mixin,),
  258. )
  259. def test_create_model_with_duplicate_manager_name(self):
  260. with self.assertRaisesMessage(ValueError, 'Found duplicate value objects in CreateModel managers argument.'):
  261. migrations.CreateModel(
  262. "Pony",
  263. fields=[],
  264. managers=[
  265. ("objects", models.Manager()),
  266. ("objects", models.Manager()),
  267. ],
  268. )
  269. def test_create_model_with_unique_after(self):
  270. """
  271. Tests the CreateModel operation directly followed by an
  272. AlterUniqueTogether (bug #22844 - sqlite remake issues)
  273. """
  274. operation1 = migrations.CreateModel(
  275. "Pony",
  276. [
  277. ("id", models.AutoField(primary_key=True)),
  278. ("pink", models.IntegerField(default=1)),
  279. ],
  280. )
  281. operation2 = migrations.CreateModel(
  282. "Rider",
  283. [
  284. ("id", models.AutoField(primary_key=True)),
  285. ("number", models.IntegerField(default=1)),
  286. ("pony", models.ForeignKey("test_crmoua.Pony", models.CASCADE)),
  287. ],
  288. )
  289. operation3 = migrations.AlterUniqueTogether(
  290. "Rider",
  291. [
  292. ("number", "pony"),
  293. ],
  294. )
  295. # Test the database alteration
  296. project_state = ProjectState()
  297. self.assertTableNotExists("test_crmoua_pony")
  298. self.assertTableNotExists("test_crmoua_rider")
  299. with connection.schema_editor() as editor:
  300. new_state = project_state.clone()
  301. operation1.state_forwards("test_crmoua", new_state)
  302. operation1.database_forwards("test_crmoua", editor, project_state, new_state)
  303. project_state, new_state = new_state, new_state.clone()
  304. operation2.state_forwards("test_crmoua", new_state)
  305. operation2.database_forwards("test_crmoua", editor, project_state, new_state)
  306. project_state, new_state = new_state, new_state.clone()
  307. operation3.state_forwards("test_crmoua", new_state)
  308. operation3.database_forwards("test_crmoua", editor, project_state, new_state)
  309. self.assertTableExists("test_crmoua_pony")
  310. self.assertTableExists("test_crmoua_rider")
  311. def test_create_model_m2m(self):
  312. """
  313. Test the creation of a model with a ManyToMany field and the
  314. auto-created "through" model.
  315. """
  316. project_state = self.set_up_test_model("test_crmomm")
  317. operation = migrations.CreateModel(
  318. "Stable",
  319. [
  320. ("id", models.AutoField(primary_key=True)),
  321. ("ponies", models.ManyToManyField("Pony", related_name="stables"))
  322. ]
  323. )
  324. # Test the state alteration
  325. new_state = project_state.clone()
  326. operation.state_forwards("test_crmomm", new_state)
  327. # Test the database alteration
  328. self.assertTableNotExists("test_crmomm_stable_ponies")
  329. with connection.schema_editor() as editor:
  330. operation.database_forwards("test_crmomm", editor, project_state, new_state)
  331. self.assertTableExists("test_crmomm_stable")
  332. self.assertTableExists("test_crmomm_stable_ponies")
  333. self.assertColumnNotExists("test_crmomm_stable", "ponies")
  334. # Make sure the M2M field actually works
  335. with atomic():
  336. Pony = new_state.apps.get_model("test_crmomm", "Pony")
  337. Stable = new_state.apps.get_model("test_crmomm", "Stable")
  338. stable = Stable.objects.create()
  339. p1 = Pony.objects.create(pink=False, weight=4.55)
  340. p2 = Pony.objects.create(pink=True, weight=5.43)
  341. stable.ponies.add(p1, p2)
  342. self.assertEqual(stable.ponies.count(), 2)
  343. stable.ponies.all().delete()
  344. # And test reversal
  345. with connection.schema_editor() as editor:
  346. operation.database_backwards("test_crmomm", editor, new_state, project_state)
  347. self.assertTableNotExists("test_crmomm_stable")
  348. self.assertTableNotExists("test_crmomm_stable_ponies")
  349. def test_create_model_inheritance(self):
  350. """
  351. Tests the CreateModel operation on a multi-table inheritance setup.
  352. """
  353. project_state = self.set_up_test_model("test_crmoih")
  354. # Test the state alteration
  355. operation = migrations.CreateModel(
  356. "ShetlandPony",
  357. [
  358. ('pony_ptr', models.OneToOneField(
  359. 'test_crmoih.Pony',
  360. models.CASCADE,
  361. auto_created=True,
  362. primary_key=True,
  363. to_field='id',
  364. serialize=False,
  365. )),
  366. ("cuteness", models.IntegerField(default=1)),
  367. ],
  368. )
  369. new_state = project_state.clone()
  370. operation.state_forwards("test_crmoih", new_state)
  371. self.assertIn(("test_crmoih", "shetlandpony"), new_state.models)
  372. # Test the database alteration
  373. self.assertTableNotExists("test_crmoih_shetlandpony")
  374. with connection.schema_editor() as editor:
  375. operation.database_forwards("test_crmoih", editor, project_state, new_state)
  376. self.assertTableExists("test_crmoih_shetlandpony")
  377. # And test reversal
  378. with connection.schema_editor() as editor:
  379. operation.database_backwards("test_crmoih", editor, new_state, project_state)
  380. self.assertTableNotExists("test_crmoih_shetlandpony")
  381. def test_create_proxy_model(self):
  382. """
  383. CreateModel ignores proxy models.
  384. """
  385. project_state = self.set_up_test_model("test_crprmo")
  386. # Test the state alteration
  387. operation = migrations.CreateModel(
  388. "ProxyPony",
  389. [],
  390. options={"proxy": True},
  391. bases=("test_crprmo.Pony",),
  392. )
  393. self.assertEqual(operation.describe(), "Create proxy model ProxyPony")
  394. new_state = project_state.clone()
  395. operation.state_forwards("test_crprmo", new_state)
  396. self.assertIn(("test_crprmo", "proxypony"), new_state.models)
  397. # Test the database alteration
  398. self.assertTableNotExists("test_crprmo_proxypony")
  399. self.assertTableExists("test_crprmo_pony")
  400. with connection.schema_editor() as editor:
  401. operation.database_forwards("test_crprmo", editor, project_state, new_state)
  402. self.assertTableNotExists("test_crprmo_proxypony")
  403. self.assertTableExists("test_crprmo_pony")
  404. # And test reversal
  405. with connection.schema_editor() as editor:
  406. operation.database_backwards("test_crprmo", editor, new_state, project_state)
  407. self.assertTableNotExists("test_crprmo_proxypony")
  408. self.assertTableExists("test_crprmo_pony")
  409. # And deconstruction
  410. definition = operation.deconstruct()
  411. self.assertEqual(definition[0], "CreateModel")
  412. self.assertEqual(definition[1], [])
  413. self.assertEqual(sorted(definition[2]), ["bases", "fields", "name", "options"])
  414. def test_create_unmanaged_model(self):
  415. """
  416. CreateModel ignores unmanaged models.
  417. """
  418. project_state = self.set_up_test_model("test_crummo")
  419. # Test the state alteration
  420. operation = migrations.CreateModel(
  421. "UnmanagedPony",
  422. [],
  423. options={"proxy": True},
  424. bases=("test_crummo.Pony",),
  425. )
  426. self.assertEqual(operation.describe(), "Create proxy model UnmanagedPony")
  427. new_state = project_state.clone()
  428. operation.state_forwards("test_crummo", new_state)
  429. self.assertIn(("test_crummo", "unmanagedpony"), new_state.models)
  430. # Test the database alteration
  431. self.assertTableNotExists("test_crummo_unmanagedpony")
  432. self.assertTableExists("test_crummo_pony")
  433. with connection.schema_editor() as editor:
  434. operation.database_forwards("test_crummo", editor, project_state, new_state)
  435. self.assertTableNotExists("test_crummo_unmanagedpony")
  436. self.assertTableExists("test_crummo_pony")
  437. # And test reversal
  438. with connection.schema_editor() as editor:
  439. operation.database_backwards("test_crummo", editor, new_state, project_state)
  440. self.assertTableNotExists("test_crummo_unmanagedpony")
  441. self.assertTableExists("test_crummo_pony")
  442. @skipUnlessDBFeature('supports_table_check_constraints')
  443. def test_create_model_with_constraint(self):
  444. where = models.Q(pink__gt=2)
  445. check_constraint = models.CheckConstraint(check=where, name='test_constraint_pony_pink_gt_2')
  446. operation = migrations.CreateModel(
  447. "Pony",
  448. [
  449. ("id", models.AutoField(primary_key=True)),
  450. ("pink", models.IntegerField(default=3)),
  451. ],
  452. options={'constraints': [check_constraint]},
  453. )
  454. # Test the state alteration
  455. project_state = ProjectState()
  456. new_state = project_state.clone()
  457. operation.state_forwards("test_crmo", new_state)
  458. self.assertEqual(len(new_state.models['test_crmo', 'pony'].options['constraints']), 1)
  459. # Test database alteration
  460. self.assertTableNotExists("test_crmo_pony")
  461. with connection.schema_editor() as editor:
  462. operation.database_forwards("test_crmo", editor, project_state, new_state)
  463. self.assertTableExists("test_crmo_pony")
  464. with connection.cursor() as cursor:
  465. with self.assertRaises(IntegrityError):
  466. cursor.execute("INSERT INTO test_crmo_pony (id, pink) VALUES (1, 1)")
  467. # Test reversal
  468. with connection.schema_editor() as editor:
  469. operation.database_backwards("test_crmo", editor, new_state, project_state)
  470. self.assertTableNotExists("test_crmo_pony")
  471. # Test deconstruction
  472. definition = operation.deconstruct()
  473. self.assertEqual(definition[0], "CreateModel")
  474. self.assertEqual(definition[1], [])
  475. self.assertEqual(definition[2]['options']['constraints'], [check_constraint])
  476. def test_create_model_managers(self):
  477. """
  478. The managers on a model are set.
  479. """
  480. project_state = self.set_up_test_model("test_cmoma")
  481. # Test the state alteration
  482. operation = migrations.CreateModel(
  483. "Food",
  484. fields=[
  485. ("id", models.AutoField(primary_key=True)),
  486. ],
  487. managers=[
  488. ("food_qs", FoodQuerySet.as_manager()),
  489. ("food_mgr", FoodManager("a", "b")),
  490. ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)),
  491. ]
  492. )
  493. self.assertEqual(operation.describe(), "Create model Food")
  494. new_state = project_state.clone()
  495. operation.state_forwards("test_cmoma", new_state)
  496. self.assertIn(("test_cmoma", "food"), new_state.models)
  497. managers = new_state.models["test_cmoma", "food"].managers
  498. self.assertEqual(managers[0][0], "food_qs")
  499. self.assertIsInstance(managers[0][1], models.Manager)
  500. self.assertEqual(managers[1][0], "food_mgr")
  501. self.assertIsInstance(managers[1][1], FoodManager)
  502. self.assertEqual(managers[1][1].args, ("a", "b", 1, 2))
  503. self.assertEqual(managers[2][0], "food_mgr_kwargs")
  504. self.assertIsInstance(managers[2][1], FoodManager)
  505. self.assertEqual(managers[2][1].args, ("x", "y", 3, 4))
  506. def test_delete_model(self):
  507. """
  508. Tests the DeleteModel operation.
  509. """
  510. project_state = self.set_up_test_model("test_dlmo")
  511. # Test the state alteration
  512. operation = migrations.DeleteModel("Pony")
  513. self.assertEqual(operation.describe(), "Delete model Pony")
  514. new_state = project_state.clone()
  515. operation.state_forwards("test_dlmo", new_state)
  516. self.assertNotIn(("test_dlmo", "pony"), new_state.models)
  517. # Test the database alteration
  518. self.assertTableExists("test_dlmo_pony")
  519. with connection.schema_editor() as editor:
  520. operation.database_forwards("test_dlmo", editor, project_state, new_state)
  521. self.assertTableNotExists("test_dlmo_pony")
  522. # And test reversal
  523. with connection.schema_editor() as editor:
  524. operation.database_backwards("test_dlmo", editor, new_state, project_state)
  525. self.assertTableExists("test_dlmo_pony")
  526. # And deconstruction
  527. definition = operation.deconstruct()
  528. self.assertEqual(definition[0], "DeleteModel")
  529. self.assertEqual(definition[1], [])
  530. self.assertEqual(list(definition[2]), ["name"])
  531. def test_delete_proxy_model(self):
  532. """
  533. Tests the DeleteModel operation ignores proxy models.
  534. """
  535. project_state = self.set_up_test_model("test_dlprmo", proxy_model=True)
  536. # Test the state alteration
  537. operation = migrations.DeleteModel("ProxyPony")
  538. new_state = project_state.clone()
  539. operation.state_forwards("test_dlprmo", new_state)
  540. self.assertIn(("test_dlprmo", "proxypony"), project_state.models)
  541. self.assertNotIn(("test_dlprmo", "proxypony"), new_state.models)
  542. # Test the database alteration
  543. self.assertTableExists("test_dlprmo_pony")
  544. self.assertTableNotExists("test_dlprmo_proxypony")
  545. with connection.schema_editor() as editor:
  546. operation.database_forwards("test_dlprmo", editor, project_state, new_state)
  547. self.assertTableExists("test_dlprmo_pony")
  548. self.assertTableNotExists("test_dlprmo_proxypony")
  549. # And test reversal
  550. with connection.schema_editor() as editor:
  551. operation.database_backwards("test_dlprmo", editor, new_state, project_state)
  552. self.assertTableExists("test_dlprmo_pony")
  553. self.assertTableNotExists("test_dlprmo_proxypony")
  554. def test_delete_mti_model(self):
  555. project_state = self.set_up_test_model('test_dlmtimo', mti_model=True)
  556. # Test the state alteration
  557. operation = migrations.DeleteModel('ShetlandPony')
  558. new_state = project_state.clone()
  559. operation.state_forwards('test_dlmtimo', new_state)
  560. self.assertIn(('test_dlmtimo', 'shetlandpony'), project_state.models)
  561. self.assertNotIn(('test_dlmtimo', 'shetlandpony'), new_state.models)
  562. # Test the database alteration
  563. self.assertTableExists('test_dlmtimo_pony')
  564. self.assertTableExists('test_dlmtimo_shetlandpony')
  565. self.assertColumnExists('test_dlmtimo_shetlandpony', 'pony_ptr_id')
  566. with connection.schema_editor() as editor:
  567. operation.database_forwards('test_dlmtimo', editor, project_state, new_state)
  568. self.assertTableExists('test_dlmtimo_pony')
  569. self.assertTableNotExists('test_dlmtimo_shetlandpony')
  570. # And test reversal
  571. with connection.schema_editor() as editor:
  572. operation.database_backwards('test_dlmtimo', editor, new_state, project_state)
  573. self.assertTableExists('test_dlmtimo_pony')
  574. self.assertTableExists('test_dlmtimo_shetlandpony')
  575. self.assertColumnExists('test_dlmtimo_shetlandpony', 'pony_ptr_id')
  576. def test_rename_model(self):
  577. """
  578. Tests the RenameModel operation.
  579. """
  580. project_state = self.set_up_test_model("test_rnmo", related_model=True)
  581. # Test the state alteration
  582. operation = migrations.RenameModel("Pony", "Horse")
  583. self.assertEqual(operation.describe(), "Rename model Pony to Horse")
  584. # Test initial state and database
  585. self.assertIn(("test_rnmo", "pony"), project_state.models)
  586. self.assertNotIn(("test_rnmo", "horse"), project_state.models)
  587. self.assertTableExists("test_rnmo_pony")
  588. self.assertTableNotExists("test_rnmo_horse")
  589. if connection.features.supports_foreign_keys:
  590. self.assertFKExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id"))
  591. self.assertFKNotExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id"))
  592. # Migrate forwards
  593. new_state = project_state.clone()
  594. atomic_rename = connection.features.supports_atomic_references_rename
  595. new_state = self.apply_operations("test_rnmo", new_state, [operation], atomic=atomic_rename)
  596. # Test new state and database
  597. self.assertNotIn(("test_rnmo", "pony"), new_state.models)
  598. self.assertIn(("test_rnmo", "horse"), new_state.models)
  599. # RenameModel also repoints all incoming FKs and M2Ms
  600. self.assertEqual("test_rnmo.Horse", new_state.models["test_rnmo", "rider"].fields[1][1].remote_field.model)
  601. self.assertTableNotExists("test_rnmo_pony")
  602. self.assertTableExists("test_rnmo_horse")
  603. if connection.features.supports_foreign_keys:
  604. self.assertFKNotExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id"))
  605. self.assertFKExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id"))
  606. # Migrate backwards
  607. original_state = self.unapply_operations("test_rnmo", project_state, [operation], atomic=atomic_rename)
  608. # Test original state and database
  609. self.assertIn(("test_rnmo", "pony"), original_state.models)
  610. self.assertNotIn(("test_rnmo", "horse"), original_state.models)
  611. self.assertEqual("Pony", original_state.models["test_rnmo", "rider"].fields[1][1].remote_field.model)
  612. self.assertTableExists("test_rnmo_pony")
  613. self.assertTableNotExists("test_rnmo_horse")
  614. if connection.features.supports_foreign_keys:
  615. self.assertFKExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id"))
  616. self.assertFKNotExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id"))
  617. # And deconstruction
  618. definition = operation.deconstruct()
  619. self.assertEqual(definition[0], "RenameModel")
  620. self.assertEqual(definition[1], [])
  621. self.assertEqual(definition[2], {'old_name': "Pony", 'new_name': "Horse"})
  622. def test_rename_model_state_forwards(self):
  623. """
  624. RenameModel operations shouldn't trigger the caching of rendered apps
  625. on state without prior apps.
  626. """
  627. state = ProjectState()
  628. state.add_model(ModelState('migrations', 'Foo', []))
  629. operation = migrations.RenameModel('Foo', 'Bar')
  630. operation.state_forwards('migrations', state)
  631. self.assertNotIn('apps', state.__dict__)
  632. self.assertNotIn(('migrations', 'foo'), state.models)
  633. self.assertIn(('migrations', 'bar'), state.models)
  634. # Now with apps cached.
  635. apps = state.apps
  636. operation = migrations.RenameModel('Bar', 'Foo')
  637. operation.state_forwards('migrations', state)
  638. self.assertIs(state.apps, apps)
  639. self.assertNotIn(('migrations', 'bar'), state.models)
  640. self.assertIn(('migrations', 'foo'), state.models)
  641. def test_rename_model_with_self_referential_fk(self):
  642. """
  643. Tests the RenameModel operation on model with self referential FK.
  644. """
  645. project_state = self.set_up_test_model("test_rmwsrf", related_model=True)
  646. # Test the state alteration
  647. operation = migrations.RenameModel("Rider", "HorseRider")
  648. self.assertEqual(operation.describe(), "Rename model Rider to HorseRider")
  649. new_state = project_state.clone()
  650. operation.state_forwards("test_rmwsrf", new_state)
  651. self.assertNotIn(("test_rmwsrf", "rider"), new_state.models)
  652. self.assertIn(("test_rmwsrf", "horserider"), new_state.models)
  653. # Remember, RenameModel also repoints all incoming FKs and M2Ms
  654. self.assertEqual(
  655. 'self',
  656. new_state.models["test_rmwsrf", "horserider"].fields[2][1].remote_field.model
  657. )
  658. HorseRider = new_state.apps.get_model('test_rmwsrf', 'horserider')
  659. self.assertIs(HorseRider._meta.get_field('horserider').remote_field.model, HorseRider)
  660. # Test the database alteration
  661. self.assertTableExists("test_rmwsrf_rider")
  662. self.assertTableNotExists("test_rmwsrf_horserider")
  663. if connection.features.supports_foreign_keys:
  664. self.assertFKExists("test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id"))
  665. self.assertFKNotExists("test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id"))
  666. atomic_rename = connection.features.supports_atomic_references_rename
  667. with connection.schema_editor(atomic=atomic_rename) as editor:
  668. operation.database_forwards("test_rmwsrf", editor, project_state, new_state)
  669. self.assertTableNotExists("test_rmwsrf_rider")
  670. self.assertTableExists("test_rmwsrf_horserider")
  671. if connection.features.supports_foreign_keys:
  672. self.assertFKNotExists("test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_rider", "id"))
  673. self.assertFKExists("test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_horserider", "id"))
  674. # And test reversal
  675. with connection.schema_editor(atomic=atomic_rename) as editor:
  676. operation.database_backwards("test_rmwsrf", editor, new_state, project_state)
  677. self.assertTableExists("test_rmwsrf_rider")
  678. self.assertTableNotExists("test_rmwsrf_horserider")
  679. if connection.features.supports_foreign_keys:
  680. self.assertFKExists("test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id"))
  681. self.assertFKNotExists("test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id"))
  682. def test_rename_model_with_superclass_fk(self):
  683. """
  684. Tests the RenameModel operation on a model which has a superclass that
  685. has a foreign key.
  686. """
  687. project_state = self.set_up_test_model("test_rmwsc", related_model=True, mti_model=True)
  688. # Test the state alteration
  689. operation = migrations.RenameModel("ShetlandPony", "LittleHorse")
  690. self.assertEqual(operation.describe(), "Rename model ShetlandPony to LittleHorse")
  691. new_state = project_state.clone()
  692. operation.state_forwards("test_rmwsc", new_state)
  693. self.assertNotIn(("test_rmwsc", "shetlandpony"), new_state.models)
  694. self.assertIn(("test_rmwsc", "littlehorse"), new_state.models)
  695. # RenameModel shouldn't repoint the superclass's relations, only local ones
  696. self.assertEqual(
  697. project_state.models["test_rmwsc", "rider"].fields[1][1].remote_field.model,
  698. new_state.models["test_rmwsc", "rider"].fields[1][1].remote_field.model
  699. )
  700. # Before running the migration we have a table for Shetland Pony, not Little Horse
  701. self.assertTableExists("test_rmwsc_shetlandpony")
  702. self.assertTableNotExists("test_rmwsc_littlehorse")
  703. if connection.features.supports_foreign_keys:
  704. # and the foreign key on rider points to pony, not shetland pony
  705. self.assertFKExists("test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id"))
  706. self.assertFKNotExists("test_rmwsc_rider", ["pony_id"], ("test_rmwsc_shetlandpony", "id"))
  707. with connection.schema_editor(atomic=connection.features.supports_atomic_references_rename) as editor:
  708. operation.database_forwards("test_rmwsc", editor, project_state, new_state)
  709. # Now we have a little horse table, not shetland pony
  710. self.assertTableNotExists("test_rmwsc_shetlandpony")
  711. self.assertTableExists("test_rmwsc_littlehorse")
  712. if connection.features.supports_foreign_keys:
  713. # but the Foreign keys still point at pony, not little horse
  714. self.assertFKExists("test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id"))
  715. self.assertFKNotExists("test_rmwsc_rider", ["pony_id"], ("test_rmwsc_littlehorse", "id"))
  716. def test_rename_model_with_self_referential_m2m(self):
  717. app_label = "test_rename_model_with_self_referential_m2m"
  718. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  719. migrations.CreateModel("ReflexivePony", fields=[
  720. ("id", models.AutoField(primary_key=True)),
  721. ("ponies", models.ManyToManyField("self")),
  722. ]),
  723. ])
  724. project_state = self.apply_operations(app_label, project_state, operations=[
  725. migrations.RenameModel("ReflexivePony", "ReflexivePony2"),
  726. ], atomic=connection.features.supports_atomic_references_rename)
  727. Pony = project_state.apps.get_model(app_label, "ReflexivePony2")
  728. pony = Pony.objects.create()
  729. pony.ponies.add(pony)
  730. def test_rename_model_with_m2m(self):
  731. app_label = "test_rename_model_with_m2m"
  732. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  733. migrations.CreateModel("Rider", fields=[
  734. ("id", models.AutoField(primary_key=True)),
  735. ]),
  736. migrations.CreateModel("Pony", fields=[
  737. ("id", models.AutoField(primary_key=True)),
  738. ("riders", models.ManyToManyField("Rider")),
  739. ]),
  740. ])
  741. Pony = project_state.apps.get_model(app_label, "Pony")
  742. Rider = project_state.apps.get_model(app_label, "Rider")
  743. pony = Pony.objects.create()
  744. rider = Rider.objects.create()
  745. pony.riders.add(rider)
  746. project_state = self.apply_operations(app_label, project_state, operations=[
  747. migrations.RenameModel("Pony", "Pony2"),
  748. ], atomic=connection.features.supports_atomic_references_rename)
  749. Pony = project_state.apps.get_model(app_label, "Pony2")
  750. Rider = project_state.apps.get_model(app_label, "Rider")
  751. pony = Pony.objects.create()
  752. rider = Rider.objects.create()
  753. pony.riders.add(rider)
  754. self.assertEqual(Pony.objects.count(), 2)
  755. self.assertEqual(Rider.objects.count(), 2)
  756. self.assertEqual(Pony._meta.get_field('riders').remote_field.through.objects.count(), 2)
  757. def test_rename_m2m_target_model(self):
  758. app_label = "test_rename_m2m_target_model"
  759. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  760. migrations.CreateModel("Rider", fields=[
  761. ("id", models.AutoField(primary_key=True)),
  762. ]),
  763. migrations.CreateModel("Pony", fields=[
  764. ("id", models.AutoField(primary_key=True)),
  765. ("riders", models.ManyToManyField("Rider")),
  766. ]),
  767. ])
  768. Pony = project_state.apps.get_model(app_label, "Pony")
  769. Rider = project_state.apps.get_model(app_label, "Rider")
  770. pony = Pony.objects.create()
  771. rider = Rider.objects.create()
  772. pony.riders.add(rider)
  773. project_state = self.apply_operations(app_label, project_state, operations=[
  774. migrations.RenameModel("Rider", "Rider2"),
  775. ], atomic=connection.features.supports_atomic_references_rename)
  776. Pony = project_state.apps.get_model(app_label, "Pony")
  777. Rider = project_state.apps.get_model(app_label, "Rider2")
  778. pony = Pony.objects.create()
  779. rider = Rider.objects.create()
  780. pony.riders.add(rider)
  781. self.assertEqual(Pony.objects.count(), 2)
  782. self.assertEqual(Rider.objects.count(), 2)
  783. self.assertEqual(Pony._meta.get_field('riders').remote_field.through.objects.count(), 2)
  784. def test_rename_m2m_through_model(self):
  785. app_label = "test_rename_through"
  786. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  787. migrations.CreateModel("Rider", fields=[
  788. ("id", models.AutoField(primary_key=True)),
  789. ]),
  790. migrations.CreateModel("Pony", fields=[
  791. ("id", models.AutoField(primary_key=True)),
  792. ]),
  793. migrations.CreateModel("PonyRider", fields=[
  794. ("id", models.AutoField(primary_key=True)),
  795. ("rider", models.ForeignKey("test_rename_through.Rider", models.CASCADE)),
  796. ("pony", models.ForeignKey("test_rename_through.Pony", models.CASCADE)),
  797. ]),
  798. migrations.AddField(
  799. "Pony",
  800. "riders",
  801. models.ManyToManyField("test_rename_through.Rider", through="test_rename_through.PonyRider"),
  802. ),
  803. ])
  804. Pony = project_state.apps.get_model(app_label, "Pony")
  805. Rider = project_state.apps.get_model(app_label, "Rider")
  806. PonyRider = project_state.apps.get_model(app_label, "PonyRider")
  807. pony = Pony.objects.create()
  808. rider = Rider.objects.create()
  809. PonyRider.objects.create(pony=pony, rider=rider)
  810. project_state = self.apply_operations(app_label, project_state, operations=[
  811. migrations.RenameModel("PonyRider", "PonyRider2"),
  812. ])
  813. Pony = project_state.apps.get_model(app_label, "Pony")
  814. Rider = project_state.apps.get_model(app_label, "Rider")
  815. PonyRider = project_state.apps.get_model(app_label, "PonyRider2")
  816. pony = Pony.objects.first()
  817. rider = Rider.objects.create()
  818. PonyRider.objects.create(pony=pony, rider=rider)
  819. self.assertEqual(Pony.objects.count(), 1)
  820. self.assertEqual(Rider.objects.count(), 2)
  821. self.assertEqual(PonyRider.objects.count(), 2)
  822. self.assertEqual(pony.riders.count(), 2)
  823. def test_rename_m2m_model_after_rename_field(self):
  824. """RenameModel renames a many-to-many column after a RenameField."""
  825. app_label = 'test_rename_multiple'
  826. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  827. migrations.CreateModel('Pony', fields=[
  828. ('id', models.AutoField(primary_key=True)),
  829. ('name', models.CharField(max_length=20)),
  830. ]),
  831. migrations.CreateModel('Rider', fields=[
  832. ('id', models.AutoField(primary_key=True)),
  833. ('pony', models.ForeignKey('test_rename_multiple.Pony', models.CASCADE)),
  834. ]),
  835. migrations.CreateModel('PonyRider', fields=[
  836. ('id', models.AutoField(primary_key=True)),
  837. ('riders', models.ManyToManyField('Rider')),
  838. ]),
  839. migrations.RenameField(model_name='pony', old_name='name', new_name='fancy_name'),
  840. migrations.RenameModel(old_name='Rider', new_name='Jockey'),
  841. ], atomic=connection.features.supports_atomic_references_rename)
  842. Pony = project_state.apps.get_model(app_label, 'Pony')
  843. Jockey = project_state.apps.get_model(app_label, 'Jockey')
  844. PonyRider = project_state.apps.get_model(app_label, 'PonyRider')
  845. # No "no such column" error means the column was renamed correctly.
  846. pony = Pony.objects.create(fancy_name='a good name')
  847. jockey = Jockey.objects.create(pony=pony)
  848. ponyrider = PonyRider.objects.create()
  849. ponyrider.riders.add(jockey)
  850. def test_add_field(self):
  851. """
  852. Tests the AddField operation.
  853. """
  854. # Test the state alteration
  855. operation = migrations.AddField(
  856. "Pony",
  857. "height",
  858. models.FloatField(null=True, default=5),
  859. )
  860. self.assertEqual(operation.describe(), "Add field height to Pony")
  861. project_state, new_state = self.make_test_state("test_adfl", operation)
  862. self.assertEqual(len(new_state.models["test_adfl", "pony"].fields), 4)
  863. field = [
  864. f for n, f in new_state.models["test_adfl", "pony"].fields
  865. if n == "height"
  866. ][0]
  867. self.assertEqual(field.default, 5)
  868. # Test the database alteration
  869. self.assertColumnNotExists("test_adfl_pony", "height")
  870. with connection.schema_editor() as editor:
  871. operation.database_forwards("test_adfl", editor, project_state, new_state)
  872. self.assertColumnExists("test_adfl_pony", "height")
  873. # And test reversal
  874. with connection.schema_editor() as editor:
  875. operation.database_backwards("test_adfl", editor, new_state, project_state)
  876. self.assertColumnNotExists("test_adfl_pony", "height")
  877. # And deconstruction
  878. definition = operation.deconstruct()
  879. self.assertEqual(definition[0], "AddField")
  880. self.assertEqual(definition[1], [])
  881. self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"])
  882. def test_add_charfield(self):
  883. """
  884. Tests the AddField operation on TextField.
  885. """
  886. project_state = self.set_up_test_model("test_adchfl")
  887. Pony = project_state.apps.get_model("test_adchfl", "Pony")
  888. pony = Pony.objects.create(weight=42)
  889. new_state = self.apply_operations("test_adchfl", project_state, [
  890. migrations.AddField(
  891. "Pony",
  892. "text",
  893. models.CharField(max_length=10, default="some text"),
  894. ),
  895. migrations.AddField(
  896. "Pony",
  897. "empty",
  898. models.CharField(max_length=10, default=""),
  899. ),
  900. # If not properly quoted digits would be interpreted as an int.
  901. migrations.AddField(
  902. "Pony",
  903. "digits",
  904. models.CharField(max_length=10, default="42"),
  905. ),
  906. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  907. migrations.AddField(
  908. "Pony",
  909. "quotes",
  910. models.CharField(max_length=10, default='"\'"'),
  911. ),
  912. ])
  913. Pony = new_state.apps.get_model("test_adchfl", "Pony")
  914. pony = Pony.objects.get(pk=pony.pk)
  915. self.assertEqual(pony.text, "some text")
  916. self.assertEqual(pony.empty, "")
  917. self.assertEqual(pony.digits, "42")
  918. self.assertEqual(pony.quotes, '"\'"')
  919. def test_add_textfield(self):
  920. """
  921. Tests the AddField operation on TextField.
  922. """
  923. project_state = self.set_up_test_model("test_adtxtfl")
  924. Pony = project_state.apps.get_model("test_adtxtfl", "Pony")
  925. pony = Pony.objects.create(weight=42)
  926. new_state = self.apply_operations("test_adtxtfl", project_state, [
  927. migrations.AddField(
  928. "Pony",
  929. "text",
  930. models.TextField(default="some text"),
  931. ),
  932. migrations.AddField(
  933. "Pony",
  934. "empty",
  935. models.TextField(default=""),
  936. ),
  937. # If not properly quoted digits would be interpreted as an int.
  938. migrations.AddField(
  939. "Pony",
  940. "digits",
  941. models.TextField(default="42"),
  942. ),
  943. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  944. migrations.AddField(
  945. "Pony",
  946. "quotes",
  947. models.TextField(default='"\'"'),
  948. ),
  949. ])
  950. Pony = new_state.apps.get_model("test_adtxtfl", "Pony")
  951. pony = Pony.objects.get(pk=pony.pk)
  952. self.assertEqual(pony.text, "some text")
  953. self.assertEqual(pony.empty, "")
  954. self.assertEqual(pony.digits, "42")
  955. self.assertEqual(pony.quotes, '"\'"')
  956. def test_add_binaryfield(self):
  957. """
  958. Tests the AddField operation on TextField/BinaryField.
  959. """
  960. project_state = self.set_up_test_model("test_adbinfl")
  961. Pony = project_state.apps.get_model("test_adbinfl", "Pony")
  962. pony = Pony.objects.create(weight=42)
  963. new_state = self.apply_operations("test_adbinfl", project_state, [
  964. migrations.AddField(
  965. "Pony",
  966. "blob",
  967. models.BinaryField(default=b"some text"),
  968. ),
  969. migrations.AddField(
  970. "Pony",
  971. "empty",
  972. models.BinaryField(default=b""),
  973. ),
  974. # If not properly quoted digits would be interpreted as an int.
  975. migrations.AddField(
  976. "Pony",
  977. "digits",
  978. models.BinaryField(default=b"42"),
  979. ),
  980. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  981. migrations.AddField(
  982. "Pony",
  983. "quotes",
  984. models.BinaryField(default=b'"\'"'),
  985. ),
  986. ])
  987. Pony = new_state.apps.get_model("test_adbinfl", "Pony")
  988. pony = Pony.objects.get(pk=pony.pk)
  989. # SQLite returns buffer/memoryview, cast to bytes for checking.
  990. self.assertEqual(bytes(pony.blob), b"some text")
  991. self.assertEqual(bytes(pony.empty), b"")
  992. self.assertEqual(bytes(pony.digits), b"42")
  993. self.assertEqual(bytes(pony.quotes), b'"\'"')
  994. def test_column_name_quoting(self):
  995. """
  996. Column names that are SQL keywords shouldn't cause problems when used
  997. in migrations (#22168).
  998. """
  999. project_state = self.set_up_test_model("test_regr22168")
  1000. operation = migrations.AddField(
  1001. "Pony",
  1002. "order",
  1003. models.IntegerField(default=0),
  1004. )
  1005. new_state = project_state.clone()
  1006. operation.state_forwards("test_regr22168", new_state)
  1007. with connection.schema_editor() as editor:
  1008. operation.database_forwards("test_regr22168", editor, project_state, new_state)
  1009. self.assertColumnExists("test_regr22168_pony", "order")
  1010. def test_add_field_preserve_default(self):
  1011. """
  1012. Tests the AddField operation's state alteration
  1013. when preserve_default = False.
  1014. """
  1015. project_state = self.set_up_test_model("test_adflpd")
  1016. # Test the state alteration
  1017. operation = migrations.AddField(
  1018. "Pony",
  1019. "height",
  1020. models.FloatField(null=True, default=4),
  1021. preserve_default=False,
  1022. )
  1023. new_state = project_state.clone()
  1024. operation.state_forwards("test_adflpd", new_state)
  1025. self.assertEqual(len(new_state.models["test_adflpd", "pony"].fields), 4)
  1026. field = [
  1027. f for n, f in new_state.models["test_adflpd", "pony"].fields
  1028. if n == "height"
  1029. ][0]
  1030. self.assertEqual(field.default, NOT_PROVIDED)
  1031. # Test the database alteration
  1032. project_state.apps.get_model("test_adflpd", "pony").objects.create(
  1033. weight=4,
  1034. )
  1035. self.assertColumnNotExists("test_adflpd_pony", "height")
  1036. with connection.schema_editor() as editor:
  1037. operation.database_forwards("test_adflpd", editor, project_state, new_state)
  1038. self.assertColumnExists("test_adflpd_pony", "height")
  1039. # And deconstruction
  1040. definition = operation.deconstruct()
  1041. self.assertEqual(definition[0], "AddField")
  1042. self.assertEqual(definition[1], [])
  1043. self.assertEqual(sorted(definition[2]), ["field", "model_name", "name", "preserve_default"])
  1044. def test_add_field_m2m(self):
  1045. """
  1046. Tests the AddField operation with a ManyToManyField.
  1047. """
  1048. project_state = self.set_up_test_model("test_adflmm", second_model=True)
  1049. # Test the state alteration
  1050. operation = migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
  1051. new_state = project_state.clone()
  1052. operation.state_forwards("test_adflmm", new_state)
  1053. self.assertEqual(len(new_state.models["test_adflmm", "pony"].fields), 4)
  1054. # Test the database alteration
  1055. self.assertTableNotExists("test_adflmm_pony_stables")
  1056. with connection.schema_editor() as editor:
  1057. operation.database_forwards("test_adflmm", editor, project_state, new_state)
  1058. self.assertTableExists("test_adflmm_pony_stables")
  1059. self.assertColumnNotExists("test_adflmm_pony", "stables")
  1060. # Make sure the M2M field actually works
  1061. with atomic():
  1062. Pony = new_state.apps.get_model("test_adflmm", "Pony")
  1063. p = Pony.objects.create(pink=False, weight=4.55)
  1064. p.stables.create()
  1065. self.assertEqual(p.stables.count(), 1)
  1066. p.stables.all().delete()
  1067. # And test reversal
  1068. with connection.schema_editor() as editor:
  1069. operation.database_backwards("test_adflmm", editor, new_state, project_state)
  1070. self.assertTableNotExists("test_adflmm_pony_stables")
  1071. def test_alter_field_m2m(self):
  1072. project_state = self.set_up_test_model("test_alflmm", second_model=True)
  1073. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  1074. migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
  1075. ])
  1076. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1077. self.assertFalse(Pony._meta.get_field('stables').blank)
  1078. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  1079. migrations.AlterField(
  1080. "Pony", "stables", models.ManyToManyField(to="Stable", related_name="ponies", blank=True)
  1081. )
  1082. ])
  1083. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1084. self.assertTrue(Pony._meta.get_field('stables').blank)
  1085. def test_repoint_field_m2m(self):
  1086. project_state = self.set_up_test_model("test_alflmm", second_model=True, third_model=True)
  1087. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  1088. migrations.AddField("Pony", "places", models.ManyToManyField("Stable", related_name="ponies"))
  1089. ])
  1090. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1091. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  1092. migrations.AlterField("Pony", "places", models.ManyToManyField(to="Van", related_name="ponies"))
  1093. ])
  1094. # Ensure the new field actually works
  1095. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1096. p = Pony.objects.create(pink=False, weight=4.55)
  1097. p.places.create()
  1098. self.assertEqual(p.places.count(), 1)
  1099. p.places.all().delete()
  1100. def test_remove_field_m2m(self):
  1101. project_state = self.set_up_test_model("test_rmflmm", second_model=True)
  1102. project_state = self.apply_operations("test_rmflmm", project_state, operations=[
  1103. migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
  1104. ])
  1105. self.assertTableExists("test_rmflmm_pony_stables")
  1106. with_field_state = project_state.clone()
  1107. operations = [migrations.RemoveField("Pony", "stables")]
  1108. project_state = self.apply_operations("test_rmflmm", project_state, operations=operations)
  1109. self.assertTableNotExists("test_rmflmm_pony_stables")
  1110. # And test reversal
  1111. self.unapply_operations("test_rmflmm", with_field_state, operations=operations)
  1112. self.assertTableExists("test_rmflmm_pony_stables")
  1113. def test_remove_field_m2m_with_through(self):
  1114. project_state = self.set_up_test_model("test_rmflmmwt", second_model=True)
  1115. self.assertTableNotExists("test_rmflmmwt_ponystables")
  1116. project_state = self.apply_operations("test_rmflmmwt", project_state, operations=[
  1117. migrations.CreateModel("PonyStables", fields=[
  1118. ("pony", models.ForeignKey('test_rmflmmwt.Pony', models.CASCADE)),
  1119. ("stable", models.ForeignKey('test_rmflmmwt.Stable', models.CASCADE)),
  1120. ]),
  1121. migrations.AddField(
  1122. "Pony", "stables",
  1123. models.ManyToManyField("Stable", related_name="ponies", through='test_rmflmmwt.PonyStables')
  1124. )
  1125. ])
  1126. self.assertTableExists("test_rmflmmwt_ponystables")
  1127. operations = [migrations.RemoveField("Pony", "stables"), migrations.DeleteModel("PonyStables")]
  1128. self.apply_operations("test_rmflmmwt", project_state, operations=operations)
  1129. def test_remove_field(self):
  1130. """
  1131. Tests the RemoveField operation.
  1132. """
  1133. project_state = self.set_up_test_model("test_rmfl")
  1134. # Test the state alteration
  1135. operation = migrations.RemoveField("Pony", "pink")
  1136. self.assertEqual(operation.describe(), "Remove field pink from Pony")
  1137. new_state = project_state.clone()
  1138. operation.state_forwards("test_rmfl", new_state)
  1139. self.assertEqual(len(new_state.models["test_rmfl", "pony"].fields), 2)
  1140. # Test the database alteration
  1141. self.assertColumnExists("test_rmfl_pony", "pink")
  1142. with connection.schema_editor() as editor:
  1143. operation.database_forwards("test_rmfl", editor, project_state, new_state)
  1144. self.assertColumnNotExists("test_rmfl_pony", "pink")
  1145. # And test reversal
  1146. with connection.schema_editor() as editor:
  1147. operation.database_backwards("test_rmfl", editor, new_state, project_state)
  1148. self.assertColumnExists("test_rmfl_pony", "pink")
  1149. # And deconstruction
  1150. definition = operation.deconstruct()
  1151. self.assertEqual(definition[0], "RemoveField")
  1152. self.assertEqual(definition[1], [])
  1153. self.assertEqual(definition[2], {'model_name': "Pony", 'name': 'pink'})
  1154. def test_remove_fk(self):
  1155. """
  1156. Tests the RemoveField operation on a foreign key.
  1157. """
  1158. project_state = self.set_up_test_model("test_rfk", related_model=True)
  1159. self.assertColumnExists("test_rfk_rider", "pony_id")
  1160. operation = migrations.RemoveField("Rider", "pony")
  1161. new_state = project_state.clone()
  1162. operation.state_forwards("test_rfk", new_state)
  1163. with connection.schema_editor() as editor:
  1164. operation.database_forwards("test_rfk", editor, project_state, new_state)
  1165. self.assertColumnNotExists("test_rfk_rider", "pony_id")
  1166. with connection.schema_editor() as editor:
  1167. operation.database_backwards("test_rfk", editor, new_state, project_state)
  1168. self.assertColumnExists("test_rfk_rider", "pony_id")
  1169. def test_alter_model_table(self):
  1170. """
  1171. Tests the AlterModelTable operation.
  1172. """
  1173. project_state = self.set_up_test_model("test_almota")
  1174. # Test the state alteration
  1175. operation = migrations.AlterModelTable("Pony", "test_almota_pony_2")
  1176. self.assertEqual(operation.describe(), "Rename table for Pony to test_almota_pony_2")
  1177. new_state = project_state.clone()
  1178. operation.state_forwards("test_almota", new_state)
  1179. self.assertEqual(new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony_2")
  1180. # Test the database alteration
  1181. self.assertTableExists("test_almota_pony")
  1182. self.assertTableNotExists("test_almota_pony_2")
  1183. with connection.schema_editor() as editor:
  1184. operation.database_forwards("test_almota", editor, project_state, new_state)
  1185. self.assertTableNotExists("test_almota_pony")
  1186. self.assertTableExists("test_almota_pony_2")
  1187. # And test reversal
  1188. with connection.schema_editor() as editor:
  1189. operation.database_backwards("test_almota", editor, new_state, project_state)
  1190. self.assertTableExists("test_almota_pony")
  1191. self.assertTableNotExists("test_almota_pony_2")
  1192. # And deconstruction
  1193. definition = operation.deconstruct()
  1194. self.assertEqual(definition[0], "AlterModelTable")
  1195. self.assertEqual(definition[1], [])
  1196. self.assertEqual(definition[2], {'name': "Pony", 'table': "test_almota_pony_2"})
  1197. def test_alter_model_table_none(self):
  1198. """
  1199. Tests the AlterModelTable operation if the table name is set to None.
  1200. """
  1201. operation = migrations.AlterModelTable("Pony", None)
  1202. self.assertEqual(operation.describe(), "Rename table for Pony to (default)")
  1203. def test_alter_model_table_noop(self):
  1204. """
  1205. Tests the AlterModelTable operation if the table name is not changed.
  1206. """
  1207. project_state = self.set_up_test_model("test_almota")
  1208. # Test the state alteration
  1209. operation = migrations.AlterModelTable("Pony", "test_almota_pony")
  1210. new_state = project_state.clone()
  1211. operation.state_forwards("test_almota", new_state)
  1212. self.assertEqual(new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony")
  1213. # Test the database alteration
  1214. self.assertTableExists("test_almota_pony")
  1215. with connection.schema_editor() as editor:
  1216. operation.database_forwards("test_almota", editor, project_state, new_state)
  1217. self.assertTableExists("test_almota_pony")
  1218. # And test reversal
  1219. with connection.schema_editor() as editor:
  1220. operation.database_backwards("test_almota", editor, new_state, project_state)
  1221. self.assertTableExists("test_almota_pony")
  1222. def test_alter_model_table_m2m(self):
  1223. """
  1224. AlterModelTable should rename auto-generated M2M tables.
  1225. """
  1226. app_label = "test_talflmltlm2m"
  1227. pony_db_table = 'pony_foo'
  1228. project_state = self.set_up_test_model(app_label, second_model=True, db_table=pony_db_table)
  1229. # Add the M2M field
  1230. first_state = project_state.clone()
  1231. operation = migrations.AddField("Pony", "stables", models.ManyToManyField("Stable"))
  1232. operation.state_forwards(app_label, first_state)
  1233. with connection.schema_editor() as editor:
  1234. operation.database_forwards(app_label, editor, project_state, first_state)
  1235. original_m2m_table = "%s_%s" % (pony_db_table, "stables")
  1236. new_m2m_table = "%s_%s" % (app_label, "pony_stables")
  1237. self.assertTableExists(original_m2m_table)
  1238. self.assertTableNotExists(new_m2m_table)
  1239. # Rename the Pony db_table which should also rename the m2m table.
  1240. second_state = first_state.clone()
  1241. operation = migrations.AlterModelTable(name='pony', table=None)
  1242. operation.state_forwards(app_label, second_state)
  1243. atomic_rename = connection.features.supports_atomic_references_rename
  1244. with connection.schema_editor(atomic=atomic_rename) as editor:
  1245. operation.database_forwards(app_label, editor, first_state, second_state)
  1246. self.assertTableExists(new_m2m_table)
  1247. self.assertTableNotExists(original_m2m_table)
  1248. # And test reversal
  1249. with connection.schema_editor(atomic=atomic_rename) as editor:
  1250. operation.database_backwards(app_label, editor, second_state, first_state)
  1251. self.assertTableExists(original_m2m_table)
  1252. self.assertTableNotExists(new_m2m_table)
  1253. def test_alter_field(self):
  1254. """
  1255. Tests the AlterField operation.
  1256. """
  1257. project_state = self.set_up_test_model("test_alfl")
  1258. # Test the state alteration
  1259. operation = migrations.AlterField("Pony", "pink", models.IntegerField(null=True))
  1260. self.assertEqual(operation.describe(), "Alter field pink on Pony")
  1261. new_state = project_state.clone()
  1262. operation.state_forwards("test_alfl", new_state)
  1263. self.assertIs(project_state.models["test_alfl", "pony"].get_field_by_name("pink").null, False)
  1264. self.assertIs(new_state.models["test_alfl", "pony"].get_field_by_name("pink").null, True)
  1265. # Test the database alteration
  1266. self.assertColumnNotNull("test_alfl_pony", "pink")
  1267. with connection.schema_editor() as editor:
  1268. operation.database_forwards("test_alfl", editor, project_state, new_state)
  1269. self.assertColumnNull("test_alfl_pony", "pink")
  1270. # And test reversal
  1271. with connection.schema_editor() as editor:
  1272. operation.database_backwards("test_alfl", editor, new_state, project_state)
  1273. self.assertColumnNotNull("test_alfl_pony", "pink")
  1274. # And deconstruction
  1275. definition = operation.deconstruct()
  1276. self.assertEqual(definition[0], "AlterField")
  1277. self.assertEqual(definition[1], [])
  1278. self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"])
  1279. def test_alter_field_pk(self):
  1280. """
  1281. Tests the AlterField operation on primary keys (for things like PostgreSQL's SERIAL weirdness)
  1282. """
  1283. project_state = self.set_up_test_model("test_alflpk")
  1284. # Test the state alteration
  1285. operation = migrations.AlterField("Pony", "id", models.IntegerField(primary_key=True))
  1286. new_state = project_state.clone()
  1287. operation.state_forwards("test_alflpk", new_state)
  1288. self.assertIsInstance(project_state.models["test_alflpk", "pony"].get_field_by_name("id"), models.AutoField)
  1289. self.assertIsInstance(new_state.models["test_alflpk", "pony"].get_field_by_name("id"), models.IntegerField)
  1290. # Test the database alteration
  1291. with connection.schema_editor() as editor:
  1292. operation.database_forwards("test_alflpk", editor, project_state, new_state)
  1293. # And test reversal
  1294. with connection.schema_editor() as editor:
  1295. operation.database_backwards("test_alflpk", editor, new_state, project_state)
  1296. @skipUnlessDBFeature('supports_foreign_keys')
  1297. def test_alter_field_pk_fk(self):
  1298. """
  1299. Tests the AlterField operation on primary keys changes any FKs pointing to it.
  1300. """
  1301. project_state = self.set_up_test_model("test_alflpkfk", related_model=True)
  1302. # Test the state alteration
  1303. operation = migrations.AlterField("Pony", "id", models.FloatField(primary_key=True))
  1304. new_state = project_state.clone()
  1305. operation.state_forwards("test_alflpkfk", new_state)
  1306. self.assertIsInstance(project_state.models["test_alflpkfk", "pony"].get_field_by_name("id"), models.AutoField)
  1307. self.assertIsInstance(new_state.models["test_alflpkfk", "pony"].get_field_by_name("id"), models.FloatField)
  1308. def assertIdTypeEqualsFkType():
  1309. with connection.cursor() as cursor:
  1310. id_type, id_null = [
  1311. (c.type_code, c.null_ok)
  1312. for c in connection.introspection.get_table_description(cursor, "test_alflpkfk_pony")
  1313. if c.name == "id"
  1314. ][0]
  1315. fk_type, fk_null = [
  1316. (c.type_code, c.null_ok)
  1317. for c in connection.introspection.get_table_description(cursor, "test_alflpkfk_rider")
  1318. if c.name == "pony_id"
  1319. ][0]
  1320. self.assertEqual(id_type, fk_type)
  1321. self.assertEqual(id_null, fk_null)
  1322. assertIdTypeEqualsFkType()
  1323. # Test the database alteration
  1324. with connection.schema_editor() as editor:
  1325. operation.database_forwards("test_alflpkfk", editor, project_state, new_state)
  1326. assertIdTypeEqualsFkType()
  1327. # And test reversal
  1328. with connection.schema_editor() as editor:
  1329. operation.database_backwards("test_alflpkfk", editor, new_state, project_state)
  1330. assertIdTypeEqualsFkType()
  1331. def test_alter_field_reloads_state_on_fk_target_changes(self):
  1332. """
  1333. If AlterField doesn't reload state appropriately, the second AlterField
  1334. crashes on MySQL due to not dropping the PonyRider.pony foreign key
  1335. constraint before modifying the column.
  1336. """
  1337. app_label = 'alter_alter_field_reloads_state_on_fk_target_changes'
  1338. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  1339. migrations.CreateModel('Rider', fields=[
  1340. ('id', models.CharField(primary_key=True, max_length=100)),
  1341. ]),
  1342. migrations.CreateModel('Pony', fields=[
  1343. ('id', models.CharField(primary_key=True, max_length=100)),
  1344. ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE)),
  1345. ]),
  1346. migrations.CreateModel('PonyRider', fields=[
  1347. ('id', models.AutoField(primary_key=True)),
  1348. ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE)),
  1349. ]),
  1350. ])
  1351. project_state = self.apply_operations(app_label, project_state, operations=[
  1352. migrations.AlterField('Rider', 'id', models.CharField(primary_key=True, max_length=99)),
  1353. migrations.AlterField('Pony', 'id', models.CharField(primary_key=True, max_length=99)),
  1354. ])
  1355. def test_alter_field_reloads_state_on_fk_with_to_field_target_changes(self):
  1356. """
  1357. If AlterField doesn't reload state appropriately, the second AlterField
  1358. crashes on MySQL due to not dropping the PonyRider.pony foreign key
  1359. constraint before modifying the column.
  1360. """
  1361. app_label = 'alter_alter_field_reloads_state_on_fk_with_to_field_target_changes'
  1362. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  1363. migrations.CreateModel('Rider', fields=[
  1364. ('id', models.CharField(primary_key=True, max_length=100)),
  1365. ('slug', models.CharField(unique=True, max_length=100)),
  1366. ]),
  1367. migrations.CreateModel('Pony', fields=[
  1368. ('id', models.CharField(primary_key=True, max_length=100)),
  1369. ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE, to_field='slug')),
  1370. ('slug', models.CharField(unique=True, max_length=100)),
  1371. ]),
  1372. migrations.CreateModel('PonyRider', fields=[
  1373. ('id', models.AutoField(primary_key=True)),
  1374. ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE, to_field='slug')),
  1375. ]),
  1376. ])
  1377. project_state = self.apply_operations(app_label, project_state, operations=[
  1378. migrations.AlterField('Rider', 'slug', models.CharField(unique=True, max_length=99)),
  1379. migrations.AlterField('Pony', 'slug', models.CharField(unique=True, max_length=99)),
  1380. ])
  1381. def test_rename_field_reloads_state_on_fk_target_changes(self):
  1382. """
  1383. If RenameField doesn't reload state appropriately, the AlterField
  1384. crashes on MySQL due to not dropping the PonyRider.pony foreign key
  1385. constraint before modifying the column.
  1386. """
  1387. app_label = 'alter_rename_field_reloads_state_on_fk_target_changes'
  1388. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  1389. migrations.CreateModel('Rider', fields=[
  1390. ('id', models.CharField(primary_key=True, max_length=100)),
  1391. ]),
  1392. migrations.CreateModel('Pony', fields=[
  1393. ('id', models.CharField(primary_key=True, max_length=100)),
  1394. ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE)),
  1395. ]),
  1396. migrations.CreateModel('PonyRider', fields=[
  1397. ('id', models.AutoField(primary_key=True)),
  1398. ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE)),
  1399. ]),
  1400. ])
  1401. project_state = self.apply_operations(app_label, project_state, operations=[
  1402. migrations.RenameField('Rider', 'id', 'id2'),
  1403. migrations.AlterField('Pony', 'id', models.CharField(primary_key=True, max_length=99)),
  1404. ], atomic=connection.features.supports_atomic_references_rename)
  1405. def test_rename_field(self):
  1406. """
  1407. Tests the RenameField operation.
  1408. """
  1409. project_state = self.set_up_test_model("test_rnfl", unique_together=True, index_together=True)
  1410. # Test the state alteration
  1411. operation = migrations.RenameField("Pony", "pink", "blue")
  1412. self.assertEqual(operation.describe(), "Rename field pink on Pony to blue")
  1413. new_state = project_state.clone()
  1414. operation.state_forwards("test_rnfl", new_state)
  1415. self.assertIn("blue", [n for n, f in new_state.models["test_rnfl", "pony"].fields])
  1416. self.assertNotIn("pink", [n for n, f in new_state.models["test_rnfl", "pony"].fields])
  1417. # Make sure the unique_together has the renamed column too
  1418. self.assertIn("blue", new_state.models["test_rnfl", "pony"].options['unique_together'][0])
  1419. self.assertNotIn("pink", new_state.models["test_rnfl", "pony"].options['unique_together'][0])
  1420. # Make sure the index_together has the renamed column too
  1421. self.assertIn("blue", new_state.models["test_rnfl", "pony"].options['index_together'][0])
  1422. self.assertNotIn("pink", new_state.models["test_rnfl", "pony"].options['index_together'][0])
  1423. # Test the database alteration
  1424. self.assertColumnExists("test_rnfl_pony", "pink")
  1425. self.assertColumnNotExists("test_rnfl_pony", "blue")
  1426. with connection.schema_editor() as editor:
  1427. operation.database_forwards("test_rnfl", editor, project_state, new_state)
  1428. self.assertColumnExists("test_rnfl_pony", "blue")
  1429. self.assertColumnNotExists("test_rnfl_pony", "pink")
  1430. # Ensure the unique constraint has been ported over
  1431. with connection.cursor() as cursor:
  1432. cursor.execute("INSERT INTO test_rnfl_pony (blue, weight) VALUES (1, 1)")
  1433. with self.assertRaises(IntegrityError):
  1434. with atomic():
  1435. cursor.execute("INSERT INTO test_rnfl_pony (blue, weight) VALUES (1, 1)")
  1436. cursor.execute("DELETE FROM test_rnfl_pony")
  1437. # Ensure the index constraint has been ported over
  1438. self.assertIndexExists("test_rnfl_pony", ["weight", "blue"])
  1439. # And test reversal
  1440. with connection.schema_editor() as editor:
  1441. operation.database_backwards("test_rnfl", editor, new_state, project_state)
  1442. self.assertColumnExists("test_rnfl_pony", "pink")
  1443. self.assertColumnNotExists("test_rnfl_pony", "blue")
  1444. # Ensure the index constraint has been reset
  1445. self.assertIndexExists("test_rnfl_pony", ["weight", "pink"])
  1446. # And deconstruction
  1447. definition = operation.deconstruct()
  1448. self.assertEqual(definition[0], "RenameField")
  1449. self.assertEqual(definition[1], [])
  1450. self.assertEqual(definition[2], {'model_name': "Pony", 'old_name': "pink", 'new_name': "blue"})
  1451. def test_rename_missing_field(self):
  1452. state = ProjectState()
  1453. state.add_model(ModelState('app', 'model', []))
  1454. with self.assertRaisesMessage(FieldDoesNotExist, "app.model has no field named 'field'"):
  1455. migrations.RenameField('model', 'field', 'new_field').state_forwards('app', state)
  1456. def test_rename_referenced_field_state_forward(self):
  1457. state = ProjectState()
  1458. state.add_model(ModelState('app', 'Model', [
  1459. ('id', models.AutoField(primary_key=True)),
  1460. ('field', models.IntegerField(unique=True)),
  1461. ]))
  1462. state.add_model(ModelState('app', 'OtherModel', [
  1463. ('id', models.AutoField(primary_key=True)),
  1464. ('fk', models.ForeignKey('Model', models.CASCADE, to_field='field')),
  1465. ('fo', models.ForeignObject('Model', models.CASCADE, from_fields=('fk',), to_fields=('field',))),
  1466. ]))
  1467. operation = migrations.RenameField('Model', 'field', 'renamed')
  1468. new_state = state.clone()
  1469. operation.state_forwards('app', new_state)
  1470. self.assertEqual(new_state.models['app', 'othermodel'].fields[1][1].remote_field.field_name, 'renamed')
  1471. self.assertEqual(new_state.models['app', 'othermodel'].fields[1][1].from_fields, ['self'])
  1472. self.assertEqual(new_state.models['app', 'othermodel'].fields[1][1].to_fields, ('renamed',))
  1473. self.assertEqual(new_state.models['app', 'othermodel'].fields[2][1].from_fields, ('fk',))
  1474. self.assertEqual(new_state.models['app', 'othermodel'].fields[2][1].to_fields, ('renamed',))
  1475. operation = migrations.RenameField('OtherModel', 'fk', 'renamed_fk')
  1476. new_state = state.clone()
  1477. operation.state_forwards('app', new_state)
  1478. self.assertEqual(new_state.models['app', 'othermodel'].fields[1][1].remote_field.field_name, 'renamed')
  1479. self.assertEqual(new_state.models['app', 'othermodel'].fields[1][1].from_fields, ('self',))
  1480. self.assertEqual(new_state.models['app', 'othermodel'].fields[1][1].to_fields, ('renamed',))
  1481. self.assertEqual(new_state.models['app', 'othermodel'].fields[2][1].from_fields, ('renamed_fk',))
  1482. self.assertEqual(new_state.models['app', 'othermodel'].fields[2][1].to_fields, ('renamed',))
  1483. def test_alter_unique_together(self):
  1484. """
  1485. Tests the AlterUniqueTogether operation.
  1486. """
  1487. project_state = self.set_up_test_model("test_alunto")
  1488. # Test the state alteration
  1489. operation = migrations.AlterUniqueTogether("Pony", [("pink", "weight")])
  1490. self.assertEqual(operation.describe(), "Alter unique_together for Pony (1 constraint(s))")
  1491. new_state = project_state.clone()
  1492. operation.state_forwards("test_alunto", new_state)
  1493. self.assertEqual(len(project_state.models["test_alunto", "pony"].options.get("unique_together", set())), 0)
  1494. self.assertEqual(len(new_state.models["test_alunto", "pony"].options.get("unique_together", set())), 1)
  1495. # Make sure we can insert duplicate rows
  1496. with connection.cursor() as cursor:
  1497. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  1498. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  1499. cursor.execute("DELETE FROM test_alunto_pony")
  1500. # Test the database alteration
  1501. with connection.schema_editor() as editor:
  1502. operation.database_forwards("test_alunto", editor, project_state, new_state)
  1503. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  1504. with self.assertRaises(IntegrityError):
  1505. with atomic():
  1506. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  1507. cursor.execute("DELETE FROM test_alunto_pony")
  1508. # And test reversal
  1509. with connection.schema_editor() as editor:
  1510. operation.database_backwards("test_alunto", editor, new_state, project_state)
  1511. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  1512. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  1513. cursor.execute("DELETE FROM test_alunto_pony")
  1514. # Test flat unique_together
  1515. operation = migrations.AlterUniqueTogether("Pony", ("pink", "weight"))
  1516. operation.state_forwards("test_alunto", new_state)
  1517. self.assertEqual(len(new_state.models["test_alunto", "pony"].options.get("unique_together", set())), 1)
  1518. # And deconstruction
  1519. definition = operation.deconstruct()
  1520. self.assertEqual(definition[0], "AlterUniqueTogether")
  1521. self.assertEqual(definition[1], [])
  1522. self.assertEqual(definition[2], {'name': "Pony", 'unique_together': {("pink", "weight")}})
  1523. def test_alter_unique_together_remove(self):
  1524. operation = migrations.AlterUniqueTogether("Pony", None)
  1525. self.assertEqual(operation.describe(), "Alter unique_together for Pony (0 constraint(s))")
  1526. def test_add_index(self):
  1527. """
  1528. Test the AddIndex operation.
  1529. """
  1530. project_state = self.set_up_test_model("test_adin")
  1531. msg = (
  1532. "Indexes passed to AddIndex operations require a name argument. "
  1533. "<Index: fields='pink'> doesn't have one."
  1534. )
  1535. with self.assertRaisesMessage(ValueError, msg):
  1536. migrations.AddIndex("Pony", models.Index(fields=["pink"]))
  1537. index = models.Index(fields=["pink"], name="test_adin_pony_pink_idx")
  1538. operation = migrations.AddIndex("Pony", index)
  1539. self.assertEqual(operation.describe(), "Create index test_adin_pony_pink_idx on field(s) pink of model Pony")
  1540. new_state = project_state.clone()
  1541. operation.state_forwards("test_adin", new_state)
  1542. # Test the database alteration
  1543. self.assertEqual(len(new_state.models["test_adin", "pony"].options['indexes']), 1)
  1544. self.assertIndexNotExists("test_adin_pony", ["pink"])
  1545. with connection.schema_editor() as editor:
  1546. operation.database_forwards("test_adin", editor, project_state, new_state)
  1547. self.assertIndexExists("test_adin_pony", ["pink"])
  1548. # And test reversal
  1549. with connection.schema_editor() as editor:
  1550. operation.database_backwards("test_adin", editor, new_state, project_state)
  1551. self.assertIndexNotExists("test_adin_pony", ["pink"])
  1552. # And deconstruction
  1553. definition = operation.deconstruct()
  1554. self.assertEqual(definition[0], "AddIndex")
  1555. self.assertEqual(definition[1], [])
  1556. self.assertEqual(definition[2], {'model_name': "Pony", 'index': index})
  1557. def test_remove_index(self):
  1558. """
  1559. Test the RemoveIndex operation.
  1560. """
  1561. project_state = self.set_up_test_model("test_rmin", multicol_index=True)
  1562. self.assertTableExists("test_rmin_pony")
  1563. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  1564. operation = migrations.RemoveIndex("Pony", "pony_test_idx")
  1565. self.assertEqual(operation.describe(), "Remove index pony_test_idx from Pony")
  1566. new_state = project_state.clone()
  1567. operation.state_forwards("test_rmin", new_state)
  1568. # Test the state alteration
  1569. self.assertEqual(len(new_state.models["test_rmin", "pony"].options['indexes']), 0)
  1570. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  1571. # Test the database alteration
  1572. with connection.schema_editor() as editor:
  1573. operation.database_forwards("test_rmin", editor, project_state, new_state)
  1574. self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"])
  1575. # And test reversal
  1576. with connection.schema_editor() as editor:
  1577. operation.database_backwards("test_rmin", editor, new_state, project_state)
  1578. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  1579. # And deconstruction
  1580. definition = operation.deconstruct()
  1581. self.assertEqual(definition[0], "RemoveIndex")
  1582. self.assertEqual(definition[1], [])
  1583. self.assertEqual(definition[2], {'model_name': "Pony", 'name': "pony_test_idx"})
  1584. # Also test a field dropped with index - sqlite remake issue
  1585. operations = [
  1586. migrations.RemoveIndex("Pony", "pony_test_idx"),
  1587. migrations.RemoveField("Pony", "pink"),
  1588. ]
  1589. self.assertColumnExists("test_rmin_pony", "pink")
  1590. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  1591. # Test database alteration
  1592. new_state = project_state.clone()
  1593. self.apply_operations('test_rmin', new_state, operations=operations)
  1594. self.assertColumnNotExists("test_rmin_pony", "pink")
  1595. self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"])
  1596. # And test reversal
  1597. self.unapply_operations("test_rmin", project_state, operations=operations)
  1598. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  1599. def test_add_index_state_forwards(self):
  1600. project_state = self.set_up_test_model('test_adinsf')
  1601. index = models.Index(fields=['pink'], name='test_adinsf_pony_pink_idx')
  1602. old_model = project_state.apps.get_model('test_adinsf', 'Pony')
  1603. new_state = project_state.clone()
  1604. operation = migrations.AddIndex('Pony', index)
  1605. operation.state_forwards('test_adinsf', new_state)
  1606. new_model = new_state.apps.get_model('test_adinsf', 'Pony')
  1607. self.assertIsNot(old_model, new_model)
  1608. def test_remove_index_state_forwards(self):
  1609. project_state = self.set_up_test_model('test_rminsf')
  1610. index = models.Index(fields=['pink'], name='test_rminsf_pony_pink_idx')
  1611. migrations.AddIndex('Pony', index).state_forwards('test_rminsf', project_state)
  1612. old_model = project_state.apps.get_model('test_rminsf', 'Pony')
  1613. new_state = project_state.clone()
  1614. operation = migrations.RemoveIndex('Pony', 'test_rminsf_pony_pink_idx')
  1615. operation.state_forwards('test_rminsf', new_state)
  1616. new_model = new_state.apps.get_model('test_rminsf', 'Pony')
  1617. self.assertIsNot(old_model, new_model)
  1618. def test_alter_field_with_index(self):
  1619. """
  1620. Test AlterField operation with an index to ensure indexes created via
  1621. Meta.indexes don't get dropped with sqlite3 remake.
  1622. """
  1623. project_state = self.set_up_test_model("test_alflin", index=True)
  1624. operation = migrations.AlterField("Pony", "pink", models.IntegerField(null=True))
  1625. new_state = project_state.clone()
  1626. operation.state_forwards("test_alflin", new_state)
  1627. # Test the database alteration
  1628. self.assertColumnNotNull("test_alflin_pony", "pink")
  1629. with connection.schema_editor() as editor:
  1630. operation.database_forwards("test_alflin", editor, project_state, new_state)
  1631. # Index hasn't been dropped
  1632. self.assertIndexExists("test_alflin_pony", ["pink"])
  1633. # And test reversal
  1634. with connection.schema_editor() as editor:
  1635. operation.database_backwards("test_alflin", editor, new_state, project_state)
  1636. # Ensure the index is still there
  1637. self.assertIndexExists("test_alflin_pony", ["pink"])
  1638. def test_alter_index_together(self):
  1639. """
  1640. Tests the AlterIndexTogether operation.
  1641. """
  1642. project_state = self.set_up_test_model("test_alinto")
  1643. # Test the state alteration
  1644. operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")])
  1645. self.assertEqual(operation.describe(), "Alter index_together for Pony (1 constraint(s))")
  1646. new_state = project_state.clone()
  1647. operation.state_forwards("test_alinto", new_state)
  1648. self.assertEqual(len(project_state.models["test_alinto", "pony"].options.get("index_together", set())), 0)
  1649. self.assertEqual(len(new_state.models["test_alinto", "pony"].options.get("index_together", set())), 1)
  1650. # Make sure there's no matching index
  1651. self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"])
  1652. # Test the database alteration
  1653. with connection.schema_editor() as editor:
  1654. operation.database_forwards("test_alinto", editor, project_state, new_state)
  1655. self.assertIndexExists("test_alinto_pony", ["pink", "weight"])
  1656. # And test reversal
  1657. with connection.schema_editor() as editor:
  1658. operation.database_backwards("test_alinto", editor, new_state, project_state)
  1659. self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"])
  1660. # And deconstruction
  1661. definition = operation.deconstruct()
  1662. self.assertEqual(definition[0], "AlterIndexTogether")
  1663. self.assertEqual(definition[1], [])
  1664. self.assertEqual(definition[2], {'name': "Pony", 'index_together': {("pink", "weight")}})
  1665. def test_alter_index_together_remove(self):
  1666. operation = migrations.AlterIndexTogether("Pony", None)
  1667. self.assertEqual(operation.describe(), "Alter index_together for Pony (0 constraint(s))")
  1668. @skipUnlessDBFeature('supports_table_check_constraints')
  1669. def test_add_constraint(self):
  1670. project_state = self.set_up_test_model("test_addconstraint")
  1671. gt_check = models.Q(pink__gt=2)
  1672. gt_constraint = models.CheckConstraint(check=gt_check, name="test_add_constraint_pony_pink_gt_2")
  1673. gt_operation = migrations.AddConstraint("Pony", gt_constraint)
  1674. self.assertEqual(
  1675. gt_operation.describe(), "Create constraint test_add_constraint_pony_pink_gt_2 on model Pony"
  1676. )
  1677. # Test the state alteration
  1678. new_state = project_state.clone()
  1679. gt_operation.state_forwards("test_addconstraint", new_state)
  1680. self.assertEqual(len(new_state.models["test_addconstraint", "pony"].options["constraints"]), 1)
  1681. Pony = new_state.apps.get_model("test_addconstraint", "Pony")
  1682. self.assertEqual(len(Pony._meta.constraints), 1)
  1683. # Test the database alteration
  1684. with connection.schema_editor() as editor:
  1685. gt_operation.database_forwards("test_addconstraint", editor, project_state, new_state)
  1686. with self.assertRaises(IntegrityError), transaction.atomic():
  1687. Pony.objects.create(pink=1, weight=1.0)
  1688. # Add another one.
  1689. lt_check = models.Q(pink__lt=100)
  1690. lt_constraint = models.CheckConstraint(check=lt_check, name="test_add_constraint_pony_pink_lt_100")
  1691. lt_operation = migrations.AddConstraint("Pony", lt_constraint)
  1692. lt_operation.state_forwards("test_addconstraint", new_state)
  1693. self.assertEqual(len(new_state.models["test_addconstraint", "pony"].options["constraints"]), 2)
  1694. Pony = new_state.apps.get_model("test_addconstraint", "Pony")
  1695. self.assertEqual(len(Pony._meta.constraints), 2)
  1696. with connection.schema_editor() as editor:
  1697. lt_operation.database_forwards("test_addconstraint", editor, project_state, new_state)
  1698. with self.assertRaises(IntegrityError), transaction.atomic():
  1699. Pony.objects.create(pink=100, weight=1.0)
  1700. # Test reversal
  1701. with connection.schema_editor() as editor:
  1702. gt_operation.database_backwards("test_addconstraint", editor, new_state, project_state)
  1703. Pony.objects.create(pink=1, weight=1.0)
  1704. # Test deconstruction
  1705. definition = gt_operation.deconstruct()
  1706. self.assertEqual(definition[0], "AddConstraint")
  1707. self.assertEqual(definition[1], [])
  1708. self.assertEqual(definition[2], {'model_name': "Pony", 'constraint': gt_constraint})
  1709. @skipUnlessDBFeature('supports_table_check_constraints')
  1710. def test_remove_constraint(self):
  1711. project_state = self.set_up_test_model("test_removeconstraint", constraints=[
  1712. models.CheckConstraint(check=models.Q(pink__gt=2), name="test_remove_constraint_pony_pink_gt_2"),
  1713. models.CheckConstraint(check=models.Q(pink__lt=100), name="test_remove_constraint_pony_pink_lt_100"),
  1714. ])
  1715. gt_operation = migrations.RemoveConstraint("Pony", "test_remove_constraint_pony_pink_gt_2")
  1716. self.assertEqual(
  1717. gt_operation.describe(), "Remove constraint test_remove_constraint_pony_pink_gt_2 from model Pony"
  1718. )
  1719. # Test state alteration
  1720. new_state = project_state.clone()
  1721. gt_operation.state_forwards("test_removeconstraint", new_state)
  1722. self.assertEqual(len(new_state.models["test_removeconstraint", "pony"].options['constraints']), 1)
  1723. Pony = new_state.apps.get_model("test_removeconstraint", "Pony")
  1724. self.assertEqual(len(Pony._meta.constraints), 1)
  1725. # Test database alteration
  1726. with connection.schema_editor() as editor:
  1727. gt_operation.database_forwards("test_removeconstraint", editor, project_state, new_state)
  1728. Pony.objects.create(pink=1, weight=1.0).delete()
  1729. with self.assertRaises(IntegrityError), transaction.atomic():
  1730. Pony.objects.create(pink=100, weight=1.0)
  1731. # Remove the other one.
  1732. lt_operation = migrations.RemoveConstraint("Pony", "test_remove_constraint_pony_pink_lt_100")
  1733. lt_operation.state_forwards("test_removeconstraint", new_state)
  1734. self.assertEqual(len(new_state.models["test_removeconstraint", "pony"].options['constraints']), 0)
  1735. Pony = new_state.apps.get_model("test_removeconstraint", "Pony")
  1736. self.assertEqual(len(Pony._meta.constraints), 0)
  1737. with connection.schema_editor() as editor:
  1738. lt_operation.database_forwards("test_removeconstraint", editor, project_state, new_state)
  1739. Pony.objects.create(pink=100, weight=1.0).delete()
  1740. # Test reversal
  1741. with connection.schema_editor() as editor:
  1742. gt_operation.database_backwards("test_removeconstraint", editor, new_state, project_state)
  1743. with self.assertRaises(IntegrityError), transaction.atomic():
  1744. Pony.objects.create(pink=1, weight=1.0)
  1745. # Test deconstruction
  1746. definition = gt_operation.deconstruct()
  1747. self.assertEqual(definition[0], "RemoveConstraint")
  1748. self.assertEqual(definition[1], [])
  1749. self.assertEqual(definition[2], {'model_name': "Pony", 'name': "test_remove_constraint_pony_pink_gt_2"})
  1750. def test_alter_model_options(self):
  1751. """
  1752. Tests the AlterModelOptions operation.
  1753. """
  1754. project_state = self.set_up_test_model("test_almoop")
  1755. # Test the state alteration (no DB alteration to test)
  1756. operation = migrations.AlterModelOptions("Pony", {"permissions": [("can_groom", "Can groom")]})
  1757. self.assertEqual(operation.describe(), "Change Meta options on Pony")
  1758. new_state = project_state.clone()
  1759. operation.state_forwards("test_almoop", new_state)
  1760. self.assertEqual(len(project_state.models["test_almoop", "pony"].options.get("permissions", [])), 0)
  1761. self.assertEqual(len(new_state.models["test_almoop", "pony"].options.get("permissions", [])), 1)
  1762. self.assertEqual(new_state.models["test_almoop", "pony"].options["permissions"][0][0], "can_groom")
  1763. # And deconstruction
  1764. definition = operation.deconstruct()
  1765. self.assertEqual(definition[0], "AlterModelOptions")
  1766. self.assertEqual(definition[1], [])
  1767. self.assertEqual(definition[2], {'name': "Pony", 'options': {"permissions": [("can_groom", "Can groom")]}})
  1768. def test_alter_model_options_emptying(self):
  1769. """
  1770. The AlterModelOptions operation removes keys from the dict (#23121)
  1771. """
  1772. project_state = self.set_up_test_model("test_almoop", options=True)
  1773. # Test the state alteration (no DB alteration to test)
  1774. operation = migrations.AlterModelOptions("Pony", {})
  1775. self.assertEqual(operation.describe(), "Change Meta options on Pony")
  1776. new_state = project_state.clone()
  1777. operation.state_forwards("test_almoop", new_state)
  1778. self.assertEqual(len(project_state.models["test_almoop", "pony"].options.get("permissions", [])), 1)
  1779. self.assertEqual(len(new_state.models["test_almoop", "pony"].options.get("permissions", [])), 0)
  1780. # And deconstruction
  1781. definition = operation.deconstruct()
  1782. self.assertEqual(definition[0], "AlterModelOptions")
  1783. self.assertEqual(definition[1], [])
  1784. self.assertEqual(definition[2], {'name': "Pony", 'options': {}})
  1785. def test_alter_order_with_respect_to(self):
  1786. """
  1787. Tests the AlterOrderWithRespectTo operation.
  1788. """
  1789. project_state = self.set_up_test_model("test_alorwrtto", related_model=True)
  1790. # Test the state alteration
  1791. operation = migrations.AlterOrderWithRespectTo("Rider", "pony")
  1792. self.assertEqual(operation.describe(), "Set order_with_respect_to on Rider to pony")
  1793. new_state = project_state.clone()
  1794. operation.state_forwards("test_alorwrtto", new_state)
  1795. self.assertIsNone(
  1796. project_state.models["test_alorwrtto", "rider"].options.get("order_with_respect_to", None)
  1797. )
  1798. self.assertEqual(
  1799. new_state.models["test_alorwrtto", "rider"].options.get("order_with_respect_to", None),
  1800. "pony"
  1801. )
  1802. # Make sure there's no matching index
  1803. self.assertColumnNotExists("test_alorwrtto_rider", "_order")
  1804. # Create some rows before alteration
  1805. rendered_state = project_state.apps
  1806. pony = rendered_state.get_model("test_alorwrtto", "Pony").objects.create(weight=50)
  1807. rendered_state.get_model("test_alorwrtto", "Rider").objects.create(pony=pony, friend_id=1)
  1808. rendered_state.get_model("test_alorwrtto", "Rider").objects.create(pony=pony, friend_id=2)
  1809. # Test the database alteration
  1810. with connection.schema_editor() as editor:
  1811. operation.database_forwards("test_alorwrtto", editor, project_state, new_state)
  1812. self.assertColumnExists("test_alorwrtto_rider", "_order")
  1813. # Check for correct value in rows
  1814. updated_riders = new_state.apps.get_model("test_alorwrtto", "Rider").objects.all()
  1815. self.assertEqual(updated_riders[0]._order, 0)
  1816. self.assertEqual(updated_riders[1]._order, 0)
  1817. # And test reversal
  1818. with connection.schema_editor() as editor:
  1819. operation.database_backwards("test_alorwrtto", editor, new_state, project_state)
  1820. self.assertColumnNotExists("test_alorwrtto_rider", "_order")
  1821. # And deconstruction
  1822. definition = operation.deconstruct()
  1823. self.assertEqual(definition[0], "AlterOrderWithRespectTo")
  1824. self.assertEqual(definition[1], [])
  1825. self.assertEqual(definition[2], {'name': "Rider", 'order_with_respect_to': "pony"})
  1826. def test_alter_model_managers(self):
  1827. """
  1828. The managers on a model are set.
  1829. """
  1830. project_state = self.set_up_test_model("test_almoma")
  1831. # Test the state alteration
  1832. operation = migrations.AlterModelManagers(
  1833. "Pony",
  1834. managers=[
  1835. ("food_qs", FoodQuerySet.as_manager()),
  1836. ("food_mgr", FoodManager("a", "b")),
  1837. ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)),
  1838. ]
  1839. )
  1840. self.assertEqual(operation.describe(), "Change managers on Pony")
  1841. managers = project_state.models["test_almoma", "pony"].managers
  1842. self.assertEqual(managers, [])
  1843. new_state = project_state.clone()
  1844. operation.state_forwards("test_almoma", new_state)
  1845. self.assertIn(("test_almoma", "pony"), new_state.models)
  1846. managers = new_state.models["test_almoma", "pony"].managers
  1847. self.assertEqual(managers[0][0], "food_qs")
  1848. self.assertIsInstance(managers[0][1], models.Manager)
  1849. self.assertEqual(managers[1][0], "food_mgr")
  1850. self.assertIsInstance(managers[1][1], FoodManager)
  1851. self.assertEqual(managers[1][1].args, ("a", "b", 1, 2))
  1852. self.assertEqual(managers[2][0], "food_mgr_kwargs")
  1853. self.assertIsInstance(managers[2][1], FoodManager)
  1854. self.assertEqual(managers[2][1].args, ("x", "y", 3, 4))
  1855. rendered_state = new_state.apps
  1856. model = rendered_state.get_model('test_almoma', 'pony')
  1857. self.assertIsInstance(model.food_qs, models.Manager)
  1858. self.assertIsInstance(model.food_mgr, FoodManager)
  1859. self.assertIsInstance(model.food_mgr_kwargs, FoodManager)
  1860. def test_alter_model_managers_emptying(self):
  1861. """
  1862. The managers on a model are set.
  1863. """
  1864. project_state = self.set_up_test_model("test_almomae", manager_model=True)
  1865. # Test the state alteration
  1866. operation = migrations.AlterModelManagers("Food", managers=[])
  1867. self.assertEqual(operation.describe(), "Change managers on Food")
  1868. self.assertIn(("test_almomae", "food"), project_state.models)
  1869. managers = project_state.models["test_almomae", "food"].managers
  1870. self.assertEqual(managers[0][0], "food_qs")
  1871. self.assertIsInstance(managers[0][1], models.Manager)
  1872. self.assertEqual(managers[1][0], "food_mgr")
  1873. self.assertIsInstance(managers[1][1], FoodManager)
  1874. self.assertEqual(managers[1][1].args, ("a", "b", 1, 2))
  1875. self.assertEqual(managers[2][0], "food_mgr_kwargs")
  1876. self.assertIsInstance(managers[2][1], FoodManager)
  1877. self.assertEqual(managers[2][1].args, ("x", "y", 3, 4))
  1878. new_state = project_state.clone()
  1879. operation.state_forwards("test_almomae", new_state)
  1880. managers = new_state.models["test_almomae", "food"].managers
  1881. self.assertEqual(managers, [])
  1882. def test_alter_fk(self):
  1883. """
  1884. Creating and then altering an FK works correctly
  1885. and deals with the pending SQL (#23091)
  1886. """
  1887. project_state = self.set_up_test_model("test_alfk")
  1888. # Test adding and then altering the FK in one go
  1889. create_operation = migrations.CreateModel(
  1890. name="Rider",
  1891. fields=[
  1892. ("id", models.AutoField(primary_key=True)),
  1893. ("pony", models.ForeignKey("Pony", models.CASCADE)),
  1894. ],
  1895. )
  1896. create_state = project_state.clone()
  1897. create_operation.state_forwards("test_alfk", create_state)
  1898. alter_operation = migrations.AlterField(
  1899. model_name='Rider',
  1900. name='pony',
  1901. field=models.ForeignKey("Pony", models.CASCADE, editable=False),
  1902. )
  1903. alter_state = create_state.clone()
  1904. alter_operation.state_forwards("test_alfk", alter_state)
  1905. with connection.schema_editor() as editor:
  1906. create_operation.database_forwards("test_alfk", editor, project_state, create_state)
  1907. alter_operation.database_forwards("test_alfk", editor, create_state, alter_state)
  1908. def test_alter_fk_non_fk(self):
  1909. """
  1910. Altering an FK to a non-FK works (#23244)
  1911. """
  1912. # Test the state alteration
  1913. operation = migrations.AlterField(
  1914. model_name="Rider",
  1915. name="pony",
  1916. field=models.FloatField(),
  1917. )
  1918. project_state, new_state = self.make_test_state("test_afknfk", operation, related_model=True)
  1919. # Test the database alteration
  1920. self.assertColumnExists("test_afknfk_rider", "pony_id")
  1921. self.assertColumnNotExists("test_afknfk_rider", "pony")
  1922. with connection.schema_editor() as editor:
  1923. operation.database_forwards("test_afknfk", editor, project_state, new_state)
  1924. self.assertColumnExists("test_afknfk_rider", "pony")
  1925. self.assertColumnNotExists("test_afknfk_rider", "pony_id")
  1926. # And test reversal
  1927. with connection.schema_editor() as editor:
  1928. operation.database_backwards("test_afknfk", editor, new_state, project_state)
  1929. self.assertColumnExists("test_afknfk_rider", "pony_id")
  1930. self.assertColumnNotExists("test_afknfk_rider", "pony")
  1931. def test_run_sql(self):
  1932. """
  1933. Tests the RunSQL operation.
  1934. """
  1935. project_state = self.set_up_test_model("test_runsql")
  1936. # Create the operation
  1937. operation = migrations.RunSQL(
  1938. # Use a multi-line string with a comment to test splitting on SQLite and MySQL respectively
  1939. "CREATE TABLE i_love_ponies (id int, special_thing varchar(15));\n"
  1940. "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 'i love ponies'); -- this is magic!\n"
  1941. "INSERT INTO i_love_ponies (id, special_thing) VALUES (2, 'i love django');\n"
  1942. "UPDATE i_love_ponies SET special_thing = 'Ponies' WHERE special_thing LIKE '%%ponies';"
  1943. "UPDATE i_love_ponies SET special_thing = 'Django' WHERE special_thing LIKE '%django';",
  1944. # Run delete queries to test for parameter substitution failure
  1945. # reported in #23426
  1946. "DELETE FROM i_love_ponies WHERE special_thing LIKE '%Django%';"
  1947. "DELETE FROM i_love_ponies WHERE special_thing LIKE '%%Ponies%%';"
  1948. "DROP TABLE i_love_ponies",
  1949. state_operations=[migrations.CreateModel("SomethingElse", [("id", models.AutoField(primary_key=True))])],
  1950. )
  1951. self.assertEqual(operation.describe(), "Raw SQL operation")
  1952. # Test the state alteration
  1953. new_state = project_state.clone()
  1954. operation.state_forwards("test_runsql", new_state)
  1955. self.assertEqual(len(new_state.models["test_runsql", "somethingelse"].fields), 1)
  1956. # Make sure there's no table
  1957. self.assertTableNotExists("i_love_ponies")
  1958. # Test SQL collection
  1959. with connection.schema_editor(collect_sql=True) as editor:
  1960. operation.database_forwards("test_runsql", editor, project_state, new_state)
  1961. self.assertIn("LIKE '%%ponies';", "\n".join(editor.collected_sql))
  1962. operation.database_backwards("test_runsql", editor, project_state, new_state)
  1963. self.assertIn("LIKE '%%Ponies%%';", "\n".join(editor.collected_sql))
  1964. # Test the database alteration
  1965. with connection.schema_editor() as editor:
  1966. operation.database_forwards("test_runsql", editor, project_state, new_state)
  1967. self.assertTableExists("i_love_ponies")
  1968. # Make sure all the SQL was processed
  1969. with connection.cursor() as cursor:
  1970. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  1971. self.assertEqual(cursor.fetchall()[0][0], 2)
  1972. cursor.execute("SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Django'")
  1973. self.assertEqual(cursor.fetchall()[0][0], 1)
  1974. cursor.execute("SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Ponies'")
  1975. self.assertEqual(cursor.fetchall()[0][0], 1)
  1976. # And test reversal
  1977. self.assertTrue(operation.reversible)
  1978. with connection.schema_editor() as editor:
  1979. operation.database_backwards("test_runsql", editor, new_state, project_state)
  1980. self.assertTableNotExists("i_love_ponies")
  1981. # And deconstruction
  1982. definition = operation.deconstruct()
  1983. self.assertEqual(definition[0], "RunSQL")
  1984. self.assertEqual(definition[1], [])
  1985. self.assertEqual(sorted(definition[2]), ["reverse_sql", "sql", "state_operations"])
  1986. # And elidable reduction
  1987. self.assertIs(False, operation.reduce(operation, []))
  1988. elidable_operation = migrations.RunSQL('SELECT 1 FROM void;', elidable=True)
  1989. self.assertEqual(elidable_operation.reduce(operation, []), [operation])
  1990. def test_run_sql_params(self):
  1991. """
  1992. #23426 - RunSQL should accept parameters.
  1993. """
  1994. project_state = self.set_up_test_model("test_runsql")
  1995. # Create the operation
  1996. operation = migrations.RunSQL(
  1997. ["CREATE TABLE i_love_ponies (id int, special_thing varchar(15));"],
  1998. ["DROP TABLE i_love_ponies"],
  1999. )
  2000. param_operation = migrations.RunSQL(
  2001. # forwards
  2002. (
  2003. "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 'Django');",
  2004. ["INSERT INTO i_love_ponies (id, special_thing) VALUES (2, %s);", ['Ponies']],
  2005. ("INSERT INTO i_love_ponies (id, special_thing) VALUES (%s, %s);", (3, 'Python',)),
  2006. ),
  2007. # backwards
  2008. [
  2009. "DELETE FROM i_love_ponies WHERE special_thing = 'Django';",
  2010. ["DELETE FROM i_love_ponies WHERE special_thing = 'Ponies';", None],
  2011. ("DELETE FROM i_love_ponies WHERE id = %s OR special_thing = %s;", [3, 'Python']),
  2012. ]
  2013. )
  2014. # Make sure there's no table
  2015. self.assertTableNotExists("i_love_ponies")
  2016. new_state = project_state.clone()
  2017. # Test the database alteration
  2018. with connection.schema_editor() as editor:
  2019. operation.database_forwards("test_runsql", editor, project_state, new_state)
  2020. # Test parameter passing
  2021. with connection.schema_editor() as editor:
  2022. param_operation.database_forwards("test_runsql", editor, project_state, new_state)
  2023. # Make sure all the SQL was processed
  2024. with connection.cursor() as cursor:
  2025. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  2026. self.assertEqual(cursor.fetchall()[0][0], 3)
  2027. with connection.schema_editor() as editor:
  2028. param_operation.database_backwards("test_runsql", editor, new_state, project_state)
  2029. with connection.cursor() as cursor:
  2030. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  2031. self.assertEqual(cursor.fetchall()[0][0], 0)
  2032. # And test reversal
  2033. with connection.schema_editor() as editor:
  2034. operation.database_backwards("test_runsql", editor, new_state, project_state)
  2035. self.assertTableNotExists("i_love_ponies")
  2036. def test_run_sql_params_invalid(self):
  2037. """
  2038. #23426 - RunSQL should fail when a list of statements with an incorrect
  2039. number of tuples is given.
  2040. """
  2041. project_state = self.set_up_test_model("test_runsql")
  2042. new_state = project_state.clone()
  2043. operation = migrations.RunSQL(
  2044. # forwards
  2045. [
  2046. ["INSERT INTO foo (bar) VALUES ('buz');"]
  2047. ],
  2048. # backwards
  2049. (
  2050. ("DELETE FROM foo WHERE bar = 'buz';", 'invalid', 'parameter count'),
  2051. ),
  2052. )
  2053. with connection.schema_editor() as editor:
  2054. with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 1"):
  2055. operation.database_forwards("test_runsql", editor, project_state, new_state)
  2056. with connection.schema_editor() as editor:
  2057. with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 3"):
  2058. operation.database_backwards("test_runsql", editor, new_state, project_state)
  2059. def test_run_sql_noop(self):
  2060. """
  2061. #24098 - Tests no-op RunSQL operations.
  2062. """
  2063. operation = migrations.RunSQL(migrations.RunSQL.noop, migrations.RunSQL.noop)
  2064. with connection.schema_editor() as editor:
  2065. operation.database_forwards("test_runsql", editor, None, None)
  2066. operation.database_backwards("test_runsql", editor, None, None)
  2067. def test_run_python(self):
  2068. """
  2069. Tests the RunPython operation
  2070. """
  2071. project_state = self.set_up_test_model("test_runpython", mti_model=True)
  2072. # Create the operation
  2073. def inner_method(models, schema_editor):
  2074. Pony = models.get_model("test_runpython", "Pony")
  2075. Pony.objects.create(pink=1, weight=3.55)
  2076. Pony.objects.create(weight=5)
  2077. def inner_method_reverse(models, schema_editor):
  2078. Pony = models.get_model("test_runpython", "Pony")
  2079. Pony.objects.filter(pink=1, weight=3.55).delete()
  2080. Pony.objects.filter(weight=5).delete()
  2081. operation = migrations.RunPython(inner_method, reverse_code=inner_method_reverse)
  2082. self.assertEqual(operation.describe(), "Raw Python operation")
  2083. # Test the state alteration does nothing
  2084. new_state = project_state.clone()
  2085. operation.state_forwards("test_runpython", new_state)
  2086. self.assertEqual(new_state, project_state)
  2087. # Test the database alteration
  2088. self.assertEqual(project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0)
  2089. with connection.schema_editor() as editor:
  2090. operation.database_forwards("test_runpython", editor, project_state, new_state)
  2091. self.assertEqual(project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2)
  2092. # Now test reversal
  2093. self.assertTrue(operation.reversible)
  2094. with connection.schema_editor() as editor:
  2095. operation.database_backwards("test_runpython", editor, project_state, new_state)
  2096. self.assertEqual(project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0)
  2097. # Now test we can't use a string
  2098. with self.assertRaisesMessage(ValueError, 'RunPython must be supplied with a callable'):
  2099. migrations.RunPython("print 'ahahaha'")
  2100. # And deconstruction
  2101. definition = operation.deconstruct()
  2102. self.assertEqual(definition[0], "RunPython")
  2103. self.assertEqual(definition[1], [])
  2104. self.assertEqual(sorted(definition[2]), ["code", "reverse_code"])
  2105. # Also test reversal fails, with an operation identical to above but without reverse_code set
  2106. no_reverse_operation = migrations.RunPython(inner_method)
  2107. self.assertFalse(no_reverse_operation.reversible)
  2108. with connection.schema_editor() as editor:
  2109. no_reverse_operation.database_forwards("test_runpython", editor, project_state, new_state)
  2110. with self.assertRaises(NotImplementedError):
  2111. no_reverse_operation.database_backwards("test_runpython", editor, new_state, project_state)
  2112. self.assertEqual(project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2)
  2113. def create_ponies(models, schema_editor):
  2114. Pony = models.get_model("test_runpython", "Pony")
  2115. pony1 = Pony.objects.create(pink=1, weight=3.55)
  2116. self.assertIsNot(pony1.pk, None)
  2117. pony2 = Pony.objects.create(weight=5)
  2118. self.assertIsNot(pony2.pk, None)
  2119. self.assertNotEqual(pony1.pk, pony2.pk)
  2120. operation = migrations.RunPython(create_ponies)
  2121. with connection.schema_editor() as editor:
  2122. operation.database_forwards("test_runpython", editor, project_state, new_state)
  2123. self.assertEqual(project_state.apps.get_model("test_runpython", "Pony").objects.count(), 4)
  2124. # And deconstruction
  2125. definition = operation.deconstruct()
  2126. self.assertEqual(definition[0], "RunPython")
  2127. self.assertEqual(definition[1], [])
  2128. self.assertEqual(sorted(definition[2]), ["code"])
  2129. def create_shetlandponies(models, schema_editor):
  2130. ShetlandPony = models.get_model("test_runpython", "ShetlandPony")
  2131. pony1 = ShetlandPony.objects.create(weight=4.0)
  2132. self.assertIsNot(pony1.pk, None)
  2133. pony2 = ShetlandPony.objects.create(weight=5.0)
  2134. self.assertIsNot(pony2.pk, None)
  2135. self.assertNotEqual(pony1.pk, pony2.pk)
  2136. operation = migrations.RunPython(create_shetlandponies)
  2137. with connection.schema_editor() as editor:
  2138. operation.database_forwards("test_runpython", editor, project_state, new_state)
  2139. self.assertEqual(project_state.apps.get_model("test_runpython", "Pony").objects.count(), 6)
  2140. self.assertEqual(project_state.apps.get_model("test_runpython", "ShetlandPony").objects.count(), 2)
  2141. # And elidable reduction
  2142. self.assertIs(False, operation.reduce(operation, []))
  2143. elidable_operation = migrations.RunPython(inner_method, elidable=True)
  2144. self.assertEqual(elidable_operation.reduce(operation, []), [operation])
  2145. def test_run_python_atomic(self):
  2146. """
  2147. Tests the RunPython operation correctly handles the "atomic" keyword
  2148. """
  2149. project_state = self.set_up_test_model("test_runpythonatomic", mti_model=True)
  2150. def inner_method(models, schema_editor):
  2151. Pony = models.get_model("test_runpythonatomic", "Pony")
  2152. Pony.objects.create(pink=1, weight=3.55)
  2153. raise ValueError("Adrian hates ponies.")
  2154. # Verify atomicity when applying.
  2155. atomic_migration = Migration("test", "test_runpythonatomic")
  2156. atomic_migration.operations = [migrations.RunPython(inner_method, reverse_code=inner_method)]
  2157. non_atomic_migration = Migration("test", "test_runpythonatomic")
  2158. non_atomic_migration.operations = [migrations.RunPython(inner_method, reverse_code=inner_method, atomic=False)]
  2159. # If we're a fully-transactional database, both versions should rollback
  2160. if connection.features.can_rollback_ddl:
  2161. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2162. with self.assertRaises(ValueError):
  2163. with connection.schema_editor() as editor:
  2164. atomic_migration.apply(project_state, editor)
  2165. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2166. with self.assertRaises(ValueError):
  2167. with connection.schema_editor() as editor:
  2168. non_atomic_migration.apply(project_state, editor)
  2169. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2170. # Otherwise, the non-atomic operation should leave a row there
  2171. else:
  2172. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2173. with self.assertRaises(ValueError):
  2174. with connection.schema_editor() as editor:
  2175. atomic_migration.apply(project_state, editor)
  2176. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2177. with self.assertRaises(ValueError):
  2178. with connection.schema_editor() as editor:
  2179. non_atomic_migration.apply(project_state, editor)
  2180. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 1)
  2181. # Reset object count to zero and verify atomicity when unapplying.
  2182. project_state.apps.get_model("test_runpythonatomic", "Pony").objects.all().delete()
  2183. # On a fully-transactional database, both versions rollback.
  2184. if connection.features.can_rollback_ddl:
  2185. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2186. with self.assertRaises(ValueError):
  2187. with connection.schema_editor() as editor:
  2188. atomic_migration.unapply(project_state, editor)
  2189. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2190. with self.assertRaises(ValueError):
  2191. with connection.schema_editor() as editor:
  2192. non_atomic_migration.unapply(project_state, editor)
  2193. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2194. # Otherwise, the non-atomic operation leaves a row there.
  2195. else:
  2196. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2197. with self.assertRaises(ValueError):
  2198. with connection.schema_editor() as editor:
  2199. atomic_migration.unapply(project_state, editor)
  2200. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2201. with self.assertRaises(ValueError):
  2202. with connection.schema_editor() as editor:
  2203. non_atomic_migration.unapply(project_state, editor)
  2204. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 1)
  2205. # Verify deconstruction.
  2206. definition = non_atomic_migration.operations[0].deconstruct()
  2207. self.assertEqual(definition[0], "RunPython")
  2208. self.assertEqual(definition[1], [])
  2209. self.assertEqual(sorted(definition[2]), ["atomic", "code", "reverse_code"])
  2210. def test_run_python_related_assignment(self):
  2211. """
  2212. #24282 - Model changes to a FK reverse side update the model
  2213. on the FK side as well.
  2214. """
  2215. def inner_method(models, schema_editor):
  2216. Author = models.get_model("test_authors", "Author")
  2217. Book = models.get_model("test_books", "Book")
  2218. author = Author.objects.create(name="Hemingway")
  2219. Book.objects.create(title="Old Man and The Sea", author=author)
  2220. create_author = migrations.CreateModel(
  2221. "Author",
  2222. [
  2223. ("id", models.AutoField(primary_key=True)),
  2224. ("name", models.CharField(max_length=100)),
  2225. ],
  2226. options={},
  2227. )
  2228. create_book = migrations.CreateModel(
  2229. "Book",
  2230. [
  2231. ("id", models.AutoField(primary_key=True)),
  2232. ("title", models.CharField(max_length=100)),
  2233. ("author", models.ForeignKey("test_authors.Author", models.CASCADE))
  2234. ],
  2235. options={},
  2236. )
  2237. add_hometown = migrations.AddField(
  2238. "Author",
  2239. "hometown",
  2240. models.CharField(max_length=100),
  2241. )
  2242. create_old_man = migrations.RunPython(inner_method, inner_method)
  2243. project_state = ProjectState()
  2244. new_state = project_state.clone()
  2245. with connection.schema_editor() as editor:
  2246. create_author.state_forwards("test_authors", new_state)
  2247. create_author.database_forwards("test_authors", editor, project_state, new_state)
  2248. project_state = new_state
  2249. new_state = new_state.clone()
  2250. with connection.schema_editor() as editor:
  2251. create_book.state_forwards("test_books", new_state)
  2252. create_book.database_forwards("test_books", editor, project_state, new_state)
  2253. project_state = new_state
  2254. new_state = new_state.clone()
  2255. with connection.schema_editor() as editor:
  2256. add_hometown.state_forwards("test_authors", new_state)
  2257. add_hometown.database_forwards("test_authors", editor, project_state, new_state)
  2258. project_state = new_state
  2259. new_state = new_state.clone()
  2260. with connection.schema_editor() as editor:
  2261. create_old_man.state_forwards("test_books", new_state)
  2262. create_old_man.database_forwards("test_books", editor, project_state, new_state)
  2263. def test_model_with_bigautofield(self):
  2264. """
  2265. A model with BigAutoField can be created.
  2266. """
  2267. def create_data(models, schema_editor):
  2268. Author = models.get_model("test_author", "Author")
  2269. Book = models.get_model("test_book", "Book")
  2270. author1 = Author.objects.create(name="Hemingway")
  2271. Book.objects.create(title="Old Man and The Sea", author=author1)
  2272. Book.objects.create(id=2 ** 33, title="A farewell to arms", author=author1)
  2273. author2 = Author.objects.create(id=2 ** 33, name="Remarque")
  2274. Book.objects.create(title="All quiet on the western front", author=author2)
  2275. Book.objects.create(title="Arc de Triomphe", author=author2)
  2276. create_author = migrations.CreateModel(
  2277. "Author",
  2278. [
  2279. ("id", models.BigAutoField(primary_key=True)),
  2280. ("name", models.CharField(max_length=100)),
  2281. ],
  2282. options={},
  2283. )
  2284. create_book = migrations.CreateModel(
  2285. "Book",
  2286. [
  2287. ("id", models.BigAutoField(primary_key=True)),
  2288. ("title", models.CharField(max_length=100)),
  2289. ("author", models.ForeignKey(to="test_author.Author", on_delete=models.CASCADE))
  2290. ],
  2291. options={},
  2292. )
  2293. fill_data = migrations.RunPython(create_data)
  2294. project_state = ProjectState()
  2295. new_state = project_state.clone()
  2296. with connection.schema_editor() as editor:
  2297. create_author.state_forwards("test_author", new_state)
  2298. create_author.database_forwards("test_author", editor, project_state, new_state)
  2299. project_state = new_state
  2300. new_state = new_state.clone()
  2301. with connection.schema_editor() as editor:
  2302. create_book.state_forwards("test_book", new_state)
  2303. create_book.database_forwards("test_book", editor, project_state, new_state)
  2304. project_state = new_state
  2305. new_state = new_state.clone()
  2306. with connection.schema_editor() as editor:
  2307. fill_data.state_forwards("fill_data", new_state)
  2308. fill_data.database_forwards("fill_data", editor, project_state, new_state)
  2309. def test_autofield_foreignfield_growth(self):
  2310. """
  2311. A field may be migrated from AutoField to BigAutoField.
  2312. """
  2313. def create_initial_data(models, schema_editor):
  2314. Article = models.get_model("test_article", "Article")
  2315. Blog = models.get_model("test_blog", "Blog")
  2316. blog = Blog.objects.create(name="web development done right")
  2317. Article.objects.create(name="Frameworks", blog=blog)
  2318. Article.objects.create(name="Programming Languages", blog=blog)
  2319. def create_big_data(models, schema_editor):
  2320. Article = models.get_model("test_article", "Article")
  2321. Blog = models.get_model("test_blog", "Blog")
  2322. blog2 = Blog.objects.create(name="Frameworks", id=2 ** 33)
  2323. Article.objects.create(name="Django", blog=blog2)
  2324. Article.objects.create(id=2 ** 33, name="Django2", blog=blog2)
  2325. create_blog = migrations.CreateModel(
  2326. "Blog",
  2327. [
  2328. ("id", models.AutoField(primary_key=True)),
  2329. ("name", models.CharField(max_length=100)),
  2330. ],
  2331. options={},
  2332. )
  2333. create_article = migrations.CreateModel(
  2334. "Article",
  2335. [
  2336. ("id", models.AutoField(primary_key=True)),
  2337. ("blog", models.ForeignKey(to="test_blog.Blog", on_delete=models.CASCADE)),
  2338. ("name", models.CharField(max_length=100)),
  2339. ("data", models.TextField(default="")),
  2340. ],
  2341. options={},
  2342. )
  2343. fill_initial_data = migrations.RunPython(create_initial_data, create_initial_data)
  2344. fill_big_data = migrations.RunPython(create_big_data, create_big_data)
  2345. grow_article_id = migrations.AlterField("Article", "id", models.BigAutoField(primary_key=True))
  2346. grow_blog_id = migrations.AlterField("Blog", "id", models.BigAutoField(primary_key=True))
  2347. project_state = ProjectState()
  2348. new_state = project_state.clone()
  2349. with connection.schema_editor() as editor:
  2350. create_blog.state_forwards("test_blog", new_state)
  2351. create_blog.database_forwards("test_blog", editor, project_state, new_state)
  2352. project_state = new_state
  2353. new_state = new_state.clone()
  2354. with connection.schema_editor() as editor:
  2355. create_article.state_forwards("test_article", new_state)
  2356. create_article.database_forwards("test_article", editor, project_state, new_state)
  2357. project_state = new_state
  2358. new_state = new_state.clone()
  2359. with connection.schema_editor() as editor:
  2360. fill_initial_data.state_forwards("fill_initial_data", new_state)
  2361. fill_initial_data.database_forwards("fill_initial_data", editor, project_state, new_state)
  2362. project_state = new_state
  2363. new_state = new_state.clone()
  2364. with connection.schema_editor() as editor:
  2365. grow_article_id.state_forwards("test_article", new_state)
  2366. grow_article_id.database_forwards("test_article", editor, project_state, new_state)
  2367. state = new_state.clone()
  2368. article = state.apps.get_model("test_article.Article")
  2369. self.assertIsInstance(article._meta.pk, models.BigAutoField)
  2370. project_state = new_state
  2371. new_state = new_state.clone()
  2372. with connection.schema_editor() as editor:
  2373. grow_blog_id.state_forwards("test_blog", new_state)
  2374. grow_blog_id.database_forwards("test_blog", editor, project_state, new_state)
  2375. state = new_state.clone()
  2376. blog = state.apps.get_model("test_blog.Blog")
  2377. self.assertIsInstance(blog._meta.pk, models.BigAutoField)
  2378. project_state = new_state
  2379. new_state = new_state.clone()
  2380. with connection.schema_editor() as editor:
  2381. fill_big_data.state_forwards("fill_big_data", new_state)
  2382. fill_big_data.database_forwards("fill_big_data", editor, project_state, new_state)
  2383. def test_run_python_noop(self):
  2384. """
  2385. #24098 - Tests no-op RunPython operations.
  2386. """
  2387. project_state = ProjectState()
  2388. new_state = project_state.clone()
  2389. operation = migrations.RunPython(migrations.RunPython.noop, migrations.RunPython.noop)
  2390. with connection.schema_editor() as editor:
  2391. operation.database_forwards("test_runpython", editor, project_state, new_state)
  2392. operation.database_backwards("test_runpython", editor, new_state, project_state)
  2393. def test_separate_database_and_state(self):
  2394. """
  2395. Tests the SeparateDatabaseAndState operation.
  2396. """
  2397. project_state = self.set_up_test_model("test_separatedatabaseandstate")
  2398. # Create the operation
  2399. database_operation = migrations.RunSQL(
  2400. "CREATE TABLE i_love_ponies (id int, special_thing int);",
  2401. "DROP TABLE i_love_ponies;"
  2402. )
  2403. state_operation = migrations.CreateModel("SomethingElse", [("id", models.AutoField(primary_key=True))])
  2404. operation = migrations.SeparateDatabaseAndState(
  2405. state_operations=[state_operation],
  2406. database_operations=[database_operation]
  2407. )
  2408. self.assertEqual(operation.describe(), "Custom state/database change combination")
  2409. # Test the state alteration
  2410. new_state = project_state.clone()
  2411. operation.state_forwards("test_separatedatabaseandstate", new_state)
  2412. self.assertEqual(len(new_state.models["test_separatedatabaseandstate", "somethingelse"].fields), 1)
  2413. # Make sure there's no table
  2414. self.assertTableNotExists("i_love_ponies")
  2415. # Test the database alteration
  2416. with connection.schema_editor() as editor:
  2417. operation.database_forwards("test_separatedatabaseandstate", editor, project_state, new_state)
  2418. self.assertTableExists("i_love_ponies")
  2419. # And test reversal
  2420. self.assertTrue(operation.reversible)
  2421. with connection.schema_editor() as editor:
  2422. operation.database_backwards("test_separatedatabaseandstate", editor, new_state, project_state)
  2423. self.assertTableNotExists("i_love_ponies")
  2424. # And deconstruction
  2425. definition = operation.deconstruct()
  2426. self.assertEqual(definition[0], "SeparateDatabaseAndState")
  2427. self.assertEqual(definition[1], [])
  2428. self.assertEqual(sorted(definition[2]), ["database_operations", "state_operations"])
  2429. def test_separate_database_and_state2(self):
  2430. """
  2431. A complex SeparateDatabaseAndState operation: Multiple operations both
  2432. for state and database. Verify the state dependencies within each list
  2433. and that state ops don't affect the database.
  2434. """
  2435. app_label = "test_separatedatabaseandstate2"
  2436. project_state = self.set_up_test_model(app_label)
  2437. # Create the operation
  2438. database_operations = [
  2439. migrations.CreateModel(
  2440. "ILovePonies",
  2441. [("id", models.AutoField(primary_key=True))],
  2442. options={"db_table": "iloveponies"},
  2443. ),
  2444. migrations.CreateModel(
  2445. "ILoveMorePonies",
  2446. # We use IntegerField and not AutoField because
  2447. # the model is going to be deleted immediately
  2448. # and with an AutoField this fails on Oracle
  2449. [("id", models.IntegerField(primary_key=True))],
  2450. options={"db_table": "ilovemoreponies"},
  2451. ),
  2452. migrations.DeleteModel("ILoveMorePonies"),
  2453. migrations.CreateModel(
  2454. "ILoveEvenMorePonies",
  2455. [("id", models.AutoField(primary_key=True))],
  2456. options={"db_table": "iloveevenmoreponies"},
  2457. ),
  2458. ]
  2459. state_operations = [
  2460. migrations.CreateModel(
  2461. "SomethingElse",
  2462. [("id", models.AutoField(primary_key=True))],
  2463. options={"db_table": "somethingelse"},
  2464. ),
  2465. migrations.DeleteModel("SomethingElse"),
  2466. migrations.CreateModel(
  2467. "SomethingCompletelyDifferent",
  2468. [("id", models.AutoField(primary_key=True))],
  2469. options={"db_table": "somethingcompletelydifferent"},
  2470. ),
  2471. ]
  2472. operation = migrations.SeparateDatabaseAndState(
  2473. state_operations=state_operations,
  2474. database_operations=database_operations,
  2475. )
  2476. # Test the state alteration
  2477. new_state = project_state.clone()
  2478. operation.state_forwards(app_label, new_state)
  2479. def assertModelsAndTables(after_db):
  2480. # Tables and models exist, or don't, as they should:
  2481. self.assertNotIn((app_label, "somethingelse"), new_state.models)
  2482. self.assertEqual(len(new_state.models[app_label, "somethingcompletelydifferent"].fields), 1)
  2483. self.assertNotIn((app_label, "iloveponiesonies"), new_state.models)
  2484. self.assertNotIn((app_label, "ilovemoreponies"), new_state.models)
  2485. self.assertNotIn((app_label, "iloveevenmoreponies"), new_state.models)
  2486. self.assertTableNotExists("somethingelse")
  2487. self.assertTableNotExists("somethingcompletelydifferent")
  2488. self.assertTableNotExists("ilovemoreponies")
  2489. if after_db:
  2490. self.assertTableExists("iloveponies")
  2491. self.assertTableExists("iloveevenmoreponies")
  2492. else:
  2493. self.assertTableNotExists("iloveponies")
  2494. self.assertTableNotExists("iloveevenmoreponies")
  2495. assertModelsAndTables(after_db=False)
  2496. # Test the database alteration
  2497. with connection.schema_editor() as editor:
  2498. operation.database_forwards(app_label, editor, project_state, new_state)
  2499. assertModelsAndTables(after_db=True)
  2500. # And test reversal
  2501. self.assertTrue(operation.reversible)
  2502. with connection.schema_editor() as editor:
  2503. operation.database_backwards(app_label, editor, new_state, project_state)
  2504. assertModelsAndTables(after_db=False)
  2505. class SwappableOperationTests(OperationTestBase):
  2506. """
  2507. Key operations ignore swappable models
  2508. (we don't want to replicate all of them here, as the functionality
  2509. is in a common base class anyway)
  2510. """
  2511. available_apps = ['migrations']
  2512. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  2513. def test_create_ignore_swapped(self):
  2514. """
  2515. The CreateTable operation ignores swapped models.
  2516. """
  2517. operation = migrations.CreateModel(
  2518. "Pony",
  2519. [
  2520. ("id", models.AutoField(primary_key=True)),
  2521. ("pink", models.IntegerField(default=1)),
  2522. ],
  2523. options={
  2524. "swappable": "TEST_SWAP_MODEL",
  2525. },
  2526. )
  2527. # Test the state alteration (it should still be there!)
  2528. project_state = ProjectState()
  2529. new_state = project_state.clone()
  2530. operation.state_forwards("test_crigsw", new_state)
  2531. self.assertEqual(new_state.models["test_crigsw", "pony"].name, "Pony")
  2532. self.assertEqual(len(new_state.models["test_crigsw", "pony"].fields), 2)
  2533. # Test the database alteration
  2534. self.assertTableNotExists("test_crigsw_pony")
  2535. with connection.schema_editor() as editor:
  2536. operation.database_forwards("test_crigsw", editor, project_state, new_state)
  2537. self.assertTableNotExists("test_crigsw_pony")
  2538. # And test reversal
  2539. with connection.schema_editor() as editor:
  2540. operation.database_backwards("test_crigsw", editor, new_state, project_state)
  2541. self.assertTableNotExists("test_crigsw_pony")
  2542. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  2543. def test_delete_ignore_swapped(self):
  2544. """
  2545. Tests the DeleteModel operation ignores swapped models.
  2546. """
  2547. operation = migrations.DeleteModel("Pony")
  2548. project_state, new_state = self.make_test_state("test_dligsw", operation)
  2549. # Test the database alteration
  2550. self.assertTableNotExists("test_dligsw_pony")
  2551. with connection.schema_editor() as editor:
  2552. operation.database_forwards("test_dligsw", editor, project_state, new_state)
  2553. self.assertTableNotExists("test_dligsw_pony")
  2554. # And test reversal
  2555. with connection.schema_editor() as editor:
  2556. operation.database_backwards("test_dligsw", editor, new_state, project_state)
  2557. self.assertTableNotExists("test_dligsw_pony")
  2558. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  2559. def test_add_field_ignore_swapped(self):
  2560. """
  2561. Tests the AddField operation.
  2562. """
  2563. # Test the state alteration
  2564. operation = migrations.AddField(
  2565. "Pony",
  2566. "height",
  2567. models.FloatField(null=True, default=5),
  2568. )
  2569. project_state, new_state = self.make_test_state("test_adfligsw", operation)
  2570. # Test the database alteration
  2571. self.assertTableNotExists("test_adfligsw_pony")
  2572. with connection.schema_editor() as editor:
  2573. operation.database_forwards("test_adfligsw", editor, project_state, new_state)
  2574. self.assertTableNotExists("test_adfligsw_pony")
  2575. # And test reversal
  2576. with connection.schema_editor() as editor:
  2577. operation.database_backwards("test_adfligsw", editor, new_state, project_state)
  2578. self.assertTableNotExists("test_adfligsw_pony")
  2579. @override_settings(TEST_SWAP_MODEL='migrations.SomeFakeModel')
  2580. def test_indexes_ignore_swapped(self):
  2581. """
  2582. Add/RemoveIndex operations ignore swapped models.
  2583. """
  2584. operation = migrations.AddIndex('Pony', models.Index(fields=['pink'], name='my_name_idx'))
  2585. project_state, new_state = self.make_test_state('test_adinigsw', operation)
  2586. with connection.schema_editor() as editor:
  2587. # No database queries should be run for swapped models
  2588. operation.database_forwards('test_adinigsw', editor, project_state, new_state)
  2589. operation.database_backwards('test_adinigsw', editor, new_state, project_state)
  2590. operation = migrations.RemoveIndex('Pony', models.Index(fields=['pink'], name='my_name_idx'))
  2591. project_state, new_state = self.make_test_state("test_rminigsw", operation)
  2592. with connection.schema_editor() as editor:
  2593. operation.database_forwards('test_rminigsw', editor, project_state, new_state)
  2594. operation.database_backwards('test_rminigsw', editor, new_state, project_state)
  2595. class TestCreateModel(SimpleTestCase):
  2596. def test_references_model_mixin(self):
  2597. CreateModel('name', [], bases=(Mixin, models.Model)).references_model('other_model')
  2598. class FieldOperationTests(SimpleTestCase):
  2599. def test_references_model(self):
  2600. operation = FieldOperation('MoDel', 'field', models.ForeignKey('Other', models.CASCADE))
  2601. # Model name match.
  2602. self.assertIs(operation.references_model('mOdEl'), True)
  2603. # Referenced field.
  2604. self.assertIs(operation.references_model('oTher'), True)
  2605. # Doesn't reference.
  2606. self.assertIs(operation.references_model('Whatever'), False)
  2607. def test_references_field_by_name(self):
  2608. operation = FieldOperation('MoDel', 'field', models.BooleanField(default=False))
  2609. self.assertIs(operation.references_field('model', 'field'), True)
  2610. def test_references_field_by_remote_field_model(self):
  2611. operation = FieldOperation('Model', 'field', models.ForeignKey('Other', models.CASCADE))
  2612. self.assertIs(operation.references_field('Other', 'whatever'), True)
  2613. self.assertIs(operation.references_field('Missing', 'whatever'), False)
  2614. def test_references_field_by_from_fields(self):
  2615. operation = FieldOperation(
  2616. 'Model', 'field', models.fields.related.ForeignObject('Other', models.CASCADE, ['from'], ['to'])
  2617. )
  2618. self.assertIs(operation.references_field('Model', 'from'), True)
  2619. self.assertIs(operation.references_field('Model', 'to'), False)
  2620. self.assertIs(operation.references_field('Other', 'from'), False)
  2621. self.assertIs(operation.references_field('Model', 'to'), False)
  2622. def test_references_field_by_to_fields(self):
  2623. operation = FieldOperation('Model', 'field', models.ForeignKey('Other', models.CASCADE, to_field='field'))
  2624. self.assertIs(operation.references_field('Other', 'field'), True)
  2625. self.assertIs(operation.references_field('Other', 'whatever'), False)
  2626. self.assertIs(operation.references_field('Missing', 'whatever'), False)
  2627. def test_references_field_by_through(self):
  2628. operation = FieldOperation('Model', 'field', models.ManyToManyField('Other', through='Through'))
  2629. self.assertIs(operation.references_field('Other', 'whatever'), True)
  2630. self.assertIs(operation.references_field('Through', 'whatever'), True)
  2631. self.assertIs(operation.references_field('Missing', 'whatever'), False)
  2632. def test_reference_field_by_through_fields(self):
  2633. operation = FieldOperation(
  2634. 'Model', 'field', models.ManyToManyField('Other', through='Through', through_fields=('first', 'second'))
  2635. )
  2636. self.assertIs(operation.references_field('Other', 'whatever'), True)
  2637. self.assertIs(operation.references_field('Through', 'whatever'), False)
  2638. self.assertIs(operation.references_field('Through', 'first'), True)
  2639. self.assertIs(operation.references_field('Through', 'second'), True)