test_operations.py 136 KB

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