test_operations.py 224 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445
  1. from django.core.exceptions import FieldDoesNotExist
  2. from django.db import IntegrityError, connection, migrations, models, transaction
  3. from django.db.migrations.migration import Migration
  4. from django.db.migrations.operations.fields import FieldOperation
  5. from django.db.migrations.state import ModelState, ProjectState
  6. from django.db.models.functions import Abs
  7. from django.db.transaction import atomic
  8. from django.test import (
  9. SimpleTestCase,
  10. ignore_warnings,
  11. override_settings,
  12. skipUnlessDBFeature,
  13. )
  14. from django.test.utils import CaptureQueriesContext
  15. from django.utils.deprecation import RemovedInDjango51Warning
  16. from .models import FoodManager, FoodQuerySet, UnicodeModel
  17. from .test_base import OperationTestBase
  18. class Mixin:
  19. pass
  20. class OperationTests(OperationTestBase):
  21. """
  22. Tests running the operations and making sure they do what they say they do.
  23. Each test looks at their state changing, and then their database operation -
  24. both forwards and backwards.
  25. """
  26. def test_create_model(self):
  27. """
  28. Tests the CreateModel operation.
  29. Most other tests use this operation as part of setup, so check failures
  30. here first.
  31. """
  32. operation = migrations.CreateModel(
  33. "Pony",
  34. [
  35. ("id", models.AutoField(primary_key=True)),
  36. ("pink", models.IntegerField(default=1)),
  37. ],
  38. )
  39. self.assertEqual(operation.describe(), "Create model Pony")
  40. self.assertEqual(operation.migration_name_fragment, "pony")
  41. # Test the state alteration
  42. project_state = ProjectState()
  43. new_state = project_state.clone()
  44. operation.state_forwards("test_crmo", new_state)
  45. self.assertEqual(new_state.models["test_crmo", "pony"].name, "Pony")
  46. self.assertEqual(len(new_state.models["test_crmo", "pony"].fields), 2)
  47. # Test the database alteration
  48. self.assertTableNotExists("test_crmo_pony")
  49. with connection.schema_editor() as editor:
  50. operation.database_forwards("test_crmo", editor, project_state, new_state)
  51. self.assertTableExists("test_crmo_pony")
  52. # And test reversal
  53. with connection.schema_editor() as editor:
  54. operation.database_backwards("test_crmo", editor, new_state, project_state)
  55. self.assertTableNotExists("test_crmo_pony")
  56. # And deconstruction
  57. definition = operation.deconstruct()
  58. self.assertEqual(definition[0], "CreateModel")
  59. self.assertEqual(definition[1], [])
  60. self.assertEqual(sorted(definition[2]), ["fields", "name"])
  61. # And default manager not in set
  62. operation = migrations.CreateModel(
  63. "Foo", fields=[], managers=[("objects", models.Manager())]
  64. )
  65. definition = operation.deconstruct()
  66. self.assertNotIn("managers", definition[2])
  67. def test_create_model_with_duplicate_field_name(self):
  68. with self.assertRaisesMessage(
  69. ValueError, "Found duplicate value pink in CreateModel fields argument."
  70. ):
  71. migrations.CreateModel(
  72. "Pony",
  73. [
  74. ("id", models.AutoField(primary_key=True)),
  75. ("pink", models.TextField()),
  76. ("pink", models.IntegerField(default=1)),
  77. ],
  78. )
  79. def test_create_model_with_duplicate_base(self):
  80. message = "Found duplicate value test_crmo.pony in CreateModel bases argument."
  81. with self.assertRaisesMessage(ValueError, message):
  82. migrations.CreateModel(
  83. "Pony",
  84. fields=[],
  85. bases=(
  86. "test_crmo.Pony",
  87. "test_crmo.Pony",
  88. ),
  89. )
  90. with self.assertRaisesMessage(ValueError, message):
  91. migrations.CreateModel(
  92. "Pony",
  93. fields=[],
  94. bases=(
  95. "test_crmo.Pony",
  96. "test_crmo.pony",
  97. ),
  98. )
  99. message = (
  100. "Found duplicate value migrations.unicodemodel in CreateModel bases "
  101. "argument."
  102. )
  103. with self.assertRaisesMessage(ValueError, message):
  104. migrations.CreateModel(
  105. "Pony",
  106. fields=[],
  107. bases=(
  108. UnicodeModel,
  109. UnicodeModel,
  110. ),
  111. )
  112. with self.assertRaisesMessage(ValueError, message):
  113. migrations.CreateModel(
  114. "Pony",
  115. fields=[],
  116. bases=(
  117. UnicodeModel,
  118. "migrations.unicodemodel",
  119. ),
  120. )
  121. with self.assertRaisesMessage(ValueError, message):
  122. migrations.CreateModel(
  123. "Pony",
  124. fields=[],
  125. bases=(
  126. UnicodeModel,
  127. "migrations.UnicodeModel",
  128. ),
  129. )
  130. message = (
  131. "Found duplicate value <class 'django.db.models.base.Model'> in "
  132. "CreateModel bases argument."
  133. )
  134. with self.assertRaisesMessage(ValueError, message):
  135. migrations.CreateModel(
  136. "Pony",
  137. fields=[],
  138. bases=(
  139. models.Model,
  140. models.Model,
  141. ),
  142. )
  143. message = (
  144. "Found duplicate value <class 'migrations.test_operations.Mixin'> in "
  145. "CreateModel bases argument."
  146. )
  147. with self.assertRaisesMessage(ValueError, message):
  148. migrations.CreateModel(
  149. "Pony",
  150. fields=[],
  151. bases=(
  152. Mixin,
  153. Mixin,
  154. ),
  155. )
  156. def test_create_model_with_duplicate_manager_name(self):
  157. with self.assertRaisesMessage(
  158. ValueError,
  159. "Found duplicate value objects in CreateModel managers argument.",
  160. ):
  161. migrations.CreateModel(
  162. "Pony",
  163. fields=[],
  164. managers=[
  165. ("objects", models.Manager()),
  166. ("objects", models.Manager()),
  167. ],
  168. )
  169. def test_create_model_with_unique_after(self):
  170. """
  171. Tests the CreateModel operation directly followed by an
  172. AlterUniqueTogether (bug #22844 - sqlite remake issues)
  173. """
  174. operation1 = migrations.CreateModel(
  175. "Pony",
  176. [
  177. ("id", models.AutoField(primary_key=True)),
  178. ("pink", models.IntegerField(default=1)),
  179. ],
  180. )
  181. operation2 = migrations.CreateModel(
  182. "Rider",
  183. [
  184. ("id", models.AutoField(primary_key=True)),
  185. ("number", models.IntegerField(default=1)),
  186. ("pony", models.ForeignKey("test_crmoua.Pony", models.CASCADE)),
  187. ],
  188. )
  189. operation3 = migrations.AlterUniqueTogether(
  190. "Rider",
  191. [
  192. ("number", "pony"),
  193. ],
  194. )
  195. # Test the database alteration
  196. project_state = ProjectState()
  197. self.assertTableNotExists("test_crmoua_pony")
  198. self.assertTableNotExists("test_crmoua_rider")
  199. with connection.schema_editor() as editor:
  200. new_state = project_state.clone()
  201. operation1.state_forwards("test_crmoua", new_state)
  202. operation1.database_forwards(
  203. "test_crmoua", editor, project_state, new_state
  204. )
  205. project_state, new_state = new_state, new_state.clone()
  206. operation2.state_forwards("test_crmoua", new_state)
  207. operation2.database_forwards(
  208. "test_crmoua", editor, project_state, new_state
  209. )
  210. project_state, new_state = new_state, new_state.clone()
  211. operation3.state_forwards("test_crmoua", new_state)
  212. operation3.database_forwards(
  213. "test_crmoua", editor, project_state, new_state
  214. )
  215. self.assertTableExists("test_crmoua_pony")
  216. self.assertTableExists("test_crmoua_rider")
  217. def test_create_model_m2m(self):
  218. """
  219. Test the creation of a model with a ManyToMany field and the
  220. auto-created "through" model.
  221. """
  222. project_state = self.set_up_test_model("test_crmomm")
  223. operation = migrations.CreateModel(
  224. "Stable",
  225. [
  226. ("id", models.AutoField(primary_key=True)),
  227. ("ponies", models.ManyToManyField("Pony", related_name="stables")),
  228. ],
  229. )
  230. # Test the state alteration
  231. new_state = project_state.clone()
  232. operation.state_forwards("test_crmomm", new_state)
  233. # Test the database alteration
  234. self.assertTableNotExists("test_crmomm_stable_ponies")
  235. with connection.schema_editor() as editor:
  236. operation.database_forwards("test_crmomm", editor, project_state, new_state)
  237. self.assertTableExists("test_crmomm_stable")
  238. self.assertTableExists("test_crmomm_stable_ponies")
  239. self.assertColumnNotExists("test_crmomm_stable", "ponies")
  240. # Make sure the M2M field actually works
  241. with atomic():
  242. Pony = new_state.apps.get_model("test_crmomm", "Pony")
  243. Stable = new_state.apps.get_model("test_crmomm", "Stable")
  244. stable = Stable.objects.create()
  245. p1 = Pony.objects.create(pink=False, weight=4.55)
  246. p2 = Pony.objects.create(pink=True, weight=5.43)
  247. stable.ponies.add(p1, p2)
  248. self.assertEqual(stable.ponies.count(), 2)
  249. stable.ponies.all().delete()
  250. # And test reversal
  251. with connection.schema_editor() as editor:
  252. operation.database_backwards(
  253. "test_crmomm", editor, new_state, project_state
  254. )
  255. self.assertTableNotExists("test_crmomm_stable")
  256. self.assertTableNotExists("test_crmomm_stable_ponies")
  257. @skipUnlessDBFeature("supports_collation_on_charfield", "supports_foreign_keys")
  258. def test_create_fk_models_to_pk_field_db_collation(self):
  259. """Creation of models with a FK to a PK with db_collation."""
  260. collation = connection.features.test_collations.get("non_default")
  261. if not collation:
  262. self.skipTest("Language collations are not supported.")
  263. app_label = "test_cfkmtopkfdbc"
  264. operations = [
  265. migrations.CreateModel(
  266. "Pony",
  267. [
  268. (
  269. "id",
  270. models.CharField(
  271. primary_key=True,
  272. max_length=10,
  273. db_collation=collation,
  274. ),
  275. ),
  276. ],
  277. )
  278. ]
  279. project_state = self.apply_operations(app_label, ProjectState(), operations)
  280. # ForeignKey.
  281. new_state = project_state.clone()
  282. operation = migrations.CreateModel(
  283. "Rider",
  284. [
  285. ("id", models.AutoField(primary_key=True)),
  286. ("pony", models.ForeignKey("Pony", models.CASCADE)),
  287. ],
  288. )
  289. operation.state_forwards(app_label, new_state)
  290. with connection.schema_editor() as editor:
  291. operation.database_forwards(app_label, editor, project_state, new_state)
  292. self.assertColumnCollation(f"{app_label}_rider", "pony_id", collation)
  293. # Reversal.
  294. with connection.schema_editor() as editor:
  295. operation.database_backwards(app_label, editor, new_state, project_state)
  296. # OneToOneField.
  297. new_state = project_state.clone()
  298. operation = migrations.CreateModel(
  299. "ShetlandPony",
  300. [
  301. (
  302. "pony",
  303. models.OneToOneField("Pony", models.CASCADE, primary_key=True),
  304. ),
  305. ("cuteness", models.IntegerField(default=1)),
  306. ],
  307. )
  308. operation.state_forwards(app_label, new_state)
  309. with connection.schema_editor() as editor:
  310. operation.database_forwards(app_label, editor, project_state, new_state)
  311. self.assertColumnCollation(f"{app_label}_shetlandpony", "pony_id", collation)
  312. # Reversal.
  313. with connection.schema_editor() as editor:
  314. operation.database_backwards(app_label, editor, new_state, project_state)
  315. def test_create_model_inheritance(self):
  316. """
  317. Tests the CreateModel operation on a multi-table inheritance setup.
  318. """
  319. project_state = self.set_up_test_model("test_crmoih")
  320. # Test the state alteration
  321. operation = migrations.CreateModel(
  322. "ShetlandPony",
  323. [
  324. (
  325. "pony_ptr",
  326. models.OneToOneField(
  327. "test_crmoih.Pony",
  328. models.CASCADE,
  329. auto_created=True,
  330. primary_key=True,
  331. to_field="id",
  332. serialize=False,
  333. ),
  334. ),
  335. ("cuteness", models.IntegerField(default=1)),
  336. ],
  337. )
  338. new_state = project_state.clone()
  339. operation.state_forwards("test_crmoih", new_state)
  340. self.assertIn(("test_crmoih", "shetlandpony"), new_state.models)
  341. # Test the database alteration
  342. self.assertTableNotExists("test_crmoih_shetlandpony")
  343. with connection.schema_editor() as editor:
  344. operation.database_forwards("test_crmoih", editor, project_state, new_state)
  345. self.assertTableExists("test_crmoih_shetlandpony")
  346. # And test reversal
  347. with connection.schema_editor() as editor:
  348. operation.database_backwards(
  349. "test_crmoih", editor, new_state, project_state
  350. )
  351. self.assertTableNotExists("test_crmoih_shetlandpony")
  352. def test_create_proxy_model(self):
  353. """
  354. CreateModel ignores proxy models.
  355. """
  356. project_state = self.set_up_test_model("test_crprmo")
  357. # Test the state alteration
  358. operation = migrations.CreateModel(
  359. "ProxyPony",
  360. [],
  361. options={"proxy": True},
  362. bases=("test_crprmo.Pony",),
  363. )
  364. self.assertEqual(operation.describe(), "Create proxy model ProxyPony")
  365. new_state = project_state.clone()
  366. operation.state_forwards("test_crprmo", new_state)
  367. self.assertIn(("test_crprmo", "proxypony"), new_state.models)
  368. # Test the database alteration
  369. self.assertTableNotExists("test_crprmo_proxypony")
  370. self.assertTableExists("test_crprmo_pony")
  371. with connection.schema_editor() as editor:
  372. operation.database_forwards("test_crprmo", editor, project_state, new_state)
  373. self.assertTableNotExists("test_crprmo_proxypony")
  374. self.assertTableExists("test_crprmo_pony")
  375. # And test reversal
  376. with connection.schema_editor() as editor:
  377. operation.database_backwards(
  378. "test_crprmo", editor, new_state, project_state
  379. )
  380. self.assertTableNotExists("test_crprmo_proxypony")
  381. self.assertTableExists("test_crprmo_pony")
  382. # And deconstruction
  383. definition = operation.deconstruct()
  384. self.assertEqual(definition[0], "CreateModel")
  385. self.assertEqual(definition[1], [])
  386. self.assertEqual(sorted(definition[2]), ["bases", "fields", "name", "options"])
  387. def test_create_unmanaged_model(self):
  388. """
  389. CreateModel ignores unmanaged models.
  390. """
  391. project_state = self.set_up_test_model("test_crummo")
  392. # Test the state alteration
  393. operation = migrations.CreateModel(
  394. "UnmanagedPony",
  395. [],
  396. options={"proxy": True},
  397. bases=("test_crummo.Pony",),
  398. )
  399. self.assertEqual(operation.describe(), "Create proxy model UnmanagedPony")
  400. new_state = project_state.clone()
  401. operation.state_forwards("test_crummo", new_state)
  402. self.assertIn(("test_crummo", "unmanagedpony"), new_state.models)
  403. # Test the database alteration
  404. self.assertTableNotExists("test_crummo_unmanagedpony")
  405. self.assertTableExists("test_crummo_pony")
  406. with connection.schema_editor() as editor:
  407. operation.database_forwards("test_crummo", editor, project_state, new_state)
  408. self.assertTableNotExists("test_crummo_unmanagedpony")
  409. self.assertTableExists("test_crummo_pony")
  410. # And test reversal
  411. with connection.schema_editor() as editor:
  412. operation.database_backwards(
  413. "test_crummo", editor, new_state, project_state
  414. )
  415. self.assertTableNotExists("test_crummo_unmanagedpony")
  416. self.assertTableExists("test_crummo_pony")
  417. @skipUnlessDBFeature("supports_table_check_constraints")
  418. def test_create_model_with_constraint(self):
  419. where = models.Q(pink__gt=2)
  420. check_constraint = models.CheckConstraint(
  421. check=where, name="test_constraint_pony_pink_gt_2"
  422. )
  423. operation = migrations.CreateModel(
  424. "Pony",
  425. [
  426. ("id", models.AutoField(primary_key=True)),
  427. ("pink", models.IntegerField(default=3)),
  428. ],
  429. options={"constraints": [check_constraint]},
  430. )
  431. # Test the state alteration
  432. project_state = ProjectState()
  433. new_state = project_state.clone()
  434. operation.state_forwards("test_crmo", new_state)
  435. self.assertEqual(
  436. len(new_state.models["test_crmo", "pony"].options["constraints"]), 1
  437. )
  438. # Test database alteration
  439. self.assertTableNotExists("test_crmo_pony")
  440. with connection.schema_editor() as editor:
  441. operation.database_forwards("test_crmo", editor, project_state, new_state)
  442. self.assertTableExists("test_crmo_pony")
  443. with connection.cursor() as cursor:
  444. with self.assertRaises(IntegrityError):
  445. cursor.execute("INSERT INTO test_crmo_pony (id, pink) VALUES (1, 1)")
  446. # Test reversal
  447. with connection.schema_editor() as editor:
  448. operation.database_backwards("test_crmo", editor, new_state, project_state)
  449. self.assertTableNotExists("test_crmo_pony")
  450. # Test deconstruction
  451. definition = operation.deconstruct()
  452. self.assertEqual(definition[0], "CreateModel")
  453. self.assertEqual(definition[1], [])
  454. self.assertEqual(definition[2]["options"]["constraints"], [check_constraint])
  455. @skipUnlessDBFeature("supports_table_check_constraints")
  456. def test_create_model_with_boolean_expression_in_check_constraint(self):
  457. app_label = "test_crmobechc"
  458. rawsql_constraint = models.CheckConstraint(
  459. check=models.expressions.RawSQL(
  460. "price < %s", (1000,), output_field=models.BooleanField()
  461. ),
  462. name=f"{app_label}_price_lt_1000_raw",
  463. )
  464. wrapper_constraint = models.CheckConstraint(
  465. check=models.expressions.ExpressionWrapper(
  466. models.Q(price__gt=500) | models.Q(price__lt=500),
  467. output_field=models.BooleanField(),
  468. ),
  469. name=f"{app_label}_price_neq_500_wrap",
  470. )
  471. operation = migrations.CreateModel(
  472. "Product",
  473. [
  474. ("id", models.AutoField(primary_key=True)),
  475. ("price", models.IntegerField(null=True)),
  476. ],
  477. options={"constraints": [rawsql_constraint, wrapper_constraint]},
  478. )
  479. project_state = ProjectState()
  480. new_state = project_state.clone()
  481. operation.state_forwards(app_label, new_state)
  482. # Add table.
  483. self.assertTableNotExists(app_label)
  484. with connection.schema_editor() as editor:
  485. operation.database_forwards(app_label, editor, project_state, new_state)
  486. self.assertTableExists(f"{app_label}_product")
  487. insert_sql = f"INSERT INTO {app_label}_product (id, price) VALUES (%d, %d)"
  488. with connection.cursor() as cursor:
  489. with self.assertRaises(IntegrityError):
  490. cursor.execute(insert_sql % (1, 1000))
  491. cursor.execute(insert_sql % (1, 999))
  492. with self.assertRaises(IntegrityError):
  493. cursor.execute(insert_sql % (2, 500))
  494. cursor.execute(insert_sql % (2, 499))
  495. def test_create_model_with_partial_unique_constraint(self):
  496. partial_unique_constraint = models.UniqueConstraint(
  497. fields=["pink"],
  498. condition=models.Q(weight__gt=5),
  499. name="test_constraint_pony_pink_for_weight_gt_5_uniq",
  500. )
  501. operation = migrations.CreateModel(
  502. "Pony",
  503. [
  504. ("id", models.AutoField(primary_key=True)),
  505. ("pink", models.IntegerField(default=3)),
  506. ("weight", models.FloatField()),
  507. ],
  508. options={"constraints": [partial_unique_constraint]},
  509. )
  510. # Test the state alteration
  511. project_state = ProjectState()
  512. new_state = project_state.clone()
  513. operation.state_forwards("test_crmo", new_state)
  514. self.assertEqual(
  515. len(new_state.models["test_crmo", "pony"].options["constraints"]), 1
  516. )
  517. # Test database alteration
  518. self.assertTableNotExists("test_crmo_pony")
  519. with connection.schema_editor() as editor:
  520. operation.database_forwards("test_crmo", editor, project_state, new_state)
  521. self.assertTableExists("test_crmo_pony")
  522. # Test constraint works
  523. Pony = new_state.apps.get_model("test_crmo", "Pony")
  524. Pony.objects.create(pink=1, weight=4.0)
  525. Pony.objects.create(pink=1, weight=4.0)
  526. Pony.objects.create(pink=1, weight=6.0)
  527. if connection.features.supports_partial_indexes:
  528. with self.assertRaises(IntegrityError):
  529. Pony.objects.create(pink=1, weight=7.0)
  530. else:
  531. Pony.objects.create(pink=1, weight=7.0)
  532. # Test reversal
  533. with connection.schema_editor() as editor:
  534. operation.database_backwards("test_crmo", editor, new_state, project_state)
  535. self.assertTableNotExists("test_crmo_pony")
  536. # Test deconstruction
  537. definition = operation.deconstruct()
  538. self.assertEqual(definition[0], "CreateModel")
  539. self.assertEqual(definition[1], [])
  540. self.assertEqual(
  541. definition[2]["options"]["constraints"], [partial_unique_constraint]
  542. )
  543. def test_create_model_with_deferred_unique_constraint(self):
  544. deferred_unique_constraint = models.UniqueConstraint(
  545. fields=["pink"],
  546. name="deferrable_pink_constraint",
  547. deferrable=models.Deferrable.DEFERRED,
  548. )
  549. operation = migrations.CreateModel(
  550. "Pony",
  551. [
  552. ("id", models.AutoField(primary_key=True)),
  553. ("pink", models.IntegerField(default=3)),
  554. ],
  555. options={"constraints": [deferred_unique_constraint]},
  556. )
  557. project_state = ProjectState()
  558. new_state = project_state.clone()
  559. operation.state_forwards("test_crmo", new_state)
  560. self.assertEqual(
  561. len(new_state.models["test_crmo", "pony"].options["constraints"]), 1
  562. )
  563. self.assertTableNotExists("test_crmo_pony")
  564. # Create table.
  565. with connection.schema_editor() as editor:
  566. operation.database_forwards("test_crmo", editor, project_state, new_state)
  567. self.assertTableExists("test_crmo_pony")
  568. Pony = new_state.apps.get_model("test_crmo", "Pony")
  569. Pony.objects.create(pink=1)
  570. if connection.features.supports_deferrable_unique_constraints:
  571. # Unique constraint is deferred.
  572. with transaction.atomic():
  573. obj = Pony.objects.create(pink=1)
  574. obj.pink = 2
  575. obj.save()
  576. # Constraint behavior can be changed with SET CONSTRAINTS.
  577. with self.assertRaises(IntegrityError):
  578. with transaction.atomic(), connection.cursor() as cursor:
  579. quoted_name = connection.ops.quote_name(
  580. deferred_unique_constraint.name
  581. )
  582. cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name)
  583. obj = Pony.objects.create(pink=1)
  584. obj.pink = 3
  585. obj.save()
  586. else:
  587. Pony.objects.create(pink=1)
  588. # Reversal.
  589. with connection.schema_editor() as editor:
  590. operation.database_backwards("test_crmo", editor, new_state, project_state)
  591. self.assertTableNotExists("test_crmo_pony")
  592. # Deconstruction.
  593. definition = operation.deconstruct()
  594. self.assertEqual(definition[0], "CreateModel")
  595. self.assertEqual(definition[1], [])
  596. self.assertEqual(
  597. definition[2]["options"]["constraints"],
  598. [deferred_unique_constraint],
  599. )
  600. @skipUnlessDBFeature("supports_covering_indexes")
  601. def test_create_model_with_covering_unique_constraint(self):
  602. covering_unique_constraint = models.UniqueConstraint(
  603. fields=["pink"],
  604. include=["weight"],
  605. name="test_constraint_pony_pink_covering_weight",
  606. )
  607. operation = migrations.CreateModel(
  608. "Pony",
  609. [
  610. ("id", models.AutoField(primary_key=True)),
  611. ("pink", models.IntegerField(default=3)),
  612. ("weight", models.FloatField()),
  613. ],
  614. options={"constraints": [covering_unique_constraint]},
  615. )
  616. project_state = ProjectState()
  617. new_state = project_state.clone()
  618. operation.state_forwards("test_crmo", new_state)
  619. self.assertEqual(
  620. len(new_state.models["test_crmo", "pony"].options["constraints"]), 1
  621. )
  622. self.assertTableNotExists("test_crmo_pony")
  623. # Create table.
  624. with connection.schema_editor() as editor:
  625. operation.database_forwards("test_crmo", editor, project_state, new_state)
  626. self.assertTableExists("test_crmo_pony")
  627. Pony = new_state.apps.get_model("test_crmo", "Pony")
  628. Pony.objects.create(pink=1, weight=4.0)
  629. with self.assertRaises(IntegrityError):
  630. Pony.objects.create(pink=1, weight=7.0)
  631. # Reversal.
  632. with connection.schema_editor() as editor:
  633. operation.database_backwards("test_crmo", editor, new_state, project_state)
  634. self.assertTableNotExists("test_crmo_pony")
  635. # Deconstruction.
  636. definition = operation.deconstruct()
  637. self.assertEqual(definition[0], "CreateModel")
  638. self.assertEqual(definition[1], [])
  639. self.assertEqual(
  640. definition[2]["options"]["constraints"],
  641. [covering_unique_constraint],
  642. )
  643. def test_create_model_managers(self):
  644. """
  645. The managers on a model are set.
  646. """
  647. project_state = self.set_up_test_model("test_cmoma")
  648. # Test the state alteration
  649. operation = migrations.CreateModel(
  650. "Food",
  651. fields=[
  652. ("id", models.AutoField(primary_key=True)),
  653. ],
  654. managers=[
  655. ("food_qs", FoodQuerySet.as_manager()),
  656. ("food_mgr", FoodManager("a", "b")),
  657. ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)),
  658. ],
  659. )
  660. self.assertEqual(operation.describe(), "Create model Food")
  661. new_state = project_state.clone()
  662. operation.state_forwards("test_cmoma", new_state)
  663. self.assertIn(("test_cmoma", "food"), new_state.models)
  664. managers = new_state.models["test_cmoma", "food"].managers
  665. self.assertEqual(managers[0][0], "food_qs")
  666. self.assertIsInstance(managers[0][1], models.Manager)
  667. self.assertEqual(managers[1][0], "food_mgr")
  668. self.assertIsInstance(managers[1][1], FoodManager)
  669. self.assertEqual(managers[1][1].args, ("a", "b", 1, 2))
  670. self.assertEqual(managers[2][0], "food_mgr_kwargs")
  671. self.assertIsInstance(managers[2][1], FoodManager)
  672. self.assertEqual(managers[2][1].args, ("x", "y", 3, 4))
  673. def test_delete_model(self):
  674. """
  675. Tests the DeleteModel operation.
  676. """
  677. project_state = self.set_up_test_model("test_dlmo")
  678. # Test the state alteration
  679. operation = migrations.DeleteModel("Pony")
  680. self.assertEqual(operation.describe(), "Delete model Pony")
  681. self.assertEqual(operation.migration_name_fragment, "delete_pony")
  682. new_state = project_state.clone()
  683. operation.state_forwards("test_dlmo", new_state)
  684. self.assertNotIn(("test_dlmo", "pony"), new_state.models)
  685. # Test the database alteration
  686. self.assertTableExists("test_dlmo_pony")
  687. with connection.schema_editor() as editor:
  688. operation.database_forwards("test_dlmo", editor, project_state, new_state)
  689. self.assertTableNotExists("test_dlmo_pony")
  690. # And test reversal
  691. with connection.schema_editor() as editor:
  692. operation.database_backwards("test_dlmo", editor, new_state, project_state)
  693. self.assertTableExists("test_dlmo_pony")
  694. # And deconstruction
  695. definition = operation.deconstruct()
  696. self.assertEqual(definition[0], "DeleteModel")
  697. self.assertEqual(definition[1], [])
  698. self.assertEqual(list(definition[2]), ["name"])
  699. def test_delete_proxy_model(self):
  700. """
  701. Tests the DeleteModel operation ignores proxy models.
  702. """
  703. project_state = self.set_up_test_model("test_dlprmo", proxy_model=True)
  704. # Test the state alteration
  705. operation = migrations.DeleteModel("ProxyPony")
  706. new_state = project_state.clone()
  707. operation.state_forwards("test_dlprmo", new_state)
  708. self.assertIn(("test_dlprmo", "proxypony"), project_state.models)
  709. self.assertNotIn(("test_dlprmo", "proxypony"), new_state.models)
  710. # Test the database alteration
  711. self.assertTableExists("test_dlprmo_pony")
  712. self.assertTableNotExists("test_dlprmo_proxypony")
  713. with connection.schema_editor() as editor:
  714. operation.database_forwards("test_dlprmo", editor, project_state, new_state)
  715. self.assertTableExists("test_dlprmo_pony")
  716. self.assertTableNotExists("test_dlprmo_proxypony")
  717. # And test reversal
  718. with connection.schema_editor() as editor:
  719. operation.database_backwards(
  720. "test_dlprmo", editor, new_state, project_state
  721. )
  722. self.assertTableExists("test_dlprmo_pony")
  723. self.assertTableNotExists("test_dlprmo_proxypony")
  724. def test_delete_mti_model(self):
  725. project_state = self.set_up_test_model("test_dlmtimo", mti_model=True)
  726. # Test the state alteration
  727. operation = migrations.DeleteModel("ShetlandPony")
  728. new_state = project_state.clone()
  729. operation.state_forwards("test_dlmtimo", new_state)
  730. self.assertIn(("test_dlmtimo", "shetlandpony"), project_state.models)
  731. self.assertNotIn(("test_dlmtimo", "shetlandpony"), new_state.models)
  732. # Test the database alteration
  733. self.assertTableExists("test_dlmtimo_pony")
  734. self.assertTableExists("test_dlmtimo_shetlandpony")
  735. self.assertColumnExists("test_dlmtimo_shetlandpony", "pony_ptr_id")
  736. with connection.schema_editor() as editor:
  737. operation.database_forwards(
  738. "test_dlmtimo", editor, project_state, new_state
  739. )
  740. self.assertTableExists("test_dlmtimo_pony")
  741. self.assertTableNotExists("test_dlmtimo_shetlandpony")
  742. # And test reversal
  743. with connection.schema_editor() as editor:
  744. operation.database_backwards(
  745. "test_dlmtimo", editor, new_state, project_state
  746. )
  747. self.assertTableExists("test_dlmtimo_pony")
  748. self.assertTableExists("test_dlmtimo_shetlandpony")
  749. self.assertColumnExists("test_dlmtimo_shetlandpony", "pony_ptr_id")
  750. def test_rename_model(self):
  751. """
  752. Tests the RenameModel operation.
  753. """
  754. project_state = self.set_up_test_model("test_rnmo", related_model=True)
  755. # Test the state alteration
  756. operation = migrations.RenameModel("Pony", "Horse")
  757. self.assertEqual(operation.describe(), "Rename model Pony to Horse")
  758. self.assertEqual(operation.migration_name_fragment, "rename_pony_horse")
  759. # Test initial state and database
  760. self.assertIn(("test_rnmo", "pony"), project_state.models)
  761. self.assertNotIn(("test_rnmo", "horse"), project_state.models)
  762. self.assertTableExists("test_rnmo_pony")
  763. self.assertTableNotExists("test_rnmo_horse")
  764. if connection.features.supports_foreign_keys:
  765. self.assertFKExists(
  766. "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id")
  767. )
  768. self.assertFKNotExists(
  769. "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id")
  770. )
  771. # Migrate forwards
  772. new_state = project_state.clone()
  773. atomic_rename = connection.features.supports_atomic_references_rename
  774. new_state = self.apply_operations(
  775. "test_rnmo", new_state, [operation], atomic=atomic_rename
  776. )
  777. # Test new state and database
  778. self.assertNotIn(("test_rnmo", "pony"), new_state.models)
  779. self.assertIn(("test_rnmo", "horse"), new_state.models)
  780. # RenameModel also repoints all incoming FKs and M2Ms
  781. self.assertEqual(
  782. new_state.models["test_rnmo", "rider"].fields["pony"].remote_field.model,
  783. "test_rnmo.Horse",
  784. )
  785. self.assertTableNotExists("test_rnmo_pony")
  786. self.assertTableExists("test_rnmo_horse")
  787. if connection.features.supports_foreign_keys:
  788. self.assertFKNotExists(
  789. "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id")
  790. )
  791. self.assertFKExists(
  792. "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id")
  793. )
  794. # Migrate backwards
  795. original_state = self.unapply_operations(
  796. "test_rnmo", project_state, [operation], atomic=atomic_rename
  797. )
  798. # Test original state and database
  799. self.assertIn(("test_rnmo", "pony"), original_state.models)
  800. self.assertNotIn(("test_rnmo", "horse"), original_state.models)
  801. self.assertEqual(
  802. original_state.models["test_rnmo", "rider"]
  803. .fields["pony"]
  804. .remote_field.model,
  805. "Pony",
  806. )
  807. self.assertTableExists("test_rnmo_pony")
  808. self.assertTableNotExists("test_rnmo_horse")
  809. if connection.features.supports_foreign_keys:
  810. self.assertFKExists(
  811. "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id")
  812. )
  813. self.assertFKNotExists(
  814. "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id")
  815. )
  816. # And deconstruction
  817. definition = operation.deconstruct()
  818. self.assertEqual(definition[0], "RenameModel")
  819. self.assertEqual(definition[1], [])
  820. self.assertEqual(definition[2], {"old_name": "Pony", "new_name": "Horse"})
  821. def test_rename_model_state_forwards(self):
  822. """
  823. RenameModel operations shouldn't trigger the caching of rendered apps
  824. on state without prior apps.
  825. """
  826. state = ProjectState()
  827. state.add_model(ModelState("migrations", "Foo", []))
  828. operation = migrations.RenameModel("Foo", "Bar")
  829. operation.state_forwards("migrations", state)
  830. self.assertNotIn("apps", state.__dict__)
  831. self.assertNotIn(("migrations", "foo"), state.models)
  832. self.assertIn(("migrations", "bar"), state.models)
  833. # Now with apps cached.
  834. apps = state.apps
  835. operation = migrations.RenameModel("Bar", "Foo")
  836. operation.state_forwards("migrations", state)
  837. self.assertIs(state.apps, apps)
  838. self.assertNotIn(("migrations", "bar"), state.models)
  839. self.assertIn(("migrations", "foo"), state.models)
  840. def test_rename_model_with_self_referential_fk(self):
  841. """
  842. Tests the RenameModel operation on model with self referential FK.
  843. """
  844. project_state = self.set_up_test_model("test_rmwsrf", related_model=True)
  845. # Test the state alteration
  846. operation = migrations.RenameModel("Rider", "HorseRider")
  847. self.assertEqual(operation.describe(), "Rename model Rider to HorseRider")
  848. new_state = project_state.clone()
  849. operation.state_forwards("test_rmwsrf", new_state)
  850. self.assertNotIn(("test_rmwsrf", "rider"), new_state.models)
  851. self.assertIn(("test_rmwsrf", "horserider"), new_state.models)
  852. # Remember, RenameModel also repoints all incoming FKs and M2Ms
  853. self.assertEqual(
  854. "self",
  855. new_state.models["test_rmwsrf", "horserider"]
  856. .fields["friend"]
  857. .remote_field.model,
  858. )
  859. HorseRider = new_state.apps.get_model("test_rmwsrf", "horserider")
  860. self.assertIs(
  861. HorseRider._meta.get_field("horserider").remote_field.model, HorseRider
  862. )
  863. # Test the database alteration
  864. self.assertTableExists("test_rmwsrf_rider")
  865. self.assertTableNotExists("test_rmwsrf_horserider")
  866. if connection.features.supports_foreign_keys:
  867. self.assertFKExists(
  868. "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id")
  869. )
  870. self.assertFKNotExists(
  871. "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id")
  872. )
  873. atomic_rename = connection.features.supports_atomic_references_rename
  874. with connection.schema_editor(atomic=atomic_rename) as editor:
  875. operation.database_forwards("test_rmwsrf", editor, project_state, new_state)
  876. self.assertTableNotExists("test_rmwsrf_rider")
  877. self.assertTableExists("test_rmwsrf_horserider")
  878. if connection.features.supports_foreign_keys:
  879. self.assertFKNotExists(
  880. "test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_rider", "id")
  881. )
  882. self.assertFKExists(
  883. "test_rmwsrf_horserider",
  884. ["friend_id"],
  885. ("test_rmwsrf_horserider", "id"),
  886. )
  887. # And test reversal
  888. with connection.schema_editor(atomic=atomic_rename) as editor:
  889. operation.database_backwards(
  890. "test_rmwsrf", editor, new_state, project_state
  891. )
  892. self.assertTableExists("test_rmwsrf_rider")
  893. self.assertTableNotExists("test_rmwsrf_horserider")
  894. if connection.features.supports_foreign_keys:
  895. self.assertFKExists(
  896. "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id")
  897. )
  898. self.assertFKNotExists(
  899. "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id")
  900. )
  901. def test_rename_model_with_superclass_fk(self):
  902. """
  903. Tests the RenameModel operation on a model which has a superclass that
  904. has a foreign key.
  905. """
  906. project_state = self.set_up_test_model(
  907. "test_rmwsc", related_model=True, mti_model=True
  908. )
  909. # Test the state alteration
  910. operation = migrations.RenameModel("ShetlandPony", "LittleHorse")
  911. self.assertEqual(
  912. operation.describe(), "Rename model ShetlandPony to LittleHorse"
  913. )
  914. new_state = project_state.clone()
  915. operation.state_forwards("test_rmwsc", new_state)
  916. self.assertNotIn(("test_rmwsc", "shetlandpony"), new_state.models)
  917. self.assertIn(("test_rmwsc", "littlehorse"), new_state.models)
  918. # RenameModel shouldn't repoint the superclass's relations, only local ones
  919. self.assertEqual(
  920. project_state.models["test_rmwsc", "rider"]
  921. .fields["pony"]
  922. .remote_field.model,
  923. new_state.models["test_rmwsc", "rider"].fields["pony"].remote_field.model,
  924. )
  925. # Before running the migration we have a table for Shetland Pony, not
  926. # Little Horse.
  927. self.assertTableExists("test_rmwsc_shetlandpony")
  928. self.assertTableNotExists("test_rmwsc_littlehorse")
  929. if connection.features.supports_foreign_keys:
  930. # and the foreign key on rider points to pony, not shetland pony
  931. self.assertFKExists(
  932. "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id")
  933. )
  934. self.assertFKNotExists(
  935. "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_shetlandpony", "id")
  936. )
  937. with connection.schema_editor(
  938. atomic=connection.features.supports_atomic_references_rename
  939. ) as editor:
  940. operation.database_forwards("test_rmwsc", editor, project_state, new_state)
  941. # Now we have a little horse table, not shetland pony
  942. self.assertTableNotExists("test_rmwsc_shetlandpony")
  943. self.assertTableExists("test_rmwsc_littlehorse")
  944. if connection.features.supports_foreign_keys:
  945. # but the Foreign keys still point at pony, not little horse
  946. self.assertFKExists(
  947. "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id")
  948. )
  949. self.assertFKNotExists(
  950. "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_littlehorse", "id")
  951. )
  952. def test_rename_model_with_self_referential_m2m(self):
  953. app_label = "test_rename_model_with_self_referential_m2m"
  954. project_state = self.apply_operations(
  955. app_label,
  956. ProjectState(),
  957. operations=[
  958. migrations.CreateModel(
  959. "ReflexivePony",
  960. fields=[
  961. ("id", models.AutoField(primary_key=True)),
  962. ("ponies", models.ManyToManyField("self")),
  963. ],
  964. ),
  965. ],
  966. )
  967. project_state = self.apply_operations(
  968. app_label,
  969. project_state,
  970. operations=[
  971. migrations.RenameModel("ReflexivePony", "ReflexivePony2"),
  972. ],
  973. atomic=connection.features.supports_atomic_references_rename,
  974. )
  975. Pony = project_state.apps.get_model(app_label, "ReflexivePony2")
  976. pony = Pony.objects.create()
  977. pony.ponies.add(pony)
  978. def test_rename_model_with_m2m(self):
  979. app_label = "test_rename_model_with_m2m"
  980. project_state = self.apply_operations(
  981. app_label,
  982. ProjectState(),
  983. operations=[
  984. migrations.CreateModel(
  985. "Rider",
  986. fields=[
  987. ("id", models.AutoField(primary_key=True)),
  988. ],
  989. ),
  990. migrations.CreateModel(
  991. "Pony",
  992. fields=[
  993. ("id", models.AutoField(primary_key=True)),
  994. ("riders", models.ManyToManyField("Rider")),
  995. ],
  996. ),
  997. ],
  998. )
  999. Pony = project_state.apps.get_model(app_label, "Pony")
  1000. Rider = project_state.apps.get_model(app_label, "Rider")
  1001. pony = Pony.objects.create()
  1002. rider = Rider.objects.create()
  1003. pony.riders.add(rider)
  1004. project_state = self.apply_operations(
  1005. app_label,
  1006. project_state,
  1007. operations=[
  1008. migrations.RenameModel("Pony", "Pony2"),
  1009. ],
  1010. atomic=connection.features.supports_atomic_references_rename,
  1011. )
  1012. Pony = project_state.apps.get_model(app_label, "Pony2")
  1013. Rider = project_state.apps.get_model(app_label, "Rider")
  1014. pony = Pony.objects.create()
  1015. rider = Rider.objects.create()
  1016. pony.riders.add(rider)
  1017. self.assertEqual(Pony.objects.count(), 2)
  1018. self.assertEqual(Rider.objects.count(), 2)
  1019. self.assertEqual(
  1020. Pony._meta.get_field("riders").remote_field.through.objects.count(), 2
  1021. )
  1022. def test_rename_model_with_db_table_rename_m2m(self):
  1023. app_label = "test_rmwdbrm2m"
  1024. project_state = self.apply_operations(
  1025. app_label,
  1026. ProjectState(),
  1027. operations=[
  1028. migrations.CreateModel(
  1029. "Rider",
  1030. fields=[
  1031. ("id", models.AutoField(primary_key=True)),
  1032. ],
  1033. ),
  1034. migrations.CreateModel(
  1035. "Pony",
  1036. fields=[
  1037. ("id", models.AutoField(primary_key=True)),
  1038. ("riders", models.ManyToManyField("Rider")),
  1039. ],
  1040. options={"db_table": "pony"},
  1041. ),
  1042. ],
  1043. )
  1044. new_state = project_state.clone()
  1045. operation = migrations.RenameModel("Pony", "PinkPony")
  1046. operation.state_forwards(app_label, new_state)
  1047. with connection.schema_editor() as editor:
  1048. operation.database_forwards(app_label, editor, project_state, new_state)
  1049. Pony = new_state.apps.get_model(app_label, "PinkPony")
  1050. Rider = new_state.apps.get_model(app_label, "Rider")
  1051. pony = Pony.objects.create()
  1052. rider = Rider.objects.create()
  1053. pony.riders.add(rider)
  1054. def test_rename_m2m_target_model(self):
  1055. app_label = "test_rename_m2m_target_model"
  1056. project_state = self.apply_operations(
  1057. app_label,
  1058. ProjectState(),
  1059. operations=[
  1060. migrations.CreateModel(
  1061. "Rider",
  1062. fields=[
  1063. ("id", models.AutoField(primary_key=True)),
  1064. ],
  1065. ),
  1066. migrations.CreateModel(
  1067. "Pony",
  1068. fields=[
  1069. ("id", models.AutoField(primary_key=True)),
  1070. ("riders", models.ManyToManyField("Rider")),
  1071. ],
  1072. ),
  1073. ],
  1074. )
  1075. Pony = project_state.apps.get_model(app_label, "Pony")
  1076. Rider = project_state.apps.get_model(app_label, "Rider")
  1077. pony = Pony.objects.create()
  1078. rider = Rider.objects.create()
  1079. pony.riders.add(rider)
  1080. project_state = self.apply_operations(
  1081. app_label,
  1082. project_state,
  1083. operations=[
  1084. migrations.RenameModel("Rider", "Rider2"),
  1085. ],
  1086. atomic=connection.features.supports_atomic_references_rename,
  1087. )
  1088. Pony = project_state.apps.get_model(app_label, "Pony")
  1089. Rider = project_state.apps.get_model(app_label, "Rider2")
  1090. pony = Pony.objects.create()
  1091. rider = Rider.objects.create()
  1092. pony.riders.add(rider)
  1093. self.assertEqual(Pony.objects.count(), 2)
  1094. self.assertEqual(Rider.objects.count(), 2)
  1095. self.assertEqual(
  1096. Pony._meta.get_field("riders").remote_field.through.objects.count(), 2
  1097. )
  1098. def test_rename_m2m_through_model(self):
  1099. app_label = "test_rename_through"
  1100. project_state = self.apply_operations(
  1101. app_label,
  1102. ProjectState(),
  1103. operations=[
  1104. migrations.CreateModel(
  1105. "Rider",
  1106. fields=[
  1107. ("id", models.AutoField(primary_key=True)),
  1108. ],
  1109. ),
  1110. migrations.CreateModel(
  1111. "Pony",
  1112. fields=[
  1113. ("id", models.AutoField(primary_key=True)),
  1114. ],
  1115. ),
  1116. migrations.CreateModel(
  1117. "PonyRider",
  1118. fields=[
  1119. ("id", models.AutoField(primary_key=True)),
  1120. (
  1121. "rider",
  1122. models.ForeignKey(
  1123. "test_rename_through.Rider", models.CASCADE
  1124. ),
  1125. ),
  1126. (
  1127. "pony",
  1128. models.ForeignKey(
  1129. "test_rename_through.Pony", models.CASCADE
  1130. ),
  1131. ),
  1132. ],
  1133. ),
  1134. migrations.AddField(
  1135. "Pony",
  1136. "riders",
  1137. models.ManyToManyField(
  1138. "test_rename_through.Rider",
  1139. through="test_rename_through.PonyRider",
  1140. ),
  1141. ),
  1142. ],
  1143. )
  1144. Pony = project_state.apps.get_model(app_label, "Pony")
  1145. Rider = project_state.apps.get_model(app_label, "Rider")
  1146. PonyRider = project_state.apps.get_model(app_label, "PonyRider")
  1147. pony = Pony.objects.create()
  1148. rider = Rider.objects.create()
  1149. PonyRider.objects.create(pony=pony, rider=rider)
  1150. project_state = self.apply_operations(
  1151. app_label,
  1152. project_state,
  1153. operations=[
  1154. migrations.RenameModel("PonyRider", "PonyRider2"),
  1155. ],
  1156. )
  1157. Pony = project_state.apps.get_model(app_label, "Pony")
  1158. Rider = project_state.apps.get_model(app_label, "Rider")
  1159. PonyRider = project_state.apps.get_model(app_label, "PonyRider2")
  1160. pony = Pony.objects.first()
  1161. rider = Rider.objects.create()
  1162. PonyRider.objects.create(pony=pony, rider=rider)
  1163. self.assertEqual(Pony.objects.count(), 1)
  1164. self.assertEqual(Rider.objects.count(), 2)
  1165. self.assertEqual(PonyRider.objects.count(), 2)
  1166. self.assertEqual(pony.riders.count(), 2)
  1167. def test_rename_m2m_model_after_rename_field(self):
  1168. """RenameModel renames a many-to-many column after a RenameField."""
  1169. app_label = "test_rename_multiple"
  1170. project_state = self.apply_operations(
  1171. app_label,
  1172. ProjectState(),
  1173. operations=[
  1174. migrations.CreateModel(
  1175. "Pony",
  1176. fields=[
  1177. ("id", models.AutoField(primary_key=True)),
  1178. ("name", models.CharField(max_length=20)),
  1179. ],
  1180. ),
  1181. migrations.CreateModel(
  1182. "Rider",
  1183. fields=[
  1184. ("id", models.AutoField(primary_key=True)),
  1185. (
  1186. "pony",
  1187. models.ForeignKey(
  1188. "test_rename_multiple.Pony", models.CASCADE
  1189. ),
  1190. ),
  1191. ],
  1192. ),
  1193. migrations.CreateModel(
  1194. "PonyRider",
  1195. fields=[
  1196. ("id", models.AutoField(primary_key=True)),
  1197. ("riders", models.ManyToManyField("Rider")),
  1198. ],
  1199. ),
  1200. migrations.RenameField(
  1201. model_name="pony", old_name="name", new_name="fancy_name"
  1202. ),
  1203. migrations.RenameModel(old_name="Rider", new_name="Jockey"),
  1204. ],
  1205. atomic=connection.features.supports_atomic_references_rename,
  1206. )
  1207. Pony = project_state.apps.get_model(app_label, "Pony")
  1208. Jockey = project_state.apps.get_model(app_label, "Jockey")
  1209. PonyRider = project_state.apps.get_model(app_label, "PonyRider")
  1210. # No "no such column" error means the column was renamed correctly.
  1211. pony = Pony.objects.create(fancy_name="a good name")
  1212. jockey = Jockey.objects.create(pony=pony)
  1213. ponyrider = PonyRider.objects.create()
  1214. ponyrider.riders.add(jockey)
  1215. def test_add_field(self):
  1216. """
  1217. Tests the AddField operation.
  1218. """
  1219. # Test the state alteration
  1220. operation = migrations.AddField(
  1221. "Pony",
  1222. "height",
  1223. models.FloatField(null=True, default=5),
  1224. )
  1225. self.assertEqual(operation.describe(), "Add field height to Pony")
  1226. self.assertEqual(operation.migration_name_fragment, "pony_height")
  1227. project_state, new_state = self.make_test_state("test_adfl", operation)
  1228. self.assertEqual(len(new_state.models["test_adfl", "pony"].fields), 4)
  1229. field = new_state.models["test_adfl", "pony"].fields["height"]
  1230. self.assertEqual(field.default, 5)
  1231. # Test the database alteration
  1232. self.assertColumnNotExists("test_adfl_pony", "height")
  1233. with connection.schema_editor() as editor:
  1234. operation.database_forwards("test_adfl", editor, project_state, new_state)
  1235. self.assertColumnExists("test_adfl_pony", "height")
  1236. # And test reversal
  1237. with connection.schema_editor() as editor:
  1238. operation.database_backwards("test_adfl", editor, new_state, project_state)
  1239. self.assertColumnNotExists("test_adfl_pony", "height")
  1240. # And deconstruction
  1241. definition = operation.deconstruct()
  1242. self.assertEqual(definition[0], "AddField")
  1243. self.assertEqual(definition[1], [])
  1244. self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"])
  1245. def test_add_charfield(self):
  1246. """
  1247. Tests the AddField operation on TextField.
  1248. """
  1249. project_state = self.set_up_test_model("test_adchfl")
  1250. Pony = project_state.apps.get_model("test_adchfl", "Pony")
  1251. pony = Pony.objects.create(weight=42)
  1252. new_state = self.apply_operations(
  1253. "test_adchfl",
  1254. project_state,
  1255. [
  1256. migrations.AddField(
  1257. "Pony",
  1258. "text",
  1259. models.CharField(max_length=10, default="some text"),
  1260. ),
  1261. migrations.AddField(
  1262. "Pony",
  1263. "empty",
  1264. models.CharField(max_length=10, default=""),
  1265. ),
  1266. # If not properly quoted digits would be interpreted as an int.
  1267. migrations.AddField(
  1268. "Pony",
  1269. "digits",
  1270. models.CharField(max_length=10, default="42"),
  1271. ),
  1272. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  1273. migrations.AddField(
  1274. "Pony",
  1275. "quotes",
  1276. models.CharField(max_length=10, default='"\'"'),
  1277. ),
  1278. ],
  1279. )
  1280. Pony = new_state.apps.get_model("test_adchfl", "Pony")
  1281. pony = Pony.objects.get(pk=pony.pk)
  1282. self.assertEqual(pony.text, "some text")
  1283. self.assertEqual(pony.empty, "")
  1284. self.assertEqual(pony.digits, "42")
  1285. self.assertEqual(pony.quotes, '"\'"')
  1286. def test_add_textfield(self):
  1287. """
  1288. Tests the AddField operation on TextField.
  1289. """
  1290. project_state = self.set_up_test_model("test_adtxtfl")
  1291. Pony = project_state.apps.get_model("test_adtxtfl", "Pony")
  1292. pony = Pony.objects.create(weight=42)
  1293. new_state = self.apply_operations(
  1294. "test_adtxtfl",
  1295. project_state,
  1296. [
  1297. migrations.AddField(
  1298. "Pony",
  1299. "text",
  1300. models.TextField(default="some text"),
  1301. ),
  1302. migrations.AddField(
  1303. "Pony",
  1304. "empty",
  1305. models.TextField(default=""),
  1306. ),
  1307. # If not properly quoted digits would be interpreted as an int.
  1308. migrations.AddField(
  1309. "Pony",
  1310. "digits",
  1311. models.TextField(default="42"),
  1312. ),
  1313. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  1314. migrations.AddField(
  1315. "Pony",
  1316. "quotes",
  1317. models.TextField(default='"\'"'),
  1318. ),
  1319. ],
  1320. )
  1321. Pony = new_state.apps.get_model("test_adtxtfl", "Pony")
  1322. pony = Pony.objects.get(pk=pony.pk)
  1323. self.assertEqual(pony.text, "some text")
  1324. self.assertEqual(pony.empty, "")
  1325. self.assertEqual(pony.digits, "42")
  1326. self.assertEqual(pony.quotes, '"\'"')
  1327. def test_add_binaryfield(self):
  1328. """
  1329. Tests the AddField operation on TextField/BinaryField.
  1330. """
  1331. project_state = self.set_up_test_model("test_adbinfl")
  1332. Pony = project_state.apps.get_model("test_adbinfl", "Pony")
  1333. pony = Pony.objects.create(weight=42)
  1334. new_state = self.apply_operations(
  1335. "test_adbinfl",
  1336. project_state,
  1337. [
  1338. migrations.AddField(
  1339. "Pony",
  1340. "blob",
  1341. models.BinaryField(default=b"some text"),
  1342. ),
  1343. migrations.AddField(
  1344. "Pony",
  1345. "empty",
  1346. models.BinaryField(default=b""),
  1347. ),
  1348. # If not properly quoted digits would be interpreted as an int.
  1349. migrations.AddField(
  1350. "Pony",
  1351. "digits",
  1352. models.BinaryField(default=b"42"),
  1353. ),
  1354. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  1355. migrations.AddField(
  1356. "Pony",
  1357. "quotes",
  1358. models.BinaryField(default=b'"\'"'),
  1359. ),
  1360. ],
  1361. )
  1362. Pony = new_state.apps.get_model("test_adbinfl", "Pony")
  1363. pony = Pony.objects.get(pk=pony.pk)
  1364. # SQLite returns buffer/memoryview, cast to bytes for checking.
  1365. self.assertEqual(bytes(pony.blob), b"some text")
  1366. self.assertEqual(bytes(pony.empty), b"")
  1367. self.assertEqual(bytes(pony.digits), b"42")
  1368. self.assertEqual(bytes(pony.quotes), b'"\'"')
  1369. def test_column_name_quoting(self):
  1370. """
  1371. Column names that are SQL keywords shouldn't cause problems when used
  1372. in migrations (#22168).
  1373. """
  1374. project_state = self.set_up_test_model("test_regr22168")
  1375. operation = migrations.AddField(
  1376. "Pony",
  1377. "order",
  1378. models.IntegerField(default=0),
  1379. )
  1380. new_state = project_state.clone()
  1381. operation.state_forwards("test_regr22168", new_state)
  1382. with connection.schema_editor() as editor:
  1383. operation.database_forwards(
  1384. "test_regr22168", editor, project_state, new_state
  1385. )
  1386. self.assertColumnExists("test_regr22168_pony", "order")
  1387. def test_add_field_preserve_default(self):
  1388. """
  1389. Tests the AddField operation's state alteration
  1390. when preserve_default = False.
  1391. """
  1392. project_state = self.set_up_test_model("test_adflpd")
  1393. # Test the state alteration
  1394. operation = migrations.AddField(
  1395. "Pony",
  1396. "height",
  1397. models.FloatField(null=True, default=4),
  1398. preserve_default=False,
  1399. )
  1400. new_state = project_state.clone()
  1401. operation.state_forwards("test_adflpd", new_state)
  1402. self.assertEqual(len(new_state.models["test_adflpd", "pony"].fields), 4)
  1403. field = new_state.models["test_adflpd", "pony"].fields["height"]
  1404. self.assertEqual(field.default, models.NOT_PROVIDED)
  1405. # Test the database alteration
  1406. project_state.apps.get_model("test_adflpd", "pony").objects.create(
  1407. weight=4,
  1408. )
  1409. self.assertColumnNotExists("test_adflpd_pony", "height")
  1410. with connection.schema_editor() as editor:
  1411. operation.database_forwards("test_adflpd", editor, project_state, new_state)
  1412. self.assertColumnExists("test_adflpd_pony", "height")
  1413. # And deconstruction
  1414. definition = operation.deconstruct()
  1415. self.assertEqual(definition[0], "AddField")
  1416. self.assertEqual(definition[1], [])
  1417. self.assertEqual(
  1418. sorted(definition[2]), ["field", "model_name", "name", "preserve_default"]
  1419. )
  1420. def test_add_field_m2m(self):
  1421. """
  1422. Tests the AddField operation with a ManyToManyField.
  1423. """
  1424. project_state = self.set_up_test_model("test_adflmm", second_model=True)
  1425. # Test the state alteration
  1426. operation = migrations.AddField(
  1427. "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies")
  1428. )
  1429. new_state = project_state.clone()
  1430. operation.state_forwards("test_adflmm", new_state)
  1431. self.assertEqual(len(new_state.models["test_adflmm", "pony"].fields), 4)
  1432. # Test the database alteration
  1433. self.assertTableNotExists("test_adflmm_pony_stables")
  1434. with connection.schema_editor() as editor:
  1435. operation.database_forwards("test_adflmm", editor, project_state, new_state)
  1436. self.assertTableExists("test_adflmm_pony_stables")
  1437. self.assertColumnNotExists("test_adflmm_pony", "stables")
  1438. # Make sure the M2M field actually works
  1439. with atomic():
  1440. Pony = new_state.apps.get_model("test_adflmm", "Pony")
  1441. p = Pony.objects.create(pink=False, weight=4.55)
  1442. p.stables.create()
  1443. self.assertEqual(p.stables.count(), 1)
  1444. p.stables.all().delete()
  1445. # And test reversal
  1446. with connection.schema_editor() as editor:
  1447. operation.database_backwards(
  1448. "test_adflmm", editor, new_state, project_state
  1449. )
  1450. self.assertTableNotExists("test_adflmm_pony_stables")
  1451. def test_alter_field_m2m(self):
  1452. project_state = self.set_up_test_model("test_alflmm", second_model=True)
  1453. project_state = self.apply_operations(
  1454. "test_alflmm",
  1455. project_state,
  1456. operations=[
  1457. migrations.AddField(
  1458. "Pony",
  1459. "stables",
  1460. models.ManyToManyField("Stable", related_name="ponies"),
  1461. )
  1462. ],
  1463. )
  1464. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1465. self.assertFalse(Pony._meta.get_field("stables").blank)
  1466. project_state = self.apply_operations(
  1467. "test_alflmm",
  1468. project_state,
  1469. operations=[
  1470. migrations.AlterField(
  1471. "Pony",
  1472. "stables",
  1473. models.ManyToManyField(
  1474. to="Stable", related_name="ponies", blank=True
  1475. ),
  1476. )
  1477. ],
  1478. )
  1479. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1480. self.assertTrue(Pony._meta.get_field("stables").blank)
  1481. def test_repoint_field_m2m(self):
  1482. project_state = self.set_up_test_model(
  1483. "test_alflmm", second_model=True, third_model=True
  1484. )
  1485. project_state = self.apply_operations(
  1486. "test_alflmm",
  1487. project_state,
  1488. operations=[
  1489. migrations.AddField(
  1490. "Pony",
  1491. "places",
  1492. models.ManyToManyField("Stable", related_name="ponies"),
  1493. )
  1494. ],
  1495. )
  1496. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1497. project_state = self.apply_operations(
  1498. "test_alflmm",
  1499. project_state,
  1500. operations=[
  1501. migrations.AlterField(
  1502. "Pony",
  1503. "places",
  1504. models.ManyToManyField(to="Van", related_name="ponies"),
  1505. )
  1506. ],
  1507. )
  1508. # Ensure the new field actually works
  1509. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1510. p = Pony.objects.create(pink=False, weight=4.55)
  1511. p.places.create()
  1512. self.assertEqual(p.places.count(), 1)
  1513. p.places.all().delete()
  1514. def test_remove_field_m2m(self):
  1515. project_state = self.set_up_test_model("test_rmflmm", second_model=True)
  1516. project_state = self.apply_operations(
  1517. "test_rmflmm",
  1518. project_state,
  1519. operations=[
  1520. migrations.AddField(
  1521. "Pony",
  1522. "stables",
  1523. models.ManyToManyField("Stable", related_name="ponies"),
  1524. )
  1525. ],
  1526. )
  1527. self.assertTableExists("test_rmflmm_pony_stables")
  1528. with_field_state = project_state.clone()
  1529. operations = [migrations.RemoveField("Pony", "stables")]
  1530. project_state = self.apply_operations(
  1531. "test_rmflmm", project_state, operations=operations
  1532. )
  1533. self.assertTableNotExists("test_rmflmm_pony_stables")
  1534. # And test reversal
  1535. self.unapply_operations("test_rmflmm", with_field_state, operations=operations)
  1536. self.assertTableExists("test_rmflmm_pony_stables")
  1537. def test_remove_field_m2m_with_through(self):
  1538. project_state = self.set_up_test_model("test_rmflmmwt", second_model=True)
  1539. self.assertTableNotExists("test_rmflmmwt_ponystables")
  1540. project_state = self.apply_operations(
  1541. "test_rmflmmwt",
  1542. project_state,
  1543. operations=[
  1544. migrations.CreateModel(
  1545. "PonyStables",
  1546. fields=[
  1547. (
  1548. "pony",
  1549. models.ForeignKey("test_rmflmmwt.Pony", models.CASCADE),
  1550. ),
  1551. (
  1552. "stable",
  1553. models.ForeignKey("test_rmflmmwt.Stable", models.CASCADE),
  1554. ),
  1555. ],
  1556. ),
  1557. migrations.AddField(
  1558. "Pony",
  1559. "stables",
  1560. models.ManyToManyField(
  1561. "Stable",
  1562. related_name="ponies",
  1563. through="test_rmflmmwt.PonyStables",
  1564. ),
  1565. ),
  1566. ],
  1567. )
  1568. self.assertTableExists("test_rmflmmwt_ponystables")
  1569. operations = [
  1570. migrations.RemoveField("Pony", "stables"),
  1571. migrations.DeleteModel("PonyStables"),
  1572. ]
  1573. self.apply_operations("test_rmflmmwt", project_state, operations=operations)
  1574. def test_remove_field(self):
  1575. """
  1576. Tests the RemoveField operation.
  1577. """
  1578. project_state = self.set_up_test_model("test_rmfl")
  1579. # Test the state alteration
  1580. operation = migrations.RemoveField("Pony", "pink")
  1581. self.assertEqual(operation.describe(), "Remove field pink from Pony")
  1582. self.assertEqual(operation.migration_name_fragment, "remove_pony_pink")
  1583. new_state = project_state.clone()
  1584. operation.state_forwards("test_rmfl", new_state)
  1585. self.assertEqual(len(new_state.models["test_rmfl", "pony"].fields), 2)
  1586. # Test the database alteration
  1587. self.assertColumnExists("test_rmfl_pony", "pink")
  1588. with connection.schema_editor() as editor:
  1589. operation.database_forwards("test_rmfl", editor, project_state, new_state)
  1590. self.assertColumnNotExists("test_rmfl_pony", "pink")
  1591. # And test reversal
  1592. with connection.schema_editor() as editor:
  1593. operation.database_backwards("test_rmfl", editor, new_state, project_state)
  1594. self.assertColumnExists("test_rmfl_pony", "pink")
  1595. # And deconstruction
  1596. definition = operation.deconstruct()
  1597. self.assertEqual(definition[0], "RemoveField")
  1598. self.assertEqual(definition[1], [])
  1599. self.assertEqual(definition[2], {"model_name": "Pony", "name": "pink"})
  1600. def test_remove_fk(self):
  1601. """
  1602. Tests the RemoveField operation on a foreign key.
  1603. """
  1604. project_state = self.set_up_test_model("test_rfk", related_model=True)
  1605. self.assertColumnExists("test_rfk_rider", "pony_id")
  1606. operation = migrations.RemoveField("Rider", "pony")
  1607. new_state = project_state.clone()
  1608. operation.state_forwards("test_rfk", new_state)
  1609. with connection.schema_editor() as editor:
  1610. operation.database_forwards("test_rfk", editor, project_state, new_state)
  1611. self.assertColumnNotExists("test_rfk_rider", "pony_id")
  1612. with connection.schema_editor() as editor:
  1613. operation.database_backwards("test_rfk", editor, new_state, project_state)
  1614. self.assertColumnExists("test_rfk_rider", "pony_id")
  1615. def test_alter_model_table(self):
  1616. """
  1617. Tests the AlterModelTable operation.
  1618. """
  1619. project_state = self.set_up_test_model("test_almota")
  1620. # Test the state alteration
  1621. operation = migrations.AlterModelTable("Pony", "test_almota_pony_2")
  1622. self.assertEqual(
  1623. operation.describe(), "Rename table for Pony to test_almota_pony_2"
  1624. )
  1625. self.assertEqual(operation.migration_name_fragment, "alter_pony_table")
  1626. new_state = project_state.clone()
  1627. operation.state_forwards("test_almota", new_state)
  1628. self.assertEqual(
  1629. new_state.models["test_almota", "pony"].options["db_table"],
  1630. "test_almota_pony_2",
  1631. )
  1632. # Test the database alteration
  1633. self.assertTableExists("test_almota_pony")
  1634. self.assertTableNotExists("test_almota_pony_2")
  1635. with connection.schema_editor() as editor:
  1636. operation.database_forwards("test_almota", editor, project_state, new_state)
  1637. self.assertTableNotExists("test_almota_pony")
  1638. self.assertTableExists("test_almota_pony_2")
  1639. # And test reversal
  1640. with connection.schema_editor() as editor:
  1641. operation.database_backwards(
  1642. "test_almota", editor, new_state, project_state
  1643. )
  1644. self.assertTableExists("test_almota_pony")
  1645. self.assertTableNotExists("test_almota_pony_2")
  1646. # And deconstruction
  1647. definition = operation.deconstruct()
  1648. self.assertEqual(definition[0], "AlterModelTable")
  1649. self.assertEqual(definition[1], [])
  1650. self.assertEqual(definition[2], {"name": "Pony", "table": "test_almota_pony_2"})
  1651. def test_alter_model_table_none(self):
  1652. """
  1653. Tests the AlterModelTable operation if the table name is set to None.
  1654. """
  1655. operation = migrations.AlterModelTable("Pony", None)
  1656. self.assertEqual(operation.describe(), "Rename table for Pony to (default)")
  1657. def test_alter_model_table_noop(self):
  1658. """
  1659. Tests the AlterModelTable operation if the table name is not changed.
  1660. """
  1661. project_state = self.set_up_test_model("test_almota")
  1662. # Test the state alteration
  1663. operation = migrations.AlterModelTable("Pony", "test_almota_pony")
  1664. new_state = project_state.clone()
  1665. operation.state_forwards("test_almota", new_state)
  1666. self.assertEqual(
  1667. new_state.models["test_almota", "pony"].options["db_table"],
  1668. "test_almota_pony",
  1669. )
  1670. # Test the database alteration
  1671. self.assertTableExists("test_almota_pony")
  1672. with connection.schema_editor() as editor:
  1673. operation.database_forwards("test_almota", editor, project_state, new_state)
  1674. self.assertTableExists("test_almota_pony")
  1675. # And test reversal
  1676. with connection.schema_editor() as editor:
  1677. operation.database_backwards(
  1678. "test_almota", editor, new_state, project_state
  1679. )
  1680. self.assertTableExists("test_almota_pony")
  1681. def test_alter_model_table_m2m(self):
  1682. """
  1683. AlterModelTable should rename auto-generated M2M tables.
  1684. """
  1685. app_label = "test_talflmltlm2m"
  1686. pony_db_table = "pony_foo"
  1687. project_state = self.set_up_test_model(
  1688. app_label, second_model=True, db_table=pony_db_table
  1689. )
  1690. # Add the M2M field
  1691. first_state = project_state.clone()
  1692. operation = migrations.AddField(
  1693. "Pony", "stables", models.ManyToManyField("Stable")
  1694. )
  1695. operation.state_forwards(app_label, first_state)
  1696. with connection.schema_editor() as editor:
  1697. operation.database_forwards(app_label, editor, project_state, first_state)
  1698. original_m2m_table = "%s_%s" % (pony_db_table, "stables")
  1699. new_m2m_table = "%s_%s" % (app_label, "pony_stables")
  1700. self.assertTableExists(original_m2m_table)
  1701. self.assertTableNotExists(new_m2m_table)
  1702. # Rename the Pony db_table which should also rename the m2m table.
  1703. second_state = first_state.clone()
  1704. operation = migrations.AlterModelTable(name="pony", table=None)
  1705. operation.state_forwards(app_label, second_state)
  1706. atomic_rename = connection.features.supports_atomic_references_rename
  1707. with connection.schema_editor(atomic=atomic_rename) as editor:
  1708. operation.database_forwards(app_label, editor, first_state, second_state)
  1709. self.assertTableExists(new_m2m_table)
  1710. self.assertTableNotExists(original_m2m_table)
  1711. # And test reversal
  1712. with connection.schema_editor(atomic=atomic_rename) as editor:
  1713. operation.database_backwards(app_label, editor, second_state, first_state)
  1714. self.assertTableExists(original_m2m_table)
  1715. self.assertTableNotExists(new_m2m_table)
  1716. def test_alter_field(self):
  1717. """
  1718. Tests the AlterField operation.
  1719. """
  1720. project_state = self.set_up_test_model("test_alfl")
  1721. # Test the state alteration
  1722. operation = migrations.AlterField(
  1723. "Pony", "pink", models.IntegerField(null=True)
  1724. )
  1725. self.assertEqual(operation.describe(), "Alter field pink on Pony")
  1726. self.assertEqual(operation.migration_name_fragment, "alter_pony_pink")
  1727. new_state = project_state.clone()
  1728. operation.state_forwards("test_alfl", new_state)
  1729. self.assertIs(
  1730. project_state.models["test_alfl", "pony"].fields["pink"].null, False
  1731. )
  1732. self.assertIs(new_state.models["test_alfl", "pony"].fields["pink"].null, True)
  1733. # Test the database alteration
  1734. self.assertColumnNotNull("test_alfl_pony", "pink")
  1735. with connection.schema_editor() as editor:
  1736. operation.database_forwards("test_alfl", editor, project_state, new_state)
  1737. self.assertColumnNull("test_alfl_pony", "pink")
  1738. # And test reversal
  1739. with connection.schema_editor() as editor:
  1740. operation.database_backwards("test_alfl", editor, new_state, project_state)
  1741. self.assertColumnNotNull("test_alfl_pony", "pink")
  1742. # And deconstruction
  1743. definition = operation.deconstruct()
  1744. self.assertEqual(definition[0], "AlterField")
  1745. self.assertEqual(definition[1], [])
  1746. self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"])
  1747. def test_alter_field_add_db_column_noop(self):
  1748. """
  1749. AlterField operation is a noop when adding only a db_column and the
  1750. column name is not changed.
  1751. """
  1752. app_label = "test_afadbn"
  1753. project_state = self.set_up_test_model(app_label, related_model=True)
  1754. pony_table = "%s_pony" % app_label
  1755. new_state = project_state.clone()
  1756. operation = migrations.AlterField(
  1757. "Pony", "weight", models.FloatField(db_column="weight")
  1758. )
  1759. operation.state_forwards(app_label, new_state)
  1760. self.assertIsNone(
  1761. project_state.models[app_label, "pony"].fields["weight"].db_column,
  1762. )
  1763. self.assertEqual(
  1764. new_state.models[app_label, "pony"].fields["weight"].db_column,
  1765. "weight",
  1766. )
  1767. self.assertColumnExists(pony_table, "weight")
  1768. with connection.schema_editor() as editor:
  1769. with self.assertNumQueries(0):
  1770. operation.database_forwards(app_label, editor, project_state, new_state)
  1771. self.assertColumnExists(pony_table, "weight")
  1772. with connection.schema_editor() as editor:
  1773. with self.assertNumQueries(0):
  1774. operation.database_backwards(
  1775. app_label, editor, new_state, project_state
  1776. )
  1777. self.assertColumnExists(pony_table, "weight")
  1778. rider_table = "%s_rider" % app_label
  1779. new_state = project_state.clone()
  1780. operation = migrations.AlterField(
  1781. "Rider",
  1782. "pony",
  1783. models.ForeignKey("Pony", models.CASCADE, db_column="pony_id"),
  1784. )
  1785. operation.state_forwards(app_label, new_state)
  1786. self.assertIsNone(
  1787. project_state.models[app_label, "rider"].fields["pony"].db_column,
  1788. )
  1789. self.assertIs(
  1790. new_state.models[app_label, "rider"].fields["pony"].db_column,
  1791. "pony_id",
  1792. )
  1793. self.assertColumnExists(rider_table, "pony_id")
  1794. with connection.schema_editor() as editor:
  1795. with self.assertNumQueries(0):
  1796. operation.database_forwards(app_label, editor, project_state, new_state)
  1797. self.assertColumnExists(rider_table, "pony_id")
  1798. with connection.schema_editor() as editor:
  1799. with self.assertNumQueries(0):
  1800. operation.database_forwards(app_label, editor, new_state, project_state)
  1801. self.assertColumnExists(rider_table, "pony_id")
  1802. def test_alter_field_pk(self):
  1803. """
  1804. The AlterField operation on primary keys (things like PostgreSQL's
  1805. SERIAL weirdness).
  1806. """
  1807. project_state = self.set_up_test_model("test_alflpk")
  1808. # Test the state alteration
  1809. operation = migrations.AlterField(
  1810. "Pony", "id", models.IntegerField(primary_key=True)
  1811. )
  1812. new_state = project_state.clone()
  1813. operation.state_forwards("test_alflpk", new_state)
  1814. self.assertIsInstance(
  1815. project_state.models["test_alflpk", "pony"].fields["id"],
  1816. models.AutoField,
  1817. )
  1818. self.assertIsInstance(
  1819. new_state.models["test_alflpk", "pony"].fields["id"],
  1820. models.IntegerField,
  1821. )
  1822. # Test the database alteration
  1823. with connection.schema_editor() as editor:
  1824. operation.database_forwards("test_alflpk", editor, project_state, new_state)
  1825. # And test reversal
  1826. with connection.schema_editor() as editor:
  1827. operation.database_backwards(
  1828. "test_alflpk", editor, new_state, project_state
  1829. )
  1830. @skipUnlessDBFeature("supports_foreign_keys")
  1831. def test_alter_field_pk_fk(self):
  1832. """
  1833. Tests the AlterField operation on primary keys changes any FKs pointing to it.
  1834. """
  1835. project_state = self.set_up_test_model("test_alflpkfk", related_model=True)
  1836. project_state = self.apply_operations(
  1837. "test_alflpkfk",
  1838. project_state,
  1839. [
  1840. migrations.CreateModel(
  1841. "Stable",
  1842. fields=[
  1843. ("ponies", models.ManyToManyField("Pony")),
  1844. ],
  1845. ),
  1846. migrations.AddField(
  1847. "Pony",
  1848. "stables",
  1849. models.ManyToManyField("Stable"),
  1850. ),
  1851. ],
  1852. )
  1853. # Test the state alteration
  1854. operation = migrations.AlterField(
  1855. "Pony", "id", models.FloatField(primary_key=True)
  1856. )
  1857. new_state = project_state.clone()
  1858. operation.state_forwards("test_alflpkfk", new_state)
  1859. self.assertIsInstance(
  1860. project_state.models["test_alflpkfk", "pony"].fields["id"],
  1861. models.AutoField,
  1862. )
  1863. self.assertIsInstance(
  1864. new_state.models["test_alflpkfk", "pony"].fields["id"],
  1865. models.FloatField,
  1866. )
  1867. def assertIdTypeEqualsFkType():
  1868. with connection.cursor() as cursor:
  1869. id_type, id_null = [
  1870. (c.type_code, c.null_ok)
  1871. for c in connection.introspection.get_table_description(
  1872. cursor, "test_alflpkfk_pony"
  1873. )
  1874. if c.name == "id"
  1875. ][0]
  1876. fk_type, fk_null = [
  1877. (c.type_code, c.null_ok)
  1878. for c in connection.introspection.get_table_description(
  1879. cursor, "test_alflpkfk_rider"
  1880. )
  1881. if c.name == "pony_id"
  1882. ][0]
  1883. m2m_fk_type, m2m_fk_null = [
  1884. (c.type_code, c.null_ok)
  1885. for c in connection.introspection.get_table_description(
  1886. cursor,
  1887. "test_alflpkfk_pony_stables",
  1888. )
  1889. if c.name == "pony_id"
  1890. ][0]
  1891. remote_m2m_fk_type, remote_m2m_fk_null = [
  1892. (c.type_code, c.null_ok)
  1893. for c in connection.introspection.get_table_description(
  1894. cursor,
  1895. "test_alflpkfk_stable_ponies",
  1896. )
  1897. if c.name == "pony_id"
  1898. ][0]
  1899. self.assertEqual(id_type, fk_type)
  1900. self.assertEqual(id_type, m2m_fk_type)
  1901. self.assertEqual(id_type, remote_m2m_fk_type)
  1902. self.assertEqual(id_null, fk_null)
  1903. self.assertEqual(id_null, m2m_fk_null)
  1904. self.assertEqual(id_null, remote_m2m_fk_null)
  1905. assertIdTypeEqualsFkType()
  1906. # Test the database alteration
  1907. with connection.schema_editor() as editor:
  1908. operation.database_forwards(
  1909. "test_alflpkfk", editor, project_state, new_state
  1910. )
  1911. assertIdTypeEqualsFkType()
  1912. if connection.features.supports_foreign_keys:
  1913. self.assertFKExists(
  1914. "test_alflpkfk_pony_stables",
  1915. ["pony_id"],
  1916. ("test_alflpkfk_pony", "id"),
  1917. )
  1918. self.assertFKExists(
  1919. "test_alflpkfk_stable_ponies",
  1920. ["pony_id"],
  1921. ("test_alflpkfk_pony", "id"),
  1922. )
  1923. # And test reversal
  1924. with connection.schema_editor() as editor:
  1925. operation.database_backwards(
  1926. "test_alflpkfk", editor, new_state, project_state
  1927. )
  1928. assertIdTypeEqualsFkType()
  1929. if connection.features.supports_foreign_keys:
  1930. self.assertFKExists(
  1931. "test_alflpkfk_pony_stables",
  1932. ["pony_id"],
  1933. ("test_alflpkfk_pony", "id"),
  1934. )
  1935. self.assertFKExists(
  1936. "test_alflpkfk_stable_ponies",
  1937. ["pony_id"],
  1938. ("test_alflpkfk_pony", "id"),
  1939. )
  1940. @skipUnlessDBFeature("supports_collation_on_charfield", "supports_foreign_keys")
  1941. def test_alter_field_pk_fk_db_collation(self):
  1942. """
  1943. AlterField operation of db_collation on primary keys changes any FKs
  1944. pointing to it.
  1945. """
  1946. collation = connection.features.test_collations.get("non_default")
  1947. if not collation:
  1948. self.skipTest("Language collations are not supported.")
  1949. app_label = "test_alflpkfkdbc"
  1950. project_state = self.apply_operations(
  1951. app_label,
  1952. ProjectState(),
  1953. [
  1954. migrations.CreateModel(
  1955. "Pony",
  1956. [
  1957. ("id", models.CharField(primary_key=True, max_length=10)),
  1958. ],
  1959. ),
  1960. migrations.CreateModel(
  1961. "Rider",
  1962. [
  1963. ("pony", models.ForeignKey("Pony", models.CASCADE)),
  1964. ],
  1965. ),
  1966. migrations.CreateModel(
  1967. "Stable",
  1968. [
  1969. ("ponies", models.ManyToManyField("Pony")),
  1970. ],
  1971. ),
  1972. ],
  1973. )
  1974. # State alteration.
  1975. operation = migrations.AlterField(
  1976. "Pony",
  1977. "id",
  1978. models.CharField(
  1979. primary_key=True,
  1980. max_length=10,
  1981. db_collation=collation,
  1982. ),
  1983. )
  1984. new_state = project_state.clone()
  1985. operation.state_forwards(app_label, new_state)
  1986. # Database alteration.
  1987. with connection.schema_editor() as editor:
  1988. operation.database_forwards(app_label, editor, project_state, new_state)
  1989. self.assertColumnCollation(f"{app_label}_pony", "id", collation)
  1990. self.assertColumnCollation(f"{app_label}_rider", "pony_id", collation)
  1991. self.assertColumnCollation(f"{app_label}_stable_ponies", "pony_id", collation)
  1992. # Reversal.
  1993. with connection.schema_editor() as editor:
  1994. operation.database_backwards(app_label, editor, new_state, project_state)
  1995. def test_alter_field_pk_mti_fk(self):
  1996. app_label = "test_alflpkmtifk"
  1997. project_state = self.set_up_test_model(app_label, mti_model=True)
  1998. project_state = self.apply_operations(
  1999. app_label,
  2000. project_state,
  2001. [
  2002. migrations.CreateModel(
  2003. "ShetlandRider",
  2004. fields=[
  2005. (
  2006. "pony",
  2007. models.ForeignKey(
  2008. f"{app_label}.ShetlandPony", models.CASCADE
  2009. ),
  2010. ),
  2011. ],
  2012. ),
  2013. ],
  2014. )
  2015. operation = migrations.AlterField(
  2016. "Pony",
  2017. "id",
  2018. models.BigAutoField(primary_key=True),
  2019. )
  2020. new_state = project_state.clone()
  2021. operation.state_forwards(app_label, new_state)
  2022. self.assertIsInstance(
  2023. new_state.models[app_label, "pony"].fields["id"],
  2024. models.BigAutoField,
  2025. )
  2026. def _get_column_id_type(cursor, table, column):
  2027. return [
  2028. c.type_code
  2029. for c in connection.introspection.get_table_description(
  2030. cursor,
  2031. f"{app_label}_{table}",
  2032. )
  2033. if c.name == column
  2034. ][0]
  2035. def assertIdTypeEqualsMTIFkType():
  2036. with connection.cursor() as cursor:
  2037. parent_id_type = _get_column_id_type(cursor, "pony", "id")
  2038. child_id_type = _get_column_id_type(
  2039. cursor, "shetlandpony", "pony_ptr_id"
  2040. )
  2041. mti_id_type = _get_column_id_type(cursor, "shetlandrider", "pony_id")
  2042. self.assertEqual(parent_id_type, child_id_type)
  2043. self.assertEqual(parent_id_type, mti_id_type)
  2044. assertIdTypeEqualsMTIFkType()
  2045. # Alter primary key.
  2046. with connection.schema_editor() as editor:
  2047. operation.database_forwards(app_label, editor, project_state, new_state)
  2048. assertIdTypeEqualsMTIFkType()
  2049. if connection.features.supports_foreign_keys:
  2050. self.assertFKExists(
  2051. f"{app_label}_shetlandpony",
  2052. ["pony_ptr_id"],
  2053. (f"{app_label}_pony", "id"),
  2054. )
  2055. self.assertFKExists(
  2056. f"{app_label}_shetlandrider",
  2057. ["pony_id"],
  2058. (f"{app_label}_shetlandpony", "pony_ptr_id"),
  2059. )
  2060. # Reversal.
  2061. with connection.schema_editor() as editor:
  2062. operation.database_backwards(app_label, editor, new_state, project_state)
  2063. assertIdTypeEqualsMTIFkType()
  2064. if connection.features.supports_foreign_keys:
  2065. self.assertFKExists(
  2066. f"{app_label}_shetlandpony",
  2067. ["pony_ptr_id"],
  2068. (f"{app_label}_pony", "id"),
  2069. )
  2070. self.assertFKExists(
  2071. f"{app_label}_shetlandrider",
  2072. ["pony_id"],
  2073. (f"{app_label}_shetlandpony", "pony_ptr_id"),
  2074. )
  2075. def test_alter_field_pk_mti_and_fk_to_base(self):
  2076. app_label = "test_alflpkmtiftb"
  2077. project_state = self.set_up_test_model(
  2078. app_label,
  2079. mti_model=True,
  2080. related_model=True,
  2081. )
  2082. operation = migrations.AlterField(
  2083. "Pony",
  2084. "id",
  2085. models.BigAutoField(primary_key=True),
  2086. )
  2087. new_state = project_state.clone()
  2088. operation.state_forwards(app_label, new_state)
  2089. self.assertIsInstance(
  2090. new_state.models[app_label, "pony"].fields["id"],
  2091. models.BigAutoField,
  2092. )
  2093. def _get_column_id_type(cursor, table, column):
  2094. return [
  2095. c.type_code
  2096. for c in connection.introspection.get_table_description(
  2097. cursor,
  2098. f"{app_label}_{table}",
  2099. )
  2100. if c.name == column
  2101. ][0]
  2102. def assertIdTypeEqualsMTIFkType():
  2103. with connection.cursor() as cursor:
  2104. parent_id_type = _get_column_id_type(cursor, "pony", "id")
  2105. fk_id_type = _get_column_id_type(cursor, "rider", "pony_id")
  2106. child_id_type = _get_column_id_type(
  2107. cursor, "shetlandpony", "pony_ptr_id"
  2108. )
  2109. self.assertEqual(parent_id_type, child_id_type)
  2110. self.assertEqual(parent_id_type, fk_id_type)
  2111. assertIdTypeEqualsMTIFkType()
  2112. # Alter primary key.
  2113. with connection.schema_editor() as editor:
  2114. operation.database_forwards(app_label, editor, project_state, new_state)
  2115. assertIdTypeEqualsMTIFkType()
  2116. if connection.features.supports_foreign_keys:
  2117. self.assertFKExists(
  2118. f"{app_label}_shetlandpony",
  2119. ["pony_ptr_id"],
  2120. (f"{app_label}_pony", "id"),
  2121. )
  2122. self.assertFKExists(
  2123. f"{app_label}_rider",
  2124. ["pony_id"],
  2125. (f"{app_label}_pony", "id"),
  2126. )
  2127. # Reversal.
  2128. with connection.schema_editor() as editor:
  2129. operation.database_backwards(app_label, editor, new_state, project_state)
  2130. assertIdTypeEqualsMTIFkType()
  2131. if connection.features.supports_foreign_keys:
  2132. self.assertFKExists(
  2133. f"{app_label}_shetlandpony",
  2134. ["pony_ptr_id"],
  2135. (f"{app_label}_pony", "id"),
  2136. )
  2137. self.assertFKExists(
  2138. f"{app_label}_rider",
  2139. ["pony_id"],
  2140. (f"{app_label}_pony", "id"),
  2141. )
  2142. @skipUnlessDBFeature("supports_foreign_keys")
  2143. def test_alter_field_reloads_state_on_fk_with_to_field_target_type_change(self):
  2144. app_label = "test_alflrsfkwtflttc"
  2145. project_state = self.apply_operations(
  2146. app_label,
  2147. ProjectState(),
  2148. operations=[
  2149. migrations.CreateModel(
  2150. "Rider",
  2151. fields=[
  2152. ("id", models.AutoField(primary_key=True)),
  2153. ("code", models.IntegerField(unique=True)),
  2154. ],
  2155. ),
  2156. migrations.CreateModel(
  2157. "Pony",
  2158. fields=[
  2159. ("id", models.AutoField(primary_key=True)),
  2160. (
  2161. "rider",
  2162. models.ForeignKey(
  2163. "%s.Rider" % app_label, models.CASCADE, to_field="code"
  2164. ),
  2165. ),
  2166. ],
  2167. ),
  2168. ],
  2169. )
  2170. operation = migrations.AlterField(
  2171. "Rider",
  2172. "code",
  2173. models.CharField(max_length=100, unique=True),
  2174. )
  2175. self.apply_operations(app_label, project_state, operations=[operation])
  2176. id_type, id_null = [
  2177. (c.type_code, c.null_ok)
  2178. for c in self.get_table_description("%s_rider" % app_label)
  2179. if c.name == "code"
  2180. ][0]
  2181. fk_type, fk_null = [
  2182. (c.type_code, c.null_ok)
  2183. for c in self.get_table_description("%s_pony" % app_label)
  2184. if c.name == "rider_id"
  2185. ][0]
  2186. self.assertEqual(id_type, fk_type)
  2187. self.assertEqual(id_null, fk_null)
  2188. @skipUnlessDBFeature("supports_foreign_keys")
  2189. def test_alter_field_reloads_state_fk_with_to_field_related_name_target_type_change(
  2190. self,
  2191. ):
  2192. app_label = "test_alflrsfkwtflrnttc"
  2193. project_state = self.apply_operations(
  2194. app_label,
  2195. ProjectState(),
  2196. operations=[
  2197. migrations.CreateModel(
  2198. "Rider",
  2199. fields=[
  2200. ("id", models.AutoField(primary_key=True)),
  2201. ("code", models.PositiveIntegerField(unique=True)),
  2202. ],
  2203. ),
  2204. migrations.CreateModel(
  2205. "Pony",
  2206. fields=[
  2207. ("id", models.AutoField(primary_key=True)),
  2208. (
  2209. "rider",
  2210. models.ForeignKey(
  2211. "%s.Rider" % app_label,
  2212. models.CASCADE,
  2213. to_field="code",
  2214. related_name="+",
  2215. ),
  2216. ),
  2217. ],
  2218. ),
  2219. ],
  2220. )
  2221. operation = migrations.AlterField(
  2222. "Rider",
  2223. "code",
  2224. models.CharField(max_length=100, unique=True),
  2225. )
  2226. self.apply_operations(app_label, project_state, operations=[operation])
  2227. def test_alter_field_reloads_state_on_fk_target_changes(self):
  2228. """
  2229. If AlterField doesn't reload state appropriately, the second AlterField
  2230. crashes on MySQL due to not dropping the PonyRider.pony foreign key
  2231. constraint before modifying the column.
  2232. """
  2233. app_label = "alter_alter_field_reloads_state_on_fk_target_changes"
  2234. project_state = self.apply_operations(
  2235. app_label,
  2236. ProjectState(),
  2237. operations=[
  2238. migrations.CreateModel(
  2239. "Rider",
  2240. fields=[
  2241. ("id", models.CharField(primary_key=True, max_length=100)),
  2242. ],
  2243. ),
  2244. migrations.CreateModel(
  2245. "Pony",
  2246. fields=[
  2247. ("id", models.CharField(primary_key=True, max_length=100)),
  2248. (
  2249. "rider",
  2250. models.ForeignKey("%s.Rider" % app_label, models.CASCADE),
  2251. ),
  2252. ],
  2253. ),
  2254. migrations.CreateModel(
  2255. "PonyRider",
  2256. fields=[
  2257. ("id", models.AutoField(primary_key=True)),
  2258. (
  2259. "pony",
  2260. models.ForeignKey("%s.Pony" % app_label, models.CASCADE),
  2261. ),
  2262. ],
  2263. ),
  2264. ],
  2265. )
  2266. project_state = self.apply_operations(
  2267. app_label,
  2268. project_state,
  2269. operations=[
  2270. migrations.AlterField(
  2271. "Rider", "id", models.CharField(primary_key=True, max_length=99)
  2272. ),
  2273. migrations.AlterField(
  2274. "Pony", "id", models.CharField(primary_key=True, max_length=99)
  2275. ),
  2276. ],
  2277. )
  2278. def test_alter_field_reloads_state_on_fk_with_to_field_target_changes(self):
  2279. """
  2280. If AlterField doesn't reload state appropriately, the second AlterField
  2281. crashes on MySQL due to not dropping the PonyRider.pony foreign key
  2282. constraint before modifying the column.
  2283. """
  2284. app_label = "alter_alter_field_reloads_state_on_fk_with_to_field_target_changes"
  2285. project_state = self.apply_operations(
  2286. app_label,
  2287. ProjectState(),
  2288. operations=[
  2289. migrations.CreateModel(
  2290. "Rider",
  2291. fields=[
  2292. ("id", models.CharField(primary_key=True, max_length=100)),
  2293. ("slug", models.CharField(unique=True, max_length=100)),
  2294. ],
  2295. ),
  2296. migrations.CreateModel(
  2297. "Pony",
  2298. fields=[
  2299. ("id", models.CharField(primary_key=True, max_length=100)),
  2300. (
  2301. "rider",
  2302. models.ForeignKey(
  2303. "%s.Rider" % app_label, models.CASCADE, to_field="slug"
  2304. ),
  2305. ),
  2306. ("slug", models.CharField(unique=True, max_length=100)),
  2307. ],
  2308. ),
  2309. migrations.CreateModel(
  2310. "PonyRider",
  2311. fields=[
  2312. ("id", models.AutoField(primary_key=True)),
  2313. (
  2314. "pony",
  2315. models.ForeignKey(
  2316. "%s.Pony" % app_label, models.CASCADE, to_field="slug"
  2317. ),
  2318. ),
  2319. ],
  2320. ),
  2321. ],
  2322. )
  2323. project_state = self.apply_operations(
  2324. app_label,
  2325. project_state,
  2326. operations=[
  2327. migrations.AlterField(
  2328. "Rider", "slug", models.CharField(unique=True, max_length=99)
  2329. ),
  2330. migrations.AlterField(
  2331. "Pony", "slug", models.CharField(unique=True, max_length=99)
  2332. ),
  2333. ],
  2334. )
  2335. def test_rename_field_reloads_state_on_fk_target_changes(self):
  2336. """
  2337. If RenameField doesn't reload state appropriately, the AlterField
  2338. crashes on MySQL due to not dropping the PonyRider.pony foreign key
  2339. constraint before modifying the column.
  2340. """
  2341. app_label = "alter_rename_field_reloads_state_on_fk_target_changes"
  2342. project_state = self.apply_operations(
  2343. app_label,
  2344. ProjectState(),
  2345. operations=[
  2346. migrations.CreateModel(
  2347. "Rider",
  2348. fields=[
  2349. ("id", models.CharField(primary_key=True, max_length=100)),
  2350. ],
  2351. ),
  2352. migrations.CreateModel(
  2353. "Pony",
  2354. fields=[
  2355. ("id", models.CharField(primary_key=True, max_length=100)),
  2356. (
  2357. "rider",
  2358. models.ForeignKey("%s.Rider" % app_label, models.CASCADE),
  2359. ),
  2360. ],
  2361. ),
  2362. migrations.CreateModel(
  2363. "PonyRider",
  2364. fields=[
  2365. ("id", models.AutoField(primary_key=True)),
  2366. (
  2367. "pony",
  2368. models.ForeignKey("%s.Pony" % app_label, models.CASCADE),
  2369. ),
  2370. ],
  2371. ),
  2372. ],
  2373. )
  2374. project_state = self.apply_operations(
  2375. app_label,
  2376. project_state,
  2377. operations=[
  2378. migrations.RenameField("Rider", "id", "id2"),
  2379. migrations.AlterField(
  2380. "Pony", "id", models.CharField(primary_key=True, max_length=99)
  2381. ),
  2382. ],
  2383. atomic=connection.features.supports_atomic_references_rename,
  2384. )
  2385. def test_rename_field(self):
  2386. """
  2387. Tests the RenameField operation.
  2388. """
  2389. project_state = self.set_up_test_model("test_rnfl")
  2390. operation = migrations.RenameField("Pony", "pink", "blue")
  2391. self.assertEqual(operation.describe(), "Rename field pink on Pony to blue")
  2392. self.assertEqual(operation.migration_name_fragment, "rename_pink_pony_blue")
  2393. new_state = project_state.clone()
  2394. operation.state_forwards("test_rnfl", new_state)
  2395. self.assertIn("blue", new_state.models["test_rnfl", "pony"].fields)
  2396. self.assertNotIn("pink", new_state.models["test_rnfl", "pony"].fields)
  2397. # Rename field.
  2398. self.assertColumnExists("test_rnfl_pony", "pink")
  2399. self.assertColumnNotExists("test_rnfl_pony", "blue")
  2400. with connection.schema_editor() as editor:
  2401. operation.database_forwards("test_rnfl", editor, project_state, new_state)
  2402. self.assertColumnExists("test_rnfl_pony", "blue")
  2403. self.assertColumnNotExists("test_rnfl_pony", "pink")
  2404. # Reversal.
  2405. with connection.schema_editor() as editor:
  2406. operation.database_backwards("test_rnfl", editor, new_state, project_state)
  2407. self.assertColumnExists("test_rnfl_pony", "pink")
  2408. self.assertColumnNotExists("test_rnfl_pony", "blue")
  2409. # Deconstruction.
  2410. definition = operation.deconstruct()
  2411. self.assertEqual(definition[0], "RenameField")
  2412. self.assertEqual(definition[1], [])
  2413. self.assertEqual(
  2414. definition[2],
  2415. {"model_name": "Pony", "old_name": "pink", "new_name": "blue"},
  2416. )
  2417. def test_rename_field_unique_together(self):
  2418. project_state = self.set_up_test_model("test_rnflut", unique_together=True)
  2419. operation = migrations.RenameField("Pony", "pink", "blue")
  2420. new_state = project_state.clone()
  2421. operation.state_forwards("test_rnflut", new_state)
  2422. # unique_together has the renamed column.
  2423. self.assertIn(
  2424. "blue",
  2425. new_state.models["test_rnflut", "pony"].options["unique_together"][0],
  2426. )
  2427. self.assertNotIn(
  2428. "pink",
  2429. new_state.models["test_rnflut", "pony"].options["unique_together"][0],
  2430. )
  2431. # Rename field.
  2432. self.assertColumnExists("test_rnflut_pony", "pink")
  2433. self.assertColumnNotExists("test_rnflut_pony", "blue")
  2434. with connection.schema_editor() as editor:
  2435. operation.database_forwards("test_rnflut", editor, project_state, new_state)
  2436. self.assertColumnExists("test_rnflut_pony", "blue")
  2437. self.assertColumnNotExists("test_rnflut_pony", "pink")
  2438. # The unique constraint has been ported over.
  2439. with connection.cursor() as cursor:
  2440. cursor.execute("INSERT INTO test_rnflut_pony (blue, weight) VALUES (1, 1)")
  2441. with self.assertRaises(IntegrityError):
  2442. with atomic():
  2443. cursor.execute(
  2444. "INSERT INTO test_rnflut_pony (blue, weight) VALUES (1, 1)"
  2445. )
  2446. cursor.execute("DELETE FROM test_rnflut_pony")
  2447. # Reversal.
  2448. with connection.schema_editor() as editor:
  2449. operation.database_backwards(
  2450. "test_rnflut", editor, new_state, project_state
  2451. )
  2452. self.assertColumnExists("test_rnflut_pony", "pink")
  2453. self.assertColumnNotExists("test_rnflut_pony", "blue")
  2454. @ignore_warnings(category=RemovedInDjango51Warning)
  2455. def test_rename_field_index_together(self):
  2456. project_state = self.set_up_test_model("test_rnflit", index_together=True)
  2457. operation = migrations.RenameField("Pony", "pink", "blue")
  2458. new_state = project_state.clone()
  2459. operation.state_forwards("test_rnflit", new_state)
  2460. self.assertIn("blue", new_state.models["test_rnflit", "pony"].fields)
  2461. self.assertNotIn("pink", new_state.models["test_rnflit", "pony"].fields)
  2462. # index_together has the renamed column.
  2463. self.assertIn(
  2464. "blue", new_state.models["test_rnflit", "pony"].options["index_together"][0]
  2465. )
  2466. self.assertNotIn(
  2467. "pink", new_state.models["test_rnflit", "pony"].options["index_together"][0]
  2468. )
  2469. # Rename field.
  2470. self.assertColumnExists("test_rnflit_pony", "pink")
  2471. self.assertColumnNotExists("test_rnflit_pony", "blue")
  2472. with connection.schema_editor() as editor:
  2473. operation.database_forwards("test_rnflit", editor, project_state, new_state)
  2474. self.assertColumnExists("test_rnflit_pony", "blue")
  2475. self.assertColumnNotExists("test_rnflit_pony", "pink")
  2476. # The index constraint has been ported over.
  2477. self.assertIndexExists("test_rnflit_pony", ["weight", "blue"])
  2478. # Reversal.
  2479. with connection.schema_editor() as editor:
  2480. operation.database_backwards(
  2481. "test_rnflit", editor, new_state, project_state
  2482. )
  2483. self.assertIndexExists("test_rnflit_pony", ["weight", "pink"])
  2484. def test_rename_field_with_db_column(self):
  2485. project_state = self.apply_operations(
  2486. "test_rfwdbc",
  2487. ProjectState(),
  2488. operations=[
  2489. migrations.CreateModel(
  2490. "Pony",
  2491. fields=[
  2492. ("id", models.AutoField(primary_key=True)),
  2493. ("field", models.IntegerField(db_column="db_field")),
  2494. (
  2495. "fk_field",
  2496. models.ForeignKey(
  2497. "Pony",
  2498. models.CASCADE,
  2499. db_column="db_fk_field",
  2500. ),
  2501. ),
  2502. ],
  2503. ),
  2504. ],
  2505. )
  2506. new_state = project_state.clone()
  2507. operation = migrations.RenameField("Pony", "field", "renamed_field")
  2508. operation.state_forwards("test_rfwdbc", new_state)
  2509. self.assertIn("renamed_field", new_state.models["test_rfwdbc", "pony"].fields)
  2510. self.assertNotIn("field", new_state.models["test_rfwdbc", "pony"].fields)
  2511. self.assertColumnExists("test_rfwdbc_pony", "db_field")
  2512. with connection.schema_editor() as editor:
  2513. with self.assertNumQueries(0):
  2514. operation.database_forwards(
  2515. "test_rfwdbc", editor, project_state, new_state
  2516. )
  2517. self.assertColumnExists("test_rfwdbc_pony", "db_field")
  2518. with connection.schema_editor() as editor:
  2519. with self.assertNumQueries(0):
  2520. operation.database_backwards(
  2521. "test_rfwdbc", editor, new_state, project_state
  2522. )
  2523. self.assertColumnExists("test_rfwdbc_pony", "db_field")
  2524. new_state = project_state.clone()
  2525. operation = migrations.RenameField("Pony", "fk_field", "renamed_fk_field")
  2526. operation.state_forwards("test_rfwdbc", new_state)
  2527. self.assertIn(
  2528. "renamed_fk_field", new_state.models["test_rfwdbc", "pony"].fields
  2529. )
  2530. self.assertNotIn("fk_field", new_state.models["test_rfwdbc", "pony"].fields)
  2531. self.assertColumnExists("test_rfwdbc_pony", "db_fk_field")
  2532. with connection.schema_editor() as editor:
  2533. with self.assertNumQueries(0):
  2534. operation.database_forwards(
  2535. "test_rfwdbc", editor, project_state, new_state
  2536. )
  2537. self.assertColumnExists("test_rfwdbc_pony", "db_fk_field")
  2538. with connection.schema_editor() as editor:
  2539. with self.assertNumQueries(0):
  2540. operation.database_backwards(
  2541. "test_rfwdbc", editor, new_state, project_state
  2542. )
  2543. self.assertColumnExists("test_rfwdbc_pony", "db_fk_field")
  2544. def test_rename_field_case(self):
  2545. project_state = self.apply_operations(
  2546. "test_rfmx",
  2547. ProjectState(),
  2548. operations=[
  2549. migrations.CreateModel(
  2550. "Pony",
  2551. fields=[
  2552. ("id", models.AutoField(primary_key=True)),
  2553. ("field", models.IntegerField()),
  2554. ],
  2555. ),
  2556. ],
  2557. )
  2558. new_state = project_state.clone()
  2559. operation = migrations.RenameField("Pony", "field", "FiElD")
  2560. operation.state_forwards("test_rfmx", new_state)
  2561. self.assertIn("FiElD", new_state.models["test_rfmx", "pony"].fields)
  2562. self.assertColumnExists("test_rfmx_pony", "field")
  2563. with connection.schema_editor() as editor:
  2564. operation.database_forwards("test_rfmx", editor, project_state, new_state)
  2565. self.assertColumnExists(
  2566. "test_rfmx_pony",
  2567. connection.introspection.identifier_converter("FiElD"),
  2568. )
  2569. with connection.schema_editor() as editor:
  2570. operation.database_backwards("test_rfmx", editor, new_state, project_state)
  2571. self.assertColumnExists("test_rfmx_pony", "field")
  2572. def test_rename_missing_field(self):
  2573. state = ProjectState()
  2574. state.add_model(ModelState("app", "model", []))
  2575. with self.assertRaisesMessage(
  2576. FieldDoesNotExist, "app.model has no field named 'field'"
  2577. ):
  2578. migrations.RenameField("model", "field", "new_field").state_forwards(
  2579. "app", state
  2580. )
  2581. def test_rename_referenced_field_state_forward(self):
  2582. state = ProjectState()
  2583. state.add_model(
  2584. ModelState(
  2585. "app",
  2586. "Model",
  2587. [
  2588. ("id", models.AutoField(primary_key=True)),
  2589. ("field", models.IntegerField(unique=True)),
  2590. ],
  2591. )
  2592. )
  2593. state.add_model(
  2594. ModelState(
  2595. "app",
  2596. "OtherModel",
  2597. [
  2598. ("id", models.AutoField(primary_key=True)),
  2599. (
  2600. "fk",
  2601. models.ForeignKey("Model", models.CASCADE, to_field="field"),
  2602. ),
  2603. (
  2604. "fo",
  2605. models.ForeignObject(
  2606. "Model",
  2607. models.CASCADE,
  2608. from_fields=("fk",),
  2609. to_fields=("field",),
  2610. ),
  2611. ),
  2612. ],
  2613. )
  2614. )
  2615. operation = migrations.RenameField("Model", "field", "renamed")
  2616. new_state = state.clone()
  2617. operation.state_forwards("app", new_state)
  2618. self.assertEqual(
  2619. new_state.models["app", "othermodel"].fields["fk"].remote_field.field_name,
  2620. "renamed",
  2621. )
  2622. self.assertEqual(
  2623. new_state.models["app", "othermodel"].fields["fk"].from_fields, ["self"]
  2624. )
  2625. self.assertEqual(
  2626. new_state.models["app", "othermodel"].fields["fk"].to_fields, ("renamed",)
  2627. )
  2628. self.assertEqual(
  2629. new_state.models["app", "othermodel"].fields["fo"].from_fields, ("fk",)
  2630. )
  2631. self.assertEqual(
  2632. new_state.models["app", "othermodel"].fields["fo"].to_fields, ("renamed",)
  2633. )
  2634. operation = migrations.RenameField("OtherModel", "fk", "renamed_fk")
  2635. new_state = state.clone()
  2636. operation.state_forwards("app", new_state)
  2637. self.assertEqual(
  2638. new_state.models["app", "othermodel"]
  2639. .fields["renamed_fk"]
  2640. .remote_field.field_name,
  2641. "renamed",
  2642. )
  2643. self.assertEqual(
  2644. new_state.models["app", "othermodel"].fields["renamed_fk"].from_fields,
  2645. ("self",),
  2646. )
  2647. self.assertEqual(
  2648. new_state.models["app", "othermodel"].fields["renamed_fk"].to_fields,
  2649. ("renamed",),
  2650. )
  2651. self.assertEqual(
  2652. new_state.models["app", "othermodel"].fields["fo"].from_fields,
  2653. ("renamed_fk",),
  2654. )
  2655. self.assertEqual(
  2656. new_state.models["app", "othermodel"].fields["fo"].to_fields, ("renamed",)
  2657. )
  2658. def test_alter_unique_together(self):
  2659. """
  2660. Tests the AlterUniqueTogether operation.
  2661. """
  2662. project_state = self.set_up_test_model("test_alunto")
  2663. # Test the state alteration
  2664. operation = migrations.AlterUniqueTogether("Pony", [("pink", "weight")])
  2665. self.assertEqual(
  2666. operation.describe(), "Alter unique_together for Pony (1 constraint(s))"
  2667. )
  2668. self.assertEqual(
  2669. operation.migration_name_fragment,
  2670. "alter_pony_unique_together",
  2671. )
  2672. new_state = project_state.clone()
  2673. operation.state_forwards("test_alunto", new_state)
  2674. self.assertEqual(
  2675. len(
  2676. project_state.models["test_alunto", "pony"].options.get(
  2677. "unique_together", set()
  2678. )
  2679. ),
  2680. 0,
  2681. )
  2682. self.assertEqual(
  2683. len(
  2684. new_state.models["test_alunto", "pony"].options.get(
  2685. "unique_together", set()
  2686. )
  2687. ),
  2688. 1,
  2689. )
  2690. # Make sure we can insert duplicate rows
  2691. with connection.cursor() as cursor:
  2692. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  2693. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  2694. cursor.execute("DELETE FROM test_alunto_pony")
  2695. # Test the database alteration
  2696. with connection.schema_editor() as editor:
  2697. operation.database_forwards(
  2698. "test_alunto", editor, project_state, new_state
  2699. )
  2700. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  2701. with self.assertRaises(IntegrityError):
  2702. with atomic():
  2703. cursor.execute(
  2704. "INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)"
  2705. )
  2706. cursor.execute("DELETE FROM test_alunto_pony")
  2707. # And test reversal
  2708. with connection.schema_editor() as editor:
  2709. operation.database_backwards(
  2710. "test_alunto", editor, new_state, project_state
  2711. )
  2712. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  2713. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  2714. cursor.execute("DELETE FROM test_alunto_pony")
  2715. # Test flat unique_together
  2716. operation = migrations.AlterUniqueTogether("Pony", ("pink", "weight"))
  2717. operation.state_forwards("test_alunto", new_state)
  2718. self.assertEqual(
  2719. len(
  2720. new_state.models["test_alunto", "pony"].options.get(
  2721. "unique_together", set()
  2722. )
  2723. ),
  2724. 1,
  2725. )
  2726. # And deconstruction
  2727. definition = operation.deconstruct()
  2728. self.assertEqual(definition[0], "AlterUniqueTogether")
  2729. self.assertEqual(definition[1], [])
  2730. self.assertEqual(
  2731. definition[2], {"name": "Pony", "unique_together": {("pink", "weight")}}
  2732. )
  2733. def test_alter_unique_together_remove(self):
  2734. operation = migrations.AlterUniqueTogether("Pony", None)
  2735. self.assertEqual(
  2736. operation.describe(), "Alter unique_together for Pony (0 constraint(s))"
  2737. )
  2738. @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields")
  2739. def test_remove_unique_together_on_pk_field(self):
  2740. app_label = "test_rutopkf"
  2741. project_state = self.apply_operations(
  2742. app_label,
  2743. ProjectState(),
  2744. operations=[
  2745. migrations.CreateModel(
  2746. "Pony",
  2747. fields=[("id", models.AutoField(primary_key=True))],
  2748. options={"unique_together": {("id",)}},
  2749. ),
  2750. ],
  2751. )
  2752. table_name = f"{app_label}_pony"
  2753. pk_constraint_name = f"{table_name}_pkey"
  2754. unique_together_constraint_name = f"{table_name}_id_fb61f881_uniq"
  2755. self.assertConstraintExists(table_name, pk_constraint_name, value=False)
  2756. self.assertConstraintExists(
  2757. table_name, unique_together_constraint_name, value=False
  2758. )
  2759. new_state = project_state.clone()
  2760. operation = migrations.AlterUniqueTogether("Pony", set())
  2761. operation.state_forwards(app_label, new_state)
  2762. with connection.schema_editor() as editor:
  2763. operation.database_forwards(app_label, editor, project_state, new_state)
  2764. self.assertConstraintExists(table_name, pk_constraint_name, value=False)
  2765. self.assertConstraintNotExists(table_name, unique_together_constraint_name)
  2766. @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields")
  2767. def test_remove_unique_together_on_unique_field(self):
  2768. app_label = "test_rutouf"
  2769. project_state = self.apply_operations(
  2770. app_label,
  2771. ProjectState(),
  2772. operations=[
  2773. migrations.CreateModel(
  2774. "Pony",
  2775. fields=[
  2776. ("id", models.AutoField(primary_key=True)),
  2777. ("name", models.CharField(max_length=30, unique=True)),
  2778. ],
  2779. options={"unique_together": {("name",)}},
  2780. ),
  2781. ],
  2782. )
  2783. table_name = f"{app_label}_pony"
  2784. unique_constraint_name = f"{table_name}_name_key"
  2785. unique_together_constraint_name = f"{table_name}_name_694f3b9f_uniq"
  2786. self.assertConstraintExists(table_name, unique_constraint_name, value=False)
  2787. self.assertConstraintExists(
  2788. table_name, unique_together_constraint_name, value=False
  2789. )
  2790. new_state = project_state.clone()
  2791. operation = migrations.AlterUniqueTogether("Pony", set())
  2792. operation.state_forwards(app_label, new_state)
  2793. with connection.schema_editor() as editor:
  2794. operation.database_forwards(app_label, editor, project_state, new_state)
  2795. self.assertConstraintExists(table_name, unique_constraint_name, value=False)
  2796. self.assertConstraintNotExists(table_name, unique_together_constraint_name)
  2797. def test_add_index(self):
  2798. """
  2799. Test the AddIndex operation.
  2800. """
  2801. project_state = self.set_up_test_model("test_adin")
  2802. msg = (
  2803. "Indexes passed to AddIndex operations require a name argument. "
  2804. "<Index: fields=['pink']> doesn't have one."
  2805. )
  2806. with self.assertRaisesMessage(ValueError, msg):
  2807. migrations.AddIndex("Pony", models.Index(fields=["pink"]))
  2808. index = models.Index(fields=["pink"], name="test_adin_pony_pink_idx")
  2809. operation = migrations.AddIndex("Pony", index)
  2810. self.assertEqual(
  2811. operation.describe(),
  2812. "Create index test_adin_pony_pink_idx on field(s) pink of model Pony",
  2813. )
  2814. self.assertEqual(
  2815. operation.migration_name_fragment,
  2816. "pony_test_adin_pony_pink_idx",
  2817. )
  2818. new_state = project_state.clone()
  2819. operation.state_forwards("test_adin", new_state)
  2820. # Test the database alteration
  2821. self.assertEqual(
  2822. len(new_state.models["test_adin", "pony"].options["indexes"]), 1
  2823. )
  2824. self.assertIndexNotExists("test_adin_pony", ["pink"])
  2825. with connection.schema_editor() as editor:
  2826. operation.database_forwards("test_adin", editor, project_state, new_state)
  2827. self.assertIndexExists("test_adin_pony", ["pink"])
  2828. # And test reversal
  2829. with connection.schema_editor() as editor:
  2830. operation.database_backwards("test_adin", editor, new_state, project_state)
  2831. self.assertIndexNotExists("test_adin_pony", ["pink"])
  2832. # And deconstruction
  2833. definition = operation.deconstruct()
  2834. self.assertEqual(definition[0], "AddIndex")
  2835. self.assertEqual(definition[1], [])
  2836. self.assertEqual(definition[2], {"model_name": "Pony", "index": index})
  2837. def test_remove_index(self):
  2838. """
  2839. Test the RemoveIndex operation.
  2840. """
  2841. project_state = self.set_up_test_model("test_rmin", multicol_index=True)
  2842. self.assertTableExists("test_rmin_pony")
  2843. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  2844. operation = migrations.RemoveIndex("Pony", "pony_test_idx")
  2845. self.assertEqual(operation.describe(), "Remove index pony_test_idx from Pony")
  2846. self.assertEqual(
  2847. operation.migration_name_fragment,
  2848. "remove_pony_pony_test_idx",
  2849. )
  2850. new_state = project_state.clone()
  2851. operation.state_forwards("test_rmin", new_state)
  2852. # Test the state alteration
  2853. self.assertEqual(
  2854. len(new_state.models["test_rmin", "pony"].options["indexes"]), 0
  2855. )
  2856. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  2857. # Test the database alteration
  2858. with connection.schema_editor() as editor:
  2859. operation.database_forwards("test_rmin", editor, project_state, new_state)
  2860. self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"])
  2861. # And test reversal
  2862. with connection.schema_editor() as editor:
  2863. operation.database_backwards("test_rmin", editor, new_state, project_state)
  2864. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  2865. # And deconstruction
  2866. definition = operation.deconstruct()
  2867. self.assertEqual(definition[0], "RemoveIndex")
  2868. self.assertEqual(definition[1], [])
  2869. self.assertEqual(definition[2], {"model_name": "Pony", "name": "pony_test_idx"})
  2870. # Also test a field dropped with index - sqlite remake issue
  2871. operations = [
  2872. migrations.RemoveIndex("Pony", "pony_test_idx"),
  2873. migrations.RemoveField("Pony", "pink"),
  2874. ]
  2875. self.assertColumnExists("test_rmin_pony", "pink")
  2876. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  2877. # Test database alteration
  2878. new_state = project_state.clone()
  2879. self.apply_operations("test_rmin", new_state, operations=operations)
  2880. self.assertColumnNotExists("test_rmin_pony", "pink")
  2881. self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"])
  2882. # And test reversal
  2883. self.unapply_operations("test_rmin", project_state, operations=operations)
  2884. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  2885. def test_rename_index(self):
  2886. app_label = "test_rnin"
  2887. project_state = self.set_up_test_model(app_label, index=True)
  2888. table_name = app_label + "_pony"
  2889. self.assertIndexNameExists(table_name, "pony_pink_idx")
  2890. self.assertIndexNameNotExists(table_name, "new_pony_test_idx")
  2891. operation = migrations.RenameIndex(
  2892. "Pony", new_name="new_pony_test_idx", old_name="pony_pink_idx"
  2893. )
  2894. self.assertEqual(
  2895. operation.describe(),
  2896. "Rename index pony_pink_idx on Pony to new_pony_test_idx",
  2897. )
  2898. self.assertEqual(
  2899. operation.migration_name_fragment,
  2900. "rename_pony_pink_idx_new_pony_test_idx",
  2901. )
  2902. new_state = project_state.clone()
  2903. operation.state_forwards(app_label, new_state)
  2904. # Rename index.
  2905. expected_queries = 1 if connection.features.can_rename_index else 2
  2906. with connection.schema_editor() as editor, self.assertNumQueries(
  2907. expected_queries
  2908. ):
  2909. operation.database_forwards(app_label, editor, project_state, new_state)
  2910. self.assertIndexNameNotExists(table_name, "pony_pink_idx")
  2911. self.assertIndexNameExists(table_name, "new_pony_test_idx")
  2912. # Reversal.
  2913. with connection.schema_editor() as editor, self.assertNumQueries(
  2914. expected_queries
  2915. ):
  2916. operation.database_backwards(app_label, editor, new_state, project_state)
  2917. self.assertIndexNameExists(table_name, "pony_pink_idx")
  2918. self.assertIndexNameNotExists(table_name, "new_pony_test_idx")
  2919. # Deconstruction.
  2920. definition = operation.deconstruct()
  2921. self.assertEqual(definition[0], "RenameIndex")
  2922. self.assertEqual(definition[1], [])
  2923. self.assertEqual(
  2924. definition[2],
  2925. {
  2926. "model_name": "Pony",
  2927. "old_name": "pony_pink_idx",
  2928. "new_name": "new_pony_test_idx",
  2929. },
  2930. )
  2931. def test_rename_index_arguments(self):
  2932. msg = "RenameIndex.old_name and old_fields are mutually exclusive."
  2933. with self.assertRaisesMessage(ValueError, msg):
  2934. migrations.RenameIndex(
  2935. "Pony",
  2936. new_name="new_idx_name",
  2937. old_name="old_idx_name",
  2938. old_fields=("weight", "pink"),
  2939. )
  2940. msg = "RenameIndex requires one of old_name and old_fields arguments to be set."
  2941. with self.assertRaisesMessage(ValueError, msg):
  2942. migrations.RenameIndex("Pony", new_name="new_idx_name")
  2943. @ignore_warnings(category=RemovedInDjango51Warning)
  2944. def test_rename_index_unnamed_index(self):
  2945. app_label = "test_rninui"
  2946. project_state = self.set_up_test_model(app_label, index_together=True)
  2947. table_name = app_label + "_pony"
  2948. self.assertIndexNameNotExists(table_name, "new_pony_test_idx")
  2949. operation = migrations.RenameIndex(
  2950. "Pony", new_name="new_pony_test_idx", old_fields=("weight", "pink")
  2951. )
  2952. self.assertEqual(
  2953. operation.describe(),
  2954. "Rename unnamed index for ('weight', 'pink') on Pony to new_pony_test_idx",
  2955. )
  2956. self.assertEqual(
  2957. operation.migration_name_fragment,
  2958. "rename_pony_weight_pink_new_pony_test_idx",
  2959. )
  2960. new_state = project_state.clone()
  2961. operation.state_forwards(app_label, new_state)
  2962. # Rename index.
  2963. with connection.schema_editor() as editor:
  2964. operation.database_forwards(app_label, editor, project_state, new_state)
  2965. self.assertIndexNameExists(table_name, "new_pony_test_idx")
  2966. # Reverse is a no-op.
  2967. with connection.schema_editor() as editor, self.assertNumQueries(0):
  2968. operation.database_backwards(app_label, editor, new_state, project_state)
  2969. self.assertIndexNameExists(table_name, "new_pony_test_idx")
  2970. # Reapply, RenameIndex operation is a noop when the old and new name
  2971. # match.
  2972. with connection.schema_editor() as editor:
  2973. operation.database_forwards(app_label, editor, new_state, project_state)
  2974. self.assertIndexNameExists(table_name, "new_pony_test_idx")
  2975. # Deconstruction.
  2976. definition = operation.deconstruct()
  2977. self.assertEqual(definition[0], "RenameIndex")
  2978. self.assertEqual(definition[1], [])
  2979. self.assertEqual(
  2980. definition[2],
  2981. {
  2982. "model_name": "Pony",
  2983. "new_name": "new_pony_test_idx",
  2984. "old_fields": ("weight", "pink"),
  2985. },
  2986. )
  2987. def test_rename_index_unknown_unnamed_index(self):
  2988. app_label = "test_rninuui"
  2989. project_state = self.set_up_test_model(app_label)
  2990. operation = migrations.RenameIndex(
  2991. "Pony", new_name="new_pony_test_idx", old_fields=("weight", "pink")
  2992. )
  2993. new_state = project_state.clone()
  2994. operation.state_forwards(app_label, new_state)
  2995. msg = "Found wrong number (0) of indexes for test_rninuui_pony(weight, pink)."
  2996. with connection.schema_editor() as editor:
  2997. with self.assertRaisesMessage(ValueError, msg):
  2998. operation.database_forwards(app_label, editor, project_state, new_state)
  2999. def test_add_index_state_forwards(self):
  3000. project_state = self.set_up_test_model("test_adinsf")
  3001. index = models.Index(fields=["pink"], name="test_adinsf_pony_pink_idx")
  3002. old_model = project_state.apps.get_model("test_adinsf", "Pony")
  3003. new_state = project_state.clone()
  3004. operation = migrations.AddIndex("Pony", index)
  3005. operation.state_forwards("test_adinsf", new_state)
  3006. new_model = new_state.apps.get_model("test_adinsf", "Pony")
  3007. self.assertIsNot(old_model, new_model)
  3008. def test_remove_index_state_forwards(self):
  3009. project_state = self.set_up_test_model("test_rminsf")
  3010. index = models.Index(fields=["pink"], name="test_rminsf_pony_pink_idx")
  3011. migrations.AddIndex("Pony", index).state_forwards("test_rminsf", project_state)
  3012. old_model = project_state.apps.get_model("test_rminsf", "Pony")
  3013. new_state = project_state.clone()
  3014. operation = migrations.RemoveIndex("Pony", "test_rminsf_pony_pink_idx")
  3015. operation.state_forwards("test_rminsf", new_state)
  3016. new_model = new_state.apps.get_model("test_rminsf", "Pony")
  3017. self.assertIsNot(old_model, new_model)
  3018. def test_rename_index_state_forwards(self):
  3019. app_label = "test_rnidsf"
  3020. project_state = self.set_up_test_model(app_label, index=True)
  3021. old_model = project_state.apps.get_model(app_label, "Pony")
  3022. new_state = project_state.clone()
  3023. operation = migrations.RenameIndex(
  3024. "Pony", new_name="new_pony_pink_idx", old_name="pony_pink_idx"
  3025. )
  3026. operation.state_forwards(app_label, new_state)
  3027. new_model = new_state.apps.get_model(app_label, "Pony")
  3028. self.assertIsNot(old_model, new_model)
  3029. self.assertEqual(new_model._meta.indexes[0].name, "new_pony_pink_idx")
  3030. @ignore_warnings(category=RemovedInDjango51Warning)
  3031. def test_rename_index_state_forwards_unnamed_index(self):
  3032. app_label = "test_rnidsfui"
  3033. project_state = self.set_up_test_model(app_label, index_together=True)
  3034. old_model = project_state.apps.get_model(app_label, "Pony")
  3035. new_state = project_state.clone()
  3036. operation = migrations.RenameIndex(
  3037. "Pony", new_name="new_pony_pink_idx", old_fields=("weight", "pink")
  3038. )
  3039. operation.state_forwards(app_label, new_state)
  3040. new_model = new_state.apps.get_model(app_label, "Pony")
  3041. self.assertIsNot(old_model, new_model)
  3042. self.assertEqual(new_model._meta.index_together, tuple())
  3043. self.assertEqual(new_model._meta.indexes[0].name, "new_pony_pink_idx")
  3044. @skipUnlessDBFeature("supports_expression_indexes")
  3045. def test_add_func_index(self):
  3046. app_label = "test_addfuncin"
  3047. index_name = f"{app_label}_pony_abs_idx"
  3048. table_name = f"{app_label}_pony"
  3049. project_state = self.set_up_test_model(app_label)
  3050. index = models.Index(Abs("weight"), name=index_name)
  3051. operation = migrations.AddIndex("Pony", index)
  3052. self.assertEqual(
  3053. operation.describe(),
  3054. "Create index test_addfuncin_pony_abs_idx on Abs(F(weight)) on model Pony",
  3055. )
  3056. self.assertEqual(
  3057. operation.migration_name_fragment,
  3058. "pony_test_addfuncin_pony_abs_idx",
  3059. )
  3060. new_state = project_state.clone()
  3061. operation.state_forwards(app_label, new_state)
  3062. self.assertEqual(len(new_state.models[app_label, "pony"].options["indexes"]), 1)
  3063. self.assertIndexNameNotExists(table_name, index_name)
  3064. # Add index.
  3065. with connection.schema_editor() as editor:
  3066. operation.database_forwards(app_label, editor, project_state, new_state)
  3067. self.assertIndexNameExists(table_name, index_name)
  3068. # Reversal.
  3069. with connection.schema_editor() as editor:
  3070. operation.database_backwards(app_label, editor, new_state, project_state)
  3071. self.assertIndexNameNotExists(table_name, index_name)
  3072. # Deconstruction.
  3073. definition = operation.deconstruct()
  3074. self.assertEqual(definition[0], "AddIndex")
  3075. self.assertEqual(definition[1], [])
  3076. self.assertEqual(definition[2], {"model_name": "Pony", "index": index})
  3077. @skipUnlessDBFeature("supports_expression_indexes")
  3078. def test_remove_func_index(self):
  3079. app_label = "test_rmfuncin"
  3080. index_name = f"{app_label}_pony_abs_idx"
  3081. table_name = f"{app_label}_pony"
  3082. project_state = self.set_up_test_model(
  3083. app_label,
  3084. indexes=[
  3085. models.Index(Abs("weight"), name=index_name),
  3086. ],
  3087. )
  3088. self.assertTableExists(table_name)
  3089. self.assertIndexNameExists(table_name, index_name)
  3090. operation = migrations.RemoveIndex("Pony", index_name)
  3091. self.assertEqual(
  3092. operation.describe(),
  3093. "Remove index test_rmfuncin_pony_abs_idx from Pony",
  3094. )
  3095. self.assertEqual(
  3096. operation.migration_name_fragment,
  3097. "remove_pony_test_rmfuncin_pony_abs_idx",
  3098. )
  3099. new_state = project_state.clone()
  3100. operation.state_forwards(app_label, new_state)
  3101. self.assertEqual(len(new_state.models[app_label, "pony"].options["indexes"]), 0)
  3102. # Remove index.
  3103. with connection.schema_editor() as editor:
  3104. operation.database_forwards(app_label, editor, project_state, new_state)
  3105. self.assertIndexNameNotExists(table_name, index_name)
  3106. # Reversal.
  3107. with connection.schema_editor() as editor:
  3108. operation.database_backwards(app_label, editor, new_state, project_state)
  3109. self.assertIndexNameExists(table_name, index_name)
  3110. # Deconstruction.
  3111. definition = operation.deconstruct()
  3112. self.assertEqual(definition[0], "RemoveIndex")
  3113. self.assertEqual(definition[1], [])
  3114. self.assertEqual(definition[2], {"model_name": "Pony", "name": index_name})
  3115. @skipUnlessDBFeature("supports_expression_indexes")
  3116. def test_alter_field_with_func_index(self):
  3117. app_label = "test_alfuncin"
  3118. index_name = f"{app_label}_pony_idx"
  3119. table_name = f"{app_label}_pony"
  3120. project_state = self.set_up_test_model(
  3121. app_label,
  3122. indexes=[models.Index(Abs("pink"), name=index_name)],
  3123. )
  3124. operation = migrations.AlterField(
  3125. "Pony", "pink", models.IntegerField(null=True)
  3126. )
  3127. new_state = project_state.clone()
  3128. operation.state_forwards(app_label, new_state)
  3129. with connection.schema_editor() as editor:
  3130. operation.database_forwards(app_label, editor, project_state, new_state)
  3131. self.assertIndexNameExists(table_name, index_name)
  3132. with connection.schema_editor() as editor:
  3133. operation.database_backwards(app_label, editor, new_state, project_state)
  3134. self.assertIndexNameExists(table_name, index_name)
  3135. def test_alter_field_with_index(self):
  3136. """
  3137. Test AlterField operation with an index to ensure indexes created via
  3138. Meta.indexes don't get dropped with sqlite3 remake.
  3139. """
  3140. project_state = self.set_up_test_model("test_alflin", index=True)
  3141. operation = migrations.AlterField(
  3142. "Pony", "pink", models.IntegerField(null=True)
  3143. )
  3144. new_state = project_state.clone()
  3145. operation.state_forwards("test_alflin", new_state)
  3146. # Test the database alteration
  3147. self.assertColumnNotNull("test_alflin_pony", "pink")
  3148. with connection.schema_editor() as editor:
  3149. operation.database_forwards("test_alflin", editor, project_state, new_state)
  3150. # Index hasn't been dropped
  3151. self.assertIndexExists("test_alflin_pony", ["pink"])
  3152. # And test reversal
  3153. with connection.schema_editor() as editor:
  3154. operation.database_backwards(
  3155. "test_alflin", editor, new_state, project_state
  3156. )
  3157. # Ensure the index is still there
  3158. self.assertIndexExists("test_alflin_pony", ["pink"])
  3159. @ignore_warnings(category=RemovedInDjango51Warning)
  3160. def test_alter_index_together(self):
  3161. """
  3162. Tests the AlterIndexTogether operation.
  3163. """
  3164. project_state = self.set_up_test_model("test_alinto")
  3165. # Test the state alteration
  3166. operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")])
  3167. self.assertEqual(
  3168. operation.describe(), "Alter index_together for Pony (1 constraint(s))"
  3169. )
  3170. self.assertEqual(
  3171. operation.migration_name_fragment,
  3172. "alter_pony_index_together",
  3173. )
  3174. new_state = project_state.clone()
  3175. operation.state_forwards("test_alinto", new_state)
  3176. self.assertEqual(
  3177. len(
  3178. project_state.models["test_alinto", "pony"].options.get(
  3179. "index_together", set()
  3180. )
  3181. ),
  3182. 0,
  3183. )
  3184. self.assertEqual(
  3185. len(
  3186. new_state.models["test_alinto", "pony"].options.get(
  3187. "index_together", set()
  3188. )
  3189. ),
  3190. 1,
  3191. )
  3192. # Make sure there's no matching index
  3193. self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"])
  3194. # Test the database alteration
  3195. with connection.schema_editor() as editor:
  3196. operation.database_forwards("test_alinto", editor, project_state, new_state)
  3197. self.assertIndexExists("test_alinto_pony", ["pink", "weight"])
  3198. # And test reversal
  3199. with connection.schema_editor() as editor:
  3200. operation.database_backwards(
  3201. "test_alinto", editor, new_state, project_state
  3202. )
  3203. self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"])
  3204. # And deconstruction
  3205. definition = operation.deconstruct()
  3206. self.assertEqual(definition[0], "AlterIndexTogether")
  3207. self.assertEqual(definition[1], [])
  3208. self.assertEqual(
  3209. definition[2], {"name": "Pony", "index_together": {("pink", "weight")}}
  3210. )
  3211. def test_alter_index_together_remove(self):
  3212. operation = migrations.AlterIndexTogether("Pony", None)
  3213. self.assertEqual(
  3214. operation.describe(), "Alter index_together for Pony (0 constraint(s))"
  3215. )
  3216. @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields")
  3217. @ignore_warnings(category=RemovedInDjango51Warning)
  3218. def test_alter_index_together_remove_with_unique_together(self):
  3219. app_label = "test_alintoremove_wunto"
  3220. table_name = "%s_pony" % app_label
  3221. project_state = self.set_up_test_model(app_label, unique_together=True)
  3222. self.assertUniqueConstraintExists(table_name, ["pink", "weight"])
  3223. # Add index together.
  3224. new_state = project_state.clone()
  3225. operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")])
  3226. operation.state_forwards(app_label, new_state)
  3227. with connection.schema_editor() as editor:
  3228. operation.database_forwards(app_label, editor, project_state, new_state)
  3229. self.assertIndexExists(table_name, ["pink", "weight"])
  3230. # Remove index together.
  3231. project_state = new_state
  3232. new_state = project_state.clone()
  3233. operation = migrations.AlterIndexTogether("Pony", set())
  3234. operation.state_forwards(app_label, new_state)
  3235. with connection.schema_editor() as editor:
  3236. operation.database_forwards(app_label, editor, project_state, new_state)
  3237. self.assertIndexNotExists(table_name, ["pink", "weight"])
  3238. self.assertUniqueConstraintExists(table_name, ["pink", "weight"])
  3239. @skipUnlessDBFeature("supports_table_check_constraints")
  3240. def test_add_constraint(self):
  3241. project_state = self.set_up_test_model("test_addconstraint")
  3242. gt_check = models.Q(pink__gt=2)
  3243. gt_constraint = models.CheckConstraint(
  3244. check=gt_check, name="test_add_constraint_pony_pink_gt_2"
  3245. )
  3246. gt_operation = migrations.AddConstraint("Pony", gt_constraint)
  3247. self.assertEqual(
  3248. gt_operation.describe(),
  3249. "Create constraint test_add_constraint_pony_pink_gt_2 on model Pony",
  3250. )
  3251. self.assertEqual(
  3252. gt_operation.migration_name_fragment,
  3253. "pony_test_add_constraint_pony_pink_gt_2",
  3254. )
  3255. # Test the state alteration
  3256. new_state = project_state.clone()
  3257. gt_operation.state_forwards("test_addconstraint", new_state)
  3258. self.assertEqual(
  3259. len(new_state.models["test_addconstraint", "pony"].options["constraints"]),
  3260. 1,
  3261. )
  3262. Pony = new_state.apps.get_model("test_addconstraint", "Pony")
  3263. self.assertEqual(len(Pony._meta.constraints), 1)
  3264. # Test the database alteration
  3265. with connection.schema_editor() as editor:
  3266. gt_operation.database_forwards(
  3267. "test_addconstraint", editor, project_state, new_state
  3268. )
  3269. with self.assertRaises(IntegrityError), transaction.atomic():
  3270. Pony.objects.create(pink=1, weight=1.0)
  3271. # Add another one.
  3272. lt_check = models.Q(pink__lt=100)
  3273. lt_constraint = models.CheckConstraint(
  3274. check=lt_check, name="test_add_constraint_pony_pink_lt_100"
  3275. )
  3276. lt_operation = migrations.AddConstraint("Pony", lt_constraint)
  3277. lt_operation.state_forwards("test_addconstraint", new_state)
  3278. self.assertEqual(
  3279. len(new_state.models["test_addconstraint", "pony"].options["constraints"]),
  3280. 2,
  3281. )
  3282. Pony = new_state.apps.get_model("test_addconstraint", "Pony")
  3283. self.assertEqual(len(Pony._meta.constraints), 2)
  3284. with connection.schema_editor() as editor:
  3285. lt_operation.database_forwards(
  3286. "test_addconstraint", editor, project_state, new_state
  3287. )
  3288. with self.assertRaises(IntegrityError), transaction.atomic():
  3289. Pony.objects.create(pink=100, weight=1.0)
  3290. # Test reversal
  3291. with connection.schema_editor() as editor:
  3292. gt_operation.database_backwards(
  3293. "test_addconstraint", editor, new_state, project_state
  3294. )
  3295. Pony.objects.create(pink=1, weight=1.0)
  3296. # Test deconstruction
  3297. definition = gt_operation.deconstruct()
  3298. self.assertEqual(definition[0], "AddConstraint")
  3299. self.assertEqual(definition[1], [])
  3300. self.assertEqual(
  3301. definition[2], {"model_name": "Pony", "constraint": gt_constraint}
  3302. )
  3303. @skipUnlessDBFeature("supports_table_check_constraints")
  3304. def test_add_constraint_percent_escaping(self):
  3305. app_label = "add_constraint_string_quoting"
  3306. operations = [
  3307. migrations.CreateModel(
  3308. "Author",
  3309. fields=[
  3310. ("id", models.AutoField(primary_key=True)),
  3311. ("name", models.CharField(max_length=100)),
  3312. ("surname", models.CharField(max_length=100, default="")),
  3313. ("rebate", models.CharField(max_length=100)),
  3314. ],
  3315. ),
  3316. ]
  3317. from_state = self.apply_operations(app_label, ProjectState(), operations)
  3318. # "%" generated in startswith lookup should be escaped in a way that is
  3319. # considered a leading wildcard.
  3320. check = models.Q(name__startswith="Albert")
  3321. constraint = models.CheckConstraint(check=check, name="name_constraint")
  3322. operation = migrations.AddConstraint("Author", constraint)
  3323. to_state = from_state.clone()
  3324. operation.state_forwards(app_label, to_state)
  3325. with connection.schema_editor() as editor:
  3326. operation.database_forwards(app_label, editor, from_state, to_state)
  3327. Author = to_state.apps.get_model(app_label, "Author")
  3328. with self.assertRaises(IntegrityError), transaction.atomic():
  3329. Author.objects.create(name="Artur")
  3330. # Literal "%" should be escaped in a way that is not a considered a
  3331. # wildcard.
  3332. check = models.Q(rebate__endswith="%")
  3333. constraint = models.CheckConstraint(check=check, name="rebate_constraint")
  3334. operation = migrations.AddConstraint("Author", constraint)
  3335. from_state = to_state
  3336. to_state = from_state.clone()
  3337. operation.state_forwards(app_label, to_state)
  3338. Author = to_state.apps.get_model(app_label, "Author")
  3339. with connection.schema_editor() as editor:
  3340. operation.database_forwards(app_label, editor, from_state, to_state)
  3341. Author = to_state.apps.get_model(app_label, "Author")
  3342. with self.assertRaises(IntegrityError), transaction.atomic():
  3343. Author.objects.create(name="Albert", rebate="10$")
  3344. author = Author.objects.create(name="Albert", rebate="10%")
  3345. self.assertEqual(Author.objects.get(), author)
  3346. # Right-hand-side baked "%" literals should not be used for parameters
  3347. # interpolation.
  3348. check = ~models.Q(surname__startswith=models.F("name"))
  3349. constraint = models.CheckConstraint(check=check, name="name_constraint_rhs")
  3350. operation = migrations.AddConstraint("Author", constraint)
  3351. from_state = to_state
  3352. to_state = from_state.clone()
  3353. operation.state_forwards(app_label, to_state)
  3354. with connection.schema_editor() as editor:
  3355. operation.database_forwards(app_label, editor, from_state, to_state)
  3356. Author = to_state.apps.get_model(app_label, "Author")
  3357. with self.assertRaises(IntegrityError), transaction.atomic():
  3358. Author.objects.create(name="Albert", surname="Alberto")
  3359. @skipUnlessDBFeature("supports_table_check_constraints")
  3360. def test_add_or_constraint(self):
  3361. app_label = "test_addorconstraint"
  3362. constraint_name = "add_constraint_or"
  3363. from_state = self.set_up_test_model(app_label)
  3364. check = models.Q(pink__gt=2, weight__gt=2) | models.Q(weight__lt=0)
  3365. constraint = models.CheckConstraint(check=check, name=constraint_name)
  3366. operation = migrations.AddConstraint("Pony", constraint)
  3367. to_state = from_state.clone()
  3368. operation.state_forwards(app_label, to_state)
  3369. with connection.schema_editor() as editor:
  3370. operation.database_forwards(app_label, editor, from_state, to_state)
  3371. Pony = to_state.apps.get_model(app_label, "Pony")
  3372. with self.assertRaises(IntegrityError), transaction.atomic():
  3373. Pony.objects.create(pink=2, weight=3.0)
  3374. with self.assertRaises(IntegrityError), transaction.atomic():
  3375. Pony.objects.create(pink=3, weight=1.0)
  3376. Pony.objects.bulk_create(
  3377. [
  3378. Pony(pink=3, weight=-1.0),
  3379. Pony(pink=1, weight=-1.0),
  3380. Pony(pink=3, weight=3.0),
  3381. ]
  3382. )
  3383. @skipUnlessDBFeature("supports_table_check_constraints")
  3384. def test_add_constraint_combinable(self):
  3385. app_label = "test_addconstraint_combinable"
  3386. operations = [
  3387. migrations.CreateModel(
  3388. "Book",
  3389. fields=[
  3390. ("id", models.AutoField(primary_key=True)),
  3391. ("read", models.PositiveIntegerField()),
  3392. ("unread", models.PositiveIntegerField()),
  3393. ],
  3394. ),
  3395. ]
  3396. from_state = self.apply_operations(app_label, ProjectState(), operations)
  3397. constraint = models.CheckConstraint(
  3398. check=models.Q(read=(100 - models.F("unread"))),
  3399. name="test_addconstraint_combinable_sum_100",
  3400. )
  3401. operation = migrations.AddConstraint("Book", constraint)
  3402. to_state = from_state.clone()
  3403. operation.state_forwards(app_label, to_state)
  3404. with connection.schema_editor() as editor:
  3405. operation.database_forwards(app_label, editor, from_state, to_state)
  3406. Book = to_state.apps.get_model(app_label, "Book")
  3407. with self.assertRaises(IntegrityError), transaction.atomic():
  3408. Book.objects.create(read=70, unread=10)
  3409. Book.objects.create(read=70, unread=30)
  3410. @skipUnlessDBFeature("supports_table_check_constraints")
  3411. def test_remove_constraint(self):
  3412. project_state = self.set_up_test_model(
  3413. "test_removeconstraint",
  3414. constraints=[
  3415. models.CheckConstraint(
  3416. check=models.Q(pink__gt=2),
  3417. name="test_remove_constraint_pony_pink_gt_2",
  3418. ),
  3419. models.CheckConstraint(
  3420. check=models.Q(pink__lt=100),
  3421. name="test_remove_constraint_pony_pink_lt_100",
  3422. ),
  3423. ],
  3424. )
  3425. gt_operation = migrations.RemoveConstraint(
  3426. "Pony", "test_remove_constraint_pony_pink_gt_2"
  3427. )
  3428. self.assertEqual(
  3429. gt_operation.describe(),
  3430. "Remove constraint test_remove_constraint_pony_pink_gt_2 from model Pony",
  3431. )
  3432. self.assertEqual(
  3433. gt_operation.migration_name_fragment,
  3434. "remove_pony_test_remove_constraint_pony_pink_gt_2",
  3435. )
  3436. # Test state alteration
  3437. new_state = project_state.clone()
  3438. gt_operation.state_forwards("test_removeconstraint", new_state)
  3439. self.assertEqual(
  3440. len(
  3441. new_state.models["test_removeconstraint", "pony"].options["constraints"]
  3442. ),
  3443. 1,
  3444. )
  3445. Pony = new_state.apps.get_model("test_removeconstraint", "Pony")
  3446. self.assertEqual(len(Pony._meta.constraints), 1)
  3447. # Test database alteration
  3448. with connection.schema_editor() as editor:
  3449. gt_operation.database_forwards(
  3450. "test_removeconstraint", editor, project_state, new_state
  3451. )
  3452. Pony.objects.create(pink=1, weight=1.0).delete()
  3453. with self.assertRaises(IntegrityError), transaction.atomic():
  3454. Pony.objects.create(pink=100, weight=1.0)
  3455. # Remove the other one.
  3456. lt_operation = migrations.RemoveConstraint(
  3457. "Pony", "test_remove_constraint_pony_pink_lt_100"
  3458. )
  3459. lt_operation.state_forwards("test_removeconstraint", new_state)
  3460. self.assertEqual(
  3461. len(
  3462. new_state.models["test_removeconstraint", "pony"].options["constraints"]
  3463. ),
  3464. 0,
  3465. )
  3466. Pony = new_state.apps.get_model("test_removeconstraint", "Pony")
  3467. self.assertEqual(len(Pony._meta.constraints), 0)
  3468. with connection.schema_editor() as editor:
  3469. lt_operation.database_forwards(
  3470. "test_removeconstraint", editor, project_state, new_state
  3471. )
  3472. Pony.objects.create(pink=100, weight=1.0).delete()
  3473. # Test reversal
  3474. with connection.schema_editor() as editor:
  3475. gt_operation.database_backwards(
  3476. "test_removeconstraint", editor, new_state, project_state
  3477. )
  3478. with self.assertRaises(IntegrityError), transaction.atomic():
  3479. Pony.objects.create(pink=1, weight=1.0)
  3480. # Test deconstruction
  3481. definition = gt_operation.deconstruct()
  3482. self.assertEqual(definition[0], "RemoveConstraint")
  3483. self.assertEqual(definition[1], [])
  3484. self.assertEqual(
  3485. definition[2],
  3486. {"model_name": "Pony", "name": "test_remove_constraint_pony_pink_gt_2"},
  3487. )
  3488. def test_add_partial_unique_constraint(self):
  3489. project_state = self.set_up_test_model("test_addpartialuniqueconstraint")
  3490. partial_unique_constraint = models.UniqueConstraint(
  3491. fields=["pink"],
  3492. condition=models.Q(weight__gt=5),
  3493. name="test_constraint_pony_pink_for_weight_gt_5_uniq",
  3494. )
  3495. operation = migrations.AddConstraint("Pony", partial_unique_constraint)
  3496. self.assertEqual(
  3497. operation.describe(),
  3498. "Create constraint test_constraint_pony_pink_for_weight_gt_5_uniq "
  3499. "on model Pony",
  3500. )
  3501. # Test the state alteration
  3502. new_state = project_state.clone()
  3503. operation.state_forwards("test_addpartialuniqueconstraint", new_state)
  3504. self.assertEqual(
  3505. len(
  3506. new_state.models["test_addpartialuniqueconstraint", "pony"].options[
  3507. "constraints"
  3508. ]
  3509. ),
  3510. 1,
  3511. )
  3512. Pony = new_state.apps.get_model("test_addpartialuniqueconstraint", "Pony")
  3513. self.assertEqual(len(Pony._meta.constraints), 1)
  3514. # Test the database alteration
  3515. with connection.schema_editor() as editor:
  3516. operation.database_forwards(
  3517. "test_addpartialuniqueconstraint", editor, project_state, new_state
  3518. )
  3519. # Test constraint works
  3520. Pony.objects.create(pink=1, weight=4.0)
  3521. Pony.objects.create(pink=1, weight=4.0)
  3522. Pony.objects.create(pink=1, weight=6.0)
  3523. if connection.features.supports_partial_indexes:
  3524. with self.assertRaises(IntegrityError), transaction.atomic():
  3525. Pony.objects.create(pink=1, weight=7.0)
  3526. else:
  3527. Pony.objects.create(pink=1, weight=7.0)
  3528. # Test reversal
  3529. with connection.schema_editor() as editor:
  3530. operation.database_backwards(
  3531. "test_addpartialuniqueconstraint", editor, new_state, project_state
  3532. )
  3533. # Test constraint doesn't work
  3534. Pony.objects.create(pink=1, weight=7.0)
  3535. # Test deconstruction
  3536. definition = operation.deconstruct()
  3537. self.assertEqual(definition[0], "AddConstraint")
  3538. self.assertEqual(definition[1], [])
  3539. self.assertEqual(
  3540. definition[2],
  3541. {"model_name": "Pony", "constraint": partial_unique_constraint},
  3542. )
  3543. def test_remove_partial_unique_constraint(self):
  3544. project_state = self.set_up_test_model(
  3545. "test_removepartialuniqueconstraint",
  3546. constraints=[
  3547. models.UniqueConstraint(
  3548. fields=["pink"],
  3549. condition=models.Q(weight__gt=5),
  3550. name="test_constraint_pony_pink_for_weight_gt_5_uniq",
  3551. ),
  3552. ],
  3553. )
  3554. gt_operation = migrations.RemoveConstraint(
  3555. "Pony", "test_constraint_pony_pink_for_weight_gt_5_uniq"
  3556. )
  3557. self.assertEqual(
  3558. gt_operation.describe(),
  3559. "Remove constraint test_constraint_pony_pink_for_weight_gt_5_uniq from "
  3560. "model Pony",
  3561. )
  3562. # Test state alteration
  3563. new_state = project_state.clone()
  3564. gt_operation.state_forwards("test_removepartialuniqueconstraint", new_state)
  3565. self.assertEqual(
  3566. len(
  3567. new_state.models["test_removepartialuniqueconstraint", "pony"].options[
  3568. "constraints"
  3569. ]
  3570. ),
  3571. 0,
  3572. )
  3573. Pony = new_state.apps.get_model("test_removepartialuniqueconstraint", "Pony")
  3574. self.assertEqual(len(Pony._meta.constraints), 0)
  3575. # Test database alteration
  3576. with connection.schema_editor() as editor:
  3577. gt_operation.database_forwards(
  3578. "test_removepartialuniqueconstraint", editor, project_state, new_state
  3579. )
  3580. # Test constraint doesn't work
  3581. Pony.objects.create(pink=1, weight=4.0)
  3582. Pony.objects.create(pink=1, weight=4.0)
  3583. Pony.objects.create(pink=1, weight=6.0)
  3584. Pony.objects.create(pink=1, weight=7.0).delete()
  3585. # Test reversal
  3586. with connection.schema_editor() as editor:
  3587. gt_operation.database_backwards(
  3588. "test_removepartialuniqueconstraint", editor, new_state, project_state
  3589. )
  3590. # Test constraint works
  3591. if connection.features.supports_partial_indexes:
  3592. with self.assertRaises(IntegrityError), transaction.atomic():
  3593. Pony.objects.create(pink=1, weight=7.0)
  3594. else:
  3595. Pony.objects.create(pink=1, weight=7.0)
  3596. # Test deconstruction
  3597. definition = gt_operation.deconstruct()
  3598. self.assertEqual(definition[0], "RemoveConstraint")
  3599. self.assertEqual(definition[1], [])
  3600. self.assertEqual(
  3601. definition[2],
  3602. {
  3603. "model_name": "Pony",
  3604. "name": "test_constraint_pony_pink_for_weight_gt_5_uniq",
  3605. },
  3606. )
  3607. def test_add_deferred_unique_constraint(self):
  3608. app_label = "test_adddeferred_uc"
  3609. project_state = self.set_up_test_model(app_label)
  3610. deferred_unique_constraint = models.UniqueConstraint(
  3611. fields=["pink"],
  3612. name="deferred_pink_constraint_add",
  3613. deferrable=models.Deferrable.DEFERRED,
  3614. )
  3615. operation = migrations.AddConstraint("Pony", deferred_unique_constraint)
  3616. self.assertEqual(
  3617. operation.describe(),
  3618. "Create constraint deferred_pink_constraint_add on model Pony",
  3619. )
  3620. # Add constraint.
  3621. new_state = project_state.clone()
  3622. operation.state_forwards(app_label, new_state)
  3623. self.assertEqual(
  3624. len(new_state.models[app_label, "pony"].options["constraints"]), 1
  3625. )
  3626. Pony = new_state.apps.get_model(app_label, "Pony")
  3627. self.assertEqual(len(Pony._meta.constraints), 1)
  3628. with connection.schema_editor() as editor, CaptureQueriesContext(
  3629. connection
  3630. ) as ctx:
  3631. operation.database_forwards(app_label, editor, project_state, new_state)
  3632. Pony.objects.create(pink=1, weight=4.0)
  3633. if connection.features.supports_deferrable_unique_constraints:
  3634. # Unique constraint is deferred.
  3635. with transaction.atomic():
  3636. obj = Pony.objects.create(pink=1, weight=4.0)
  3637. obj.pink = 2
  3638. obj.save()
  3639. # Constraint behavior can be changed with SET CONSTRAINTS.
  3640. with self.assertRaises(IntegrityError):
  3641. with transaction.atomic(), connection.cursor() as cursor:
  3642. quoted_name = connection.ops.quote_name(
  3643. deferred_unique_constraint.name
  3644. )
  3645. cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name)
  3646. obj = Pony.objects.create(pink=1, weight=4.0)
  3647. obj.pink = 3
  3648. obj.save()
  3649. else:
  3650. self.assertEqual(len(ctx), 0)
  3651. Pony.objects.create(pink=1, weight=4.0)
  3652. # Reversal.
  3653. with connection.schema_editor() as editor:
  3654. operation.database_backwards(app_label, editor, new_state, project_state)
  3655. # Constraint doesn't work.
  3656. Pony.objects.create(pink=1, weight=4.0)
  3657. # Deconstruction.
  3658. definition = operation.deconstruct()
  3659. self.assertEqual(definition[0], "AddConstraint")
  3660. self.assertEqual(definition[1], [])
  3661. self.assertEqual(
  3662. definition[2],
  3663. {"model_name": "Pony", "constraint": deferred_unique_constraint},
  3664. )
  3665. def test_remove_deferred_unique_constraint(self):
  3666. app_label = "test_removedeferred_uc"
  3667. deferred_unique_constraint = models.UniqueConstraint(
  3668. fields=["pink"],
  3669. name="deferred_pink_constraint_rm",
  3670. deferrable=models.Deferrable.DEFERRED,
  3671. )
  3672. project_state = self.set_up_test_model(
  3673. app_label, constraints=[deferred_unique_constraint]
  3674. )
  3675. operation = migrations.RemoveConstraint("Pony", deferred_unique_constraint.name)
  3676. self.assertEqual(
  3677. operation.describe(),
  3678. "Remove constraint deferred_pink_constraint_rm from model Pony",
  3679. )
  3680. # Remove constraint.
  3681. new_state = project_state.clone()
  3682. operation.state_forwards(app_label, new_state)
  3683. self.assertEqual(
  3684. len(new_state.models[app_label, "pony"].options["constraints"]), 0
  3685. )
  3686. Pony = new_state.apps.get_model(app_label, "Pony")
  3687. self.assertEqual(len(Pony._meta.constraints), 0)
  3688. with connection.schema_editor() as editor, CaptureQueriesContext(
  3689. connection
  3690. ) as ctx:
  3691. operation.database_forwards(app_label, editor, project_state, new_state)
  3692. # Constraint doesn't work.
  3693. Pony.objects.create(pink=1, weight=4.0)
  3694. Pony.objects.create(pink=1, weight=4.0).delete()
  3695. if not connection.features.supports_deferrable_unique_constraints:
  3696. self.assertEqual(len(ctx), 0)
  3697. # Reversal.
  3698. with connection.schema_editor() as editor:
  3699. operation.database_backwards(app_label, editor, new_state, project_state)
  3700. if connection.features.supports_deferrable_unique_constraints:
  3701. # Unique constraint is deferred.
  3702. with transaction.atomic():
  3703. obj = Pony.objects.create(pink=1, weight=4.0)
  3704. obj.pink = 2
  3705. obj.save()
  3706. # Constraint behavior can be changed with SET CONSTRAINTS.
  3707. with self.assertRaises(IntegrityError):
  3708. with transaction.atomic(), connection.cursor() as cursor:
  3709. quoted_name = connection.ops.quote_name(
  3710. deferred_unique_constraint.name
  3711. )
  3712. cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name)
  3713. obj = Pony.objects.create(pink=1, weight=4.0)
  3714. obj.pink = 3
  3715. obj.save()
  3716. else:
  3717. Pony.objects.create(pink=1, weight=4.0)
  3718. # Deconstruction.
  3719. definition = operation.deconstruct()
  3720. self.assertEqual(definition[0], "RemoveConstraint")
  3721. self.assertEqual(definition[1], [])
  3722. self.assertEqual(
  3723. definition[2],
  3724. {
  3725. "model_name": "Pony",
  3726. "name": "deferred_pink_constraint_rm",
  3727. },
  3728. )
  3729. def test_add_covering_unique_constraint(self):
  3730. app_label = "test_addcovering_uc"
  3731. project_state = self.set_up_test_model(app_label)
  3732. covering_unique_constraint = models.UniqueConstraint(
  3733. fields=["pink"],
  3734. name="covering_pink_constraint_add",
  3735. include=["weight"],
  3736. )
  3737. operation = migrations.AddConstraint("Pony", covering_unique_constraint)
  3738. self.assertEqual(
  3739. operation.describe(),
  3740. "Create constraint covering_pink_constraint_add on model Pony",
  3741. )
  3742. # Add constraint.
  3743. new_state = project_state.clone()
  3744. operation.state_forwards(app_label, new_state)
  3745. self.assertEqual(
  3746. len(new_state.models[app_label, "pony"].options["constraints"]), 1
  3747. )
  3748. Pony = new_state.apps.get_model(app_label, "Pony")
  3749. self.assertEqual(len(Pony._meta.constraints), 1)
  3750. with connection.schema_editor() as editor, CaptureQueriesContext(
  3751. connection
  3752. ) as ctx:
  3753. operation.database_forwards(app_label, editor, project_state, new_state)
  3754. Pony.objects.create(pink=1, weight=4.0)
  3755. if connection.features.supports_covering_indexes:
  3756. with self.assertRaises(IntegrityError):
  3757. Pony.objects.create(pink=1, weight=4.0)
  3758. else:
  3759. self.assertEqual(len(ctx), 0)
  3760. Pony.objects.create(pink=1, weight=4.0)
  3761. # Reversal.
  3762. with connection.schema_editor() as editor:
  3763. operation.database_backwards(app_label, editor, new_state, project_state)
  3764. # Constraint doesn't work.
  3765. Pony.objects.create(pink=1, weight=4.0)
  3766. # Deconstruction.
  3767. definition = operation.deconstruct()
  3768. self.assertEqual(definition[0], "AddConstraint")
  3769. self.assertEqual(definition[1], [])
  3770. self.assertEqual(
  3771. definition[2],
  3772. {"model_name": "Pony", "constraint": covering_unique_constraint},
  3773. )
  3774. def test_remove_covering_unique_constraint(self):
  3775. app_label = "test_removecovering_uc"
  3776. covering_unique_constraint = models.UniqueConstraint(
  3777. fields=["pink"],
  3778. name="covering_pink_constraint_rm",
  3779. include=["weight"],
  3780. )
  3781. project_state = self.set_up_test_model(
  3782. app_label, constraints=[covering_unique_constraint]
  3783. )
  3784. operation = migrations.RemoveConstraint("Pony", covering_unique_constraint.name)
  3785. self.assertEqual(
  3786. operation.describe(),
  3787. "Remove constraint covering_pink_constraint_rm from model Pony",
  3788. )
  3789. # Remove constraint.
  3790. new_state = project_state.clone()
  3791. operation.state_forwards(app_label, new_state)
  3792. self.assertEqual(
  3793. len(new_state.models[app_label, "pony"].options["constraints"]), 0
  3794. )
  3795. Pony = new_state.apps.get_model(app_label, "Pony")
  3796. self.assertEqual(len(Pony._meta.constraints), 0)
  3797. with connection.schema_editor() as editor, CaptureQueriesContext(
  3798. connection
  3799. ) as ctx:
  3800. operation.database_forwards(app_label, editor, project_state, new_state)
  3801. # Constraint doesn't work.
  3802. Pony.objects.create(pink=1, weight=4.0)
  3803. Pony.objects.create(pink=1, weight=4.0).delete()
  3804. if not connection.features.supports_covering_indexes:
  3805. self.assertEqual(len(ctx), 0)
  3806. # Reversal.
  3807. with connection.schema_editor() as editor:
  3808. operation.database_backwards(app_label, editor, new_state, project_state)
  3809. if connection.features.supports_covering_indexes:
  3810. with self.assertRaises(IntegrityError):
  3811. Pony.objects.create(pink=1, weight=4.0)
  3812. else:
  3813. Pony.objects.create(pink=1, weight=4.0)
  3814. # Deconstruction.
  3815. definition = operation.deconstruct()
  3816. self.assertEqual(definition[0], "RemoveConstraint")
  3817. self.assertEqual(definition[1], [])
  3818. self.assertEqual(
  3819. definition[2],
  3820. {
  3821. "model_name": "Pony",
  3822. "name": "covering_pink_constraint_rm",
  3823. },
  3824. )
  3825. def test_alter_field_with_func_unique_constraint(self):
  3826. app_label = "test_alfuncuc"
  3827. constraint_name = f"{app_label}_pony_uq"
  3828. table_name = f"{app_label}_pony"
  3829. project_state = self.set_up_test_model(
  3830. app_label,
  3831. constraints=[
  3832. models.UniqueConstraint("pink", "weight", name=constraint_name)
  3833. ],
  3834. )
  3835. operation = migrations.AlterField(
  3836. "Pony", "pink", models.IntegerField(null=True)
  3837. )
  3838. new_state = project_state.clone()
  3839. operation.state_forwards(app_label, new_state)
  3840. with connection.schema_editor() as editor:
  3841. operation.database_forwards(app_label, editor, project_state, new_state)
  3842. if connection.features.supports_expression_indexes:
  3843. self.assertIndexNameExists(table_name, constraint_name)
  3844. with connection.schema_editor() as editor:
  3845. operation.database_backwards(app_label, editor, new_state, project_state)
  3846. if connection.features.supports_expression_indexes:
  3847. self.assertIndexNameExists(table_name, constraint_name)
  3848. def test_add_func_unique_constraint(self):
  3849. app_label = "test_adfuncuc"
  3850. constraint_name = f"{app_label}_pony_abs_uq"
  3851. table_name = f"{app_label}_pony"
  3852. project_state = self.set_up_test_model(app_label)
  3853. constraint = models.UniqueConstraint(Abs("weight"), name=constraint_name)
  3854. operation = migrations.AddConstraint("Pony", constraint)
  3855. self.assertEqual(
  3856. operation.describe(),
  3857. "Create constraint test_adfuncuc_pony_abs_uq on model Pony",
  3858. )
  3859. self.assertEqual(
  3860. operation.migration_name_fragment,
  3861. "pony_test_adfuncuc_pony_abs_uq",
  3862. )
  3863. new_state = project_state.clone()
  3864. operation.state_forwards(app_label, new_state)
  3865. self.assertEqual(
  3866. len(new_state.models[app_label, "pony"].options["constraints"]), 1
  3867. )
  3868. self.assertIndexNameNotExists(table_name, constraint_name)
  3869. # Add constraint.
  3870. with connection.schema_editor() as editor:
  3871. operation.database_forwards(app_label, editor, project_state, new_state)
  3872. Pony = new_state.apps.get_model(app_label, "Pony")
  3873. Pony.objects.create(weight=4.0)
  3874. if connection.features.supports_expression_indexes:
  3875. self.assertIndexNameExists(table_name, constraint_name)
  3876. with self.assertRaises(IntegrityError):
  3877. Pony.objects.create(weight=-4.0)
  3878. else:
  3879. self.assertIndexNameNotExists(table_name, constraint_name)
  3880. Pony.objects.create(weight=-4.0)
  3881. # Reversal.
  3882. with connection.schema_editor() as editor:
  3883. operation.database_backwards(app_label, editor, new_state, project_state)
  3884. self.assertIndexNameNotExists(table_name, constraint_name)
  3885. # Constraint doesn't work.
  3886. Pony.objects.create(weight=-4.0)
  3887. # Deconstruction.
  3888. definition = operation.deconstruct()
  3889. self.assertEqual(definition[0], "AddConstraint")
  3890. self.assertEqual(definition[1], [])
  3891. self.assertEqual(
  3892. definition[2],
  3893. {"model_name": "Pony", "constraint": constraint},
  3894. )
  3895. def test_remove_func_unique_constraint(self):
  3896. app_label = "test_rmfuncuc"
  3897. constraint_name = f"{app_label}_pony_abs_uq"
  3898. table_name = f"{app_label}_pony"
  3899. project_state = self.set_up_test_model(
  3900. app_label,
  3901. constraints=[
  3902. models.UniqueConstraint(Abs("weight"), name=constraint_name),
  3903. ],
  3904. )
  3905. self.assertTableExists(table_name)
  3906. if connection.features.supports_expression_indexes:
  3907. self.assertIndexNameExists(table_name, constraint_name)
  3908. operation = migrations.RemoveConstraint("Pony", constraint_name)
  3909. self.assertEqual(
  3910. operation.describe(),
  3911. "Remove constraint test_rmfuncuc_pony_abs_uq from model Pony",
  3912. )
  3913. self.assertEqual(
  3914. operation.migration_name_fragment,
  3915. "remove_pony_test_rmfuncuc_pony_abs_uq",
  3916. )
  3917. new_state = project_state.clone()
  3918. operation.state_forwards(app_label, new_state)
  3919. self.assertEqual(
  3920. len(new_state.models[app_label, "pony"].options["constraints"]), 0
  3921. )
  3922. Pony = new_state.apps.get_model(app_label, "Pony")
  3923. self.assertEqual(len(Pony._meta.constraints), 0)
  3924. # Remove constraint.
  3925. with connection.schema_editor() as editor:
  3926. operation.database_forwards(app_label, editor, project_state, new_state)
  3927. self.assertIndexNameNotExists(table_name, constraint_name)
  3928. # Constraint doesn't work.
  3929. Pony.objects.create(pink=1, weight=4.0)
  3930. Pony.objects.create(pink=1, weight=-4.0).delete()
  3931. # Reversal.
  3932. with connection.schema_editor() as editor:
  3933. operation.database_backwards(app_label, editor, new_state, project_state)
  3934. if connection.features.supports_expression_indexes:
  3935. self.assertIndexNameExists(table_name, constraint_name)
  3936. with self.assertRaises(IntegrityError):
  3937. Pony.objects.create(weight=-4.0)
  3938. else:
  3939. self.assertIndexNameNotExists(table_name, constraint_name)
  3940. Pony.objects.create(weight=-4.0)
  3941. # Deconstruction.
  3942. definition = operation.deconstruct()
  3943. self.assertEqual(definition[0], "RemoveConstraint")
  3944. self.assertEqual(definition[1], [])
  3945. self.assertEqual(definition[2], {"model_name": "Pony", "name": constraint_name})
  3946. def test_alter_model_options(self):
  3947. """
  3948. Tests the AlterModelOptions operation.
  3949. """
  3950. project_state = self.set_up_test_model("test_almoop")
  3951. # Test the state alteration (no DB alteration to test)
  3952. operation = migrations.AlterModelOptions(
  3953. "Pony", {"permissions": [("can_groom", "Can groom")]}
  3954. )
  3955. self.assertEqual(operation.describe(), "Change Meta options on Pony")
  3956. self.assertEqual(operation.migration_name_fragment, "alter_pony_options")
  3957. new_state = project_state.clone()
  3958. operation.state_forwards("test_almoop", new_state)
  3959. self.assertEqual(
  3960. len(
  3961. project_state.models["test_almoop", "pony"].options.get(
  3962. "permissions", []
  3963. )
  3964. ),
  3965. 0,
  3966. )
  3967. self.assertEqual(
  3968. len(new_state.models["test_almoop", "pony"].options.get("permissions", [])),
  3969. 1,
  3970. )
  3971. self.assertEqual(
  3972. new_state.models["test_almoop", "pony"].options["permissions"][0][0],
  3973. "can_groom",
  3974. )
  3975. # And deconstruction
  3976. definition = operation.deconstruct()
  3977. self.assertEqual(definition[0], "AlterModelOptions")
  3978. self.assertEqual(definition[1], [])
  3979. self.assertEqual(
  3980. definition[2],
  3981. {"name": "Pony", "options": {"permissions": [("can_groom", "Can groom")]}},
  3982. )
  3983. def test_alter_model_options_emptying(self):
  3984. """
  3985. The AlterModelOptions operation removes keys from the dict (#23121)
  3986. """
  3987. project_state = self.set_up_test_model("test_almoop", options=True)
  3988. # Test the state alteration (no DB alteration to test)
  3989. operation = migrations.AlterModelOptions("Pony", {})
  3990. self.assertEqual(operation.describe(), "Change Meta options on Pony")
  3991. new_state = project_state.clone()
  3992. operation.state_forwards("test_almoop", new_state)
  3993. self.assertEqual(
  3994. len(
  3995. project_state.models["test_almoop", "pony"].options.get(
  3996. "permissions", []
  3997. )
  3998. ),
  3999. 1,
  4000. )
  4001. self.assertEqual(
  4002. len(new_state.models["test_almoop", "pony"].options.get("permissions", [])),
  4003. 0,
  4004. )
  4005. # And deconstruction
  4006. definition = operation.deconstruct()
  4007. self.assertEqual(definition[0], "AlterModelOptions")
  4008. self.assertEqual(definition[1], [])
  4009. self.assertEqual(definition[2], {"name": "Pony", "options": {}})
  4010. def test_alter_order_with_respect_to(self):
  4011. """
  4012. Tests the AlterOrderWithRespectTo operation.
  4013. """
  4014. project_state = self.set_up_test_model("test_alorwrtto", related_model=True)
  4015. # Test the state alteration
  4016. operation = migrations.AlterOrderWithRespectTo("Rider", "pony")
  4017. self.assertEqual(
  4018. operation.describe(), "Set order_with_respect_to on Rider to pony"
  4019. )
  4020. self.assertEqual(
  4021. operation.migration_name_fragment,
  4022. "alter_rider_order_with_respect_to",
  4023. )
  4024. new_state = project_state.clone()
  4025. operation.state_forwards("test_alorwrtto", new_state)
  4026. self.assertIsNone(
  4027. project_state.models["test_alorwrtto", "rider"].options.get(
  4028. "order_with_respect_to", None
  4029. )
  4030. )
  4031. self.assertEqual(
  4032. new_state.models["test_alorwrtto", "rider"].options.get(
  4033. "order_with_respect_to", None
  4034. ),
  4035. "pony",
  4036. )
  4037. # Make sure there's no matching index
  4038. self.assertColumnNotExists("test_alorwrtto_rider", "_order")
  4039. # Create some rows before alteration
  4040. rendered_state = project_state.apps
  4041. pony = rendered_state.get_model("test_alorwrtto", "Pony").objects.create(
  4042. weight=50
  4043. )
  4044. rider1 = rendered_state.get_model("test_alorwrtto", "Rider").objects.create(
  4045. pony=pony
  4046. )
  4047. rider1.friend = rider1
  4048. rider1.save()
  4049. rider2 = rendered_state.get_model("test_alorwrtto", "Rider").objects.create(
  4050. pony=pony
  4051. )
  4052. rider2.friend = rider2
  4053. rider2.save()
  4054. # Test the database alteration
  4055. with connection.schema_editor() as editor:
  4056. operation.database_forwards(
  4057. "test_alorwrtto", editor, project_state, new_state
  4058. )
  4059. self.assertColumnExists("test_alorwrtto_rider", "_order")
  4060. # Check for correct value in rows
  4061. updated_riders = new_state.apps.get_model(
  4062. "test_alorwrtto", "Rider"
  4063. ).objects.all()
  4064. self.assertEqual(updated_riders[0]._order, 0)
  4065. self.assertEqual(updated_riders[1]._order, 0)
  4066. # And test reversal
  4067. with connection.schema_editor() as editor:
  4068. operation.database_backwards(
  4069. "test_alorwrtto", editor, new_state, project_state
  4070. )
  4071. self.assertColumnNotExists("test_alorwrtto_rider", "_order")
  4072. # And deconstruction
  4073. definition = operation.deconstruct()
  4074. self.assertEqual(definition[0], "AlterOrderWithRespectTo")
  4075. self.assertEqual(definition[1], [])
  4076. self.assertEqual(
  4077. definition[2], {"name": "Rider", "order_with_respect_to": "pony"}
  4078. )
  4079. def test_alter_model_managers(self):
  4080. """
  4081. The managers on a model are set.
  4082. """
  4083. project_state = self.set_up_test_model("test_almoma")
  4084. # Test the state alteration
  4085. operation = migrations.AlterModelManagers(
  4086. "Pony",
  4087. managers=[
  4088. ("food_qs", FoodQuerySet.as_manager()),
  4089. ("food_mgr", FoodManager("a", "b")),
  4090. ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)),
  4091. ],
  4092. )
  4093. self.assertEqual(operation.describe(), "Change managers on Pony")
  4094. self.assertEqual(operation.migration_name_fragment, "alter_pony_managers")
  4095. managers = project_state.models["test_almoma", "pony"].managers
  4096. self.assertEqual(managers, [])
  4097. new_state = project_state.clone()
  4098. operation.state_forwards("test_almoma", new_state)
  4099. self.assertIn(("test_almoma", "pony"), new_state.models)
  4100. managers = new_state.models["test_almoma", "pony"].managers
  4101. self.assertEqual(managers[0][0], "food_qs")
  4102. self.assertIsInstance(managers[0][1], models.Manager)
  4103. self.assertEqual(managers[1][0], "food_mgr")
  4104. self.assertIsInstance(managers[1][1], FoodManager)
  4105. self.assertEqual(managers[1][1].args, ("a", "b", 1, 2))
  4106. self.assertEqual(managers[2][0], "food_mgr_kwargs")
  4107. self.assertIsInstance(managers[2][1], FoodManager)
  4108. self.assertEqual(managers[2][1].args, ("x", "y", 3, 4))
  4109. rendered_state = new_state.apps
  4110. model = rendered_state.get_model("test_almoma", "pony")
  4111. self.assertIsInstance(model.food_qs, models.Manager)
  4112. self.assertIsInstance(model.food_mgr, FoodManager)
  4113. self.assertIsInstance(model.food_mgr_kwargs, FoodManager)
  4114. def test_alter_model_managers_emptying(self):
  4115. """
  4116. The managers on a model are set.
  4117. """
  4118. project_state = self.set_up_test_model("test_almomae", manager_model=True)
  4119. # Test the state alteration
  4120. operation = migrations.AlterModelManagers("Food", managers=[])
  4121. self.assertEqual(operation.describe(), "Change managers on Food")
  4122. self.assertIn(("test_almomae", "food"), project_state.models)
  4123. managers = project_state.models["test_almomae", "food"].managers
  4124. self.assertEqual(managers[0][0], "food_qs")
  4125. self.assertIsInstance(managers[0][1], models.Manager)
  4126. self.assertEqual(managers[1][0], "food_mgr")
  4127. self.assertIsInstance(managers[1][1], FoodManager)
  4128. self.assertEqual(managers[1][1].args, ("a", "b", 1, 2))
  4129. self.assertEqual(managers[2][0], "food_mgr_kwargs")
  4130. self.assertIsInstance(managers[2][1], FoodManager)
  4131. self.assertEqual(managers[2][1].args, ("x", "y", 3, 4))
  4132. new_state = project_state.clone()
  4133. operation.state_forwards("test_almomae", new_state)
  4134. managers = new_state.models["test_almomae", "food"].managers
  4135. self.assertEqual(managers, [])
  4136. def test_alter_fk(self):
  4137. """
  4138. Creating and then altering an FK works correctly
  4139. and deals with the pending SQL (#23091)
  4140. """
  4141. project_state = self.set_up_test_model("test_alfk")
  4142. # Test adding and then altering the FK in one go
  4143. create_operation = migrations.CreateModel(
  4144. name="Rider",
  4145. fields=[
  4146. ("id", models.AutoField(primary_key=True)),
  4147. ("pony", models.ForeignKey("Pony", models.CASCADE)),
  4148. ],
  4149. )
  4150. create_state = project_state.clone()
  4151. create_operation.state_forwards("test_alfk", create_state)
  4152. alter_operation = migrations.AlterField(
  4153. model_name="Rider",
  4154. name="pony",
  4155. field=models.ForeignKey("Pony", models.CASCADE, editable=False),
  4156. )
  4157. alter_state = create_state.clone()
  4158. alter_operation.state_forwards("test_alfk", alter_state)
  4159. with connection.schema_editor() as editor:
  4160. create_operation.database_forwards(
  4161. "test_alfk", editor, project_state, create_state
  4162. )
  4163. alter_operation.database_forwards(
  4164. "test_alfk", editor, create_state, alter_state
  4165. )
  4166. def test_alter_fk_non_fk(self):
  4167. """
  4168. Altering an FK to a non-FK works (#23244)
  4169. """
  4170. # Test the state alteration
  4171. operation = migrations.AlterField(
  4172. model_name="Rider",
  4173. name="pony",
  4174. field=models.FloatField(),
  4175. )
  4176. project_state, new_state = self.make_test_state(
  4177. "test_afknfk", operation, related_model=True
  4178. )
  4179. # Test the database alteration
  4180. self.assertColumnExists("test_afknfk_rider", "pony_id")
  4181. self.assertColumnNotExists("test_afknfk_rider", "pony")
  4182. with connection.schema_editor() as editor:
  4183. operation.database_forwards("test_afknfk", editor, project_state, new_state)
  4184. self.assertColumnExists("test_afknfk_rider", "pony")
  4185. self.assertColumnNotExists("test_afknfk_rider", "pony_id")
  4186. # And test reversal
  4187. with connection.schema_editor() as editor:
  4188. operation.database_backwards(
  4189. "test_afknfk", editor, new_state, project_state
  4190. )
  4191. self.assertColumnExists("test_afknfk_rider", "pony_id")
  4192. self.assertColumnNotExists("test_afknfk_rider", "pony")
  4193. def test_run_sql(self):
  4194. """
  4195. Tests the RunSQL operation.
  4196. """
  4197. project_state = self.set_up_test_model("test_runsql")
  4198. # Create the operation
  4199. operation = migrations.RunSQL(
  4200. # Use a multi-line string with a comment to test splitting on
  4201. # SQLite and MySQL respectively.
  4202. "CREATE TABLE i_love_ponies (id int, special_thing varchar(15));\n"
  4203. "INSERT INTO i_love_ponies (id, special_thing) "
  4204. "VALUES (1, 'i love ponies'); -- this is magic!\n"
  4205. "INSERT INTO i_love_ponies (id, special_thing) "
  4206. "VALUES (2, 'i love django');\n"
  4207. "UPDATE i_love_ponies SET special_thing = 'Ponies' "
  4208. "WHERE special_thing LIKE '%%ponies';"
  4209. "UPDATE i_love_ponies SET special_thing = 'Django' "
  4210. "WHERE special_thing LIKE '%django';",
  4211. # Run delete queries to test for parameter substitution failure
  4212. # reported in #23426
  4213. "DELETE FROM i_love_ponies WHERE special_thing LIKE '%Django%';"
  4214. "DELETE FROM i_love_ponies WHERE special_thing LIKE '%%Ponies%%';"
  4215. "DROP TABLE i_love_ponies",
  4216. state_operations=[
  4217. migrations.CreateModel(
  4218. "SomethingElse", [("id", models.AutoField(primary_key=True))]
  4219. )
  4220. ],
  4221. )
  4222. self.assertEqual(operation.describe(), "Raw SQL operation")
  4223. # Test the state alteration
  4224. new_state = project_state.clone()
  4225. operation.state_forwards("test_runsql", new_state)
  4226. self.assertEqual(
  4227. len(new_state.models["test_runsql", "somethingelse"].fields), 1
  4228. )
  4229. # Make sure there's no table
  4230. self.assertTableNotExists("i_love_ponies")
  4231. # Test SQL collection
  4232. with connection.schema_editor(collect_sql=True) as editor:
  4233. operation.database_forwards("test_runsql", editor, project_state, new_state)
  4234. self.assertIn("LIKE '%%ponies';", "\n".join(editor.collected_sql))
  4235. operation.database_backwards(
  4236. "test_runsql", editor, project_state, new_state
  4237. )
  4238. self.assertIn("LIKE '%%Ponies%%';", "\n".join(editor.collected_sql))
  4239. # Test the database alteration
  4240. with connection.schema_editor() as editor:
  4241. operation.database_forwards("test_runsql", editor, project_state, new_state)
  4242. self.assertTableExists("i_love_ponies")
  4243. # Make sure all the SQL was processed
  4244. with connection.cursor() as cursor:
  4245. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  4246. self.assertEqual(cursor.fetchall()[0][0], 2)
  4247. cursor.execute(
  4248. "SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Django'"
  4249. )
  4250. self.assertEqual(cursor.fetchall()[0][0], 1)
  4251. cursor.execute(
  4252. "SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Ponies'"
  4253. )
  4254. self.assertEqual(cursor.fetchall()[0][0], 1)
  4255. # And test reversal
  4256. self.assertTrue(operation.reversible)
  4257. with connection.schema_editor() as editor:
  4258. operation.database_backwards(
  4259. "test_runsql", editor, new_state, project_state
  4260. )
  4261. self.assertTableNotExists("i_love_ponies")
  4262. # And deconstruction
  4263. definition = operation.deconstruct()
  4264. self.assertEqual(definition[0], "RunSQL")
  4265. self.assertEqual(definition[1], [])
  4266. self.assertEqual(
  4267. sorted(definition[2]), ["reverse_sql", "sql", "state_operations"]
  4268. )
  4269. # And elidable reduction
  4270. self.assertIs(False, operation.reduce(operation, []))
  4271. elidable_operation = migrations.RunSQL("SELECT 1 FROM void;", elidable=True)
  4272. self.assertEqual(elidable_operation.reduce(operation, []), [operation])
  4273. def test_run_sql_params(self):
  4274. """
  4275. #23426 - RunSQL should accept parameters.
  4276. """
  4277. project_state = self.set_up_test_model("test_runsql")
  4278. # Create the operation
  4279. operation = migrations.RunSQL(
  4280. ["CREATE TABLE i_love_ponies (id int, special_thing varchar(15));"],
  4281. ["DROP TABLE i_love_ponies"],
  4282. )
  4283. param_operation = migrations.RunSQL(
  4284. # forwards
  4285. (
  4286. "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 'Django');",
  4287. [
  4288. "INSERT INTO i_love_ponies (id, special_thing) VALUES (2, %s);",
  4289. ["Ponies"],
  4290. ],
  4291. (
  4292. "INSERT INTO i_love_ponies (id, special_thing) VALUES (%s, %s);",
  4293. (
  4294. 3,
  4295. "Python",
  4296. ),
  4297. ),
  4298. ),
  4299. # backwards
  4300. [
  4301. "DELETE FROM i_love_ponies WHERE special_thing = 'Django';",
  4302. ["DELETE FROM i_love_ponies WHERE special_thing = 'Ponies';", None],
  4303. (
  4304. "DELETE FROM i_love_ponies WHERE id = %s OR special_thing = %s;",
  4305. [3, "Python"],
  4306. ),
  4307. ],
  4308. )
  4309. # Make sure there's no table
  4310. self.assertTableNotExists("i_love_ponies")
  4311. new_state = project_state.clone()
  4312. # Test the database alteration
  4313. with connection.schema_editor() as editor:
  4314. operation.database_forwards("test_runsql", editor, project_state, new_state)
  4315. # Test parameter passing
  4316. with connection.schema_editor() as editor:
  4317. param_operation.database_forwards(
  4318. "test_runsql", editor, project_state, new_state
  4319. )
  4320. # Make sure all the SQL was processed
  4321. with connection.cursor() as cursor:
  4322. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  4323. self.assertEqual(cursor.fetchall()[0][0], 3)
  4324. with connection.schema_editor() as editor:
  4325. param_operation.database_backwards(
  4326. "test_runsql", editor, new_state, project_state
  4327. )
  4328. with connection.cursor() as cursor:
  4329. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  4330. self.assertEqual(cursor.fetchall()[0][0], 0)
  4331. # And test reversal
  4332. with connection.schema_editor() as editor:
  4333. operation.database_backwards(
  4334. "test_runsql", editor, new_state, project_state
  4335. )
  4336. self.assertTableNotExists("i_love_ponies")
  4337. def test_run_sql_params_invalid(self):
  4338. """
  4339. #23426 - RunSQL should fail when a list of statements with an incorrect
  4340. number of tuples is given.
  4341. """
  4342. project_state = self.set_up_test_model("test_runsql")
  4343. new_state = project_state.clone()
  4344. operation = migrations.RunSQL(
  4345. # forwards
  4346. [["INSERT INTO foo (bar) VALUES ('buz');"]],
  4347. # backwards
  4348. (("DELETE FROM foo WHERE bar = 'buz';", "invalid", "parameter count"),),
  4349. )
  4350. with connection.schema_editor() as editor:
  4351. with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 1"):
  4352. operation.database_forwards(
  4353. "test_runsql", editor, project_state, new_state
  4354. )
  4355. with connection.schema_editor() as editor:
  4356. with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 3"):
  4357. operation.database_backwards(
  4358. "test_runsql", editor, new_state, project_state
  4359. )
  4360. def test_run_sql_noop(self):
  4361. """
  4362. #24098 - Tests no-op RunSQL operations.
  4363. """
  4364. operation = migrations.RunSQL(migrations.RunSQL.noop, migrations.RunSQL.noop)
  4365. with connection.schema_editor() as editor:
  4366. operation.database_forwards("test_runsql", editor, None, None)
  4367. operation.database_backwards("test_runsql", editor, None, None)
  4368. def test_run_sql_add_missing_semicolon_on_collect_sql(self):
  4369. project_state = self.set_up_test_model("test_runsql")
  4370. new_state = project_state.clone()
  4371. tests = [
  4372. "INSERT INTO test_runsql_pony (pink, weight) VALUES (1, 1);\n",
  4373. "INSERT INTO test_runsql_pony (pink, weight) VALUES (1, 1)\n",
  4374. ]
  4375. for sql in tests:
  4376. with self.subTest(sql=sql):
  4377. operation = migrations.RunSQL(sql, migrations.RunPython.noop)
  4378. with connection.schema_editor(collect_sql=True) as editor:
  4379. operation.database_forwards(
  4380. "test_runsql", editor, project_state, new_state
  4381. )
  4382. collected_sql = "\n".join(editor.collected_sql)
  4383. self.assertEqual(collected_sql.count(";"), 1)
  4384. def test_run_python(self):
  4385. """
  4386. Tests the RunPython operation
  4387. """
  4388. project_state = self.set_up_test_model("test_runpython", mti_model=True)
  4389. # Create the operation
  4390. def inner_method(models, schema_editor):
  4391. Pony = models.get_model("test_runpython", "Pony")
  4392. Pony.objects.create(pink=1, weight=3.55)
  4393. Pony.objects.create(weight=5)
  4394. def inner_method_reverse(models, schema_editor):
  4395. Pony = models.get_model("test_runpython", "Pony")
  4396. Pony.objects.filter(pink=1, weight=3.55).delete()
  4397. Pony.objects.filter(weight=5).delete()
  4398. operation = migrations.RunPython(
  4399. inner_method, reverse_code=inner_method_reverse
  4400. )
  4401. self.assertEqual(operation.describe(), "Raw Python operation")
  4402. # Test the state alteration does nothing
  4403. new_state = project_state.clone()
  4404. operation.state_forwards("test_runpython", new_state)
  4405. self.assertEqual(new_state, project_state)
  4406. # Test the database alteration
  4407. self.assertEqual(
  4408. project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0
  4409. )
  4410. with connection.schema_editor() as editor:
  4411. operation.database_forwards(
  4412. "test_runpython", editor, project_state, new_state
  4413. )
  4414. self.assertEqual(
  4415. project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2
  4416. )
  4417. # Now test reversal
  4418. self.assertTrue(operation.reversible)
  4419. with connection.schema_editor() as editor:
  4420. operation.database_backwards(
  4421. "test_runpython", editor, project_state, new_state
  4422. )
  4423. self.assertEqual(
  4424. project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0
  4425. )
  4426. # Now test we can't use a string
  4427. with self.assertRaisesMessage(
  4428. ValueError, "RunPython must be supplied with a callable"
  4429. ):
  4430. migrations.RunPython("print 'ahahaha'")
  4431. # And deconstruction
  4432. definition = operation.deconstruct()
  4433. self.assertEqual(definition[0], "RunPython")
  4434. self.assertEqual(definition[1], [])
  4435. self.assertEqual(sorted(definition[2]), ["code", "reverse_code"])
  4436. # Also test reversal fails, with an operation identical to above but
  4437. # without reverse_code set.
  4438. no_reverse_operation = migrations.RunPython(inner_method)
  4439. self.assertFalse(no_reverse_operation.reversible)
  4440. with connection.schema_editor() as editor:
  4441. no_reverse_operation.database_forwards(
  4442. "test_runpython", editor, project_state, new_state
  4443. )
  4444. with self.assertRaises(NotImplementedError):
  4445. no_reverse_operation.database_backwards(
  4446. "test_runpython", editor, new_state, project_state
  4447. )
  4448. self.assertEqual(
  4449. project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2
  4450. )
  4451. def create_ponies(models, schema_editor):
  4452. Pony = models.get_model("test_runpython", "Pony")
  4453. pony1 = Pony.objects.create(pink=1, weight=3.55)
  4454. self.assertIsNot(pony1.pk, None)
  4455. pony2 = Pony.objects.create(weight=5)
  4456. self.assertIsNot(pony2.pk, None)
  4457. self.assertNotEqual(pony1.pk, pony2.pk)
  4458. operation = migrations.RunPython(create_ponies)
  4459. with connection.schema_editor() as editor:
  4460. operation.database_forwards(
  4461. "test_runpython", editor, project_state, new_state
  4462. )
  4463. self.assertEqual(
  4464. project_state.apps.get_model("test_runpython", "Pony").objects.count(), 4
  4465. )
  4466. # And deconstruction
  4467. definition = operation.deconstruct()
  4468. self.assertEqual(definition[0], "RunPython")
  4469. self.assertEqual(definition[1], [])
  4470. self.assertEqual(sorted(definition[2]), ["code"])
  4471. def create_shetlandponies(models, schema_editor):
  4472. ShetlandPony = models.get_model("test_runpython", "ShetlandPony")
  4473. pony1 = ShetlandPony.objects.create(weight=4.0)
  4474. self.assertIsNot(pony1.pk, None)
  4475. pony2 = ShetlandPony.objects.create(weight=5.0)
  4476. self.assertIsNot(pony2.pk, None)
  4477. self.assertNotEqual(pony1.pk, pony2.pk)
  4478. operation = migrations.RunPython(create_shetlandponies)
  4479. with connection.schema_editor() as editor:
  4480. operation.database_forwards(
  4481. "test_runpython", editor, project_state, new_state
  4482. )
  4483. self.assertEqual(
  4484. project_state.apps.get_model("test_runpython", "Pony").objects.count(), 6
  4485. )
  4486. self.assertEqual(
  4487. project_state.apps.get_model(
  4488. "test_runpython", "ShetlandPony"
  4489. ).objects.count(),
  4490. 2,
  4491. )
  4492. # And elidable reduction
  4493. self.assertIs(False, operation.reduce(operation, []))
  4494. elidable_operation = migrations.RunPython(inner_method, elidable=True)
  4495. self.assertEqual(elidable_operation.reduce(operation, []), [operation])
  4496. def test_run_python_atomic(self):
  4497. """
  4498. Tests the RunPython operation correctly handles the "atomic" keyword
  4499. """
  4500. project_state = self.set_up_test_model("test_runpythonatomic", mti_model=True)
  4501. def inner_method(models, schema_editor):
  4502. Pony = models.get_model("test_runpythonatomic", "Pony")
  4503. Pony.objects.create(pink=1, weight=3.55)
  4504. raise ValueError("Adrian hates ponies.")
  4505. # Verify atomicity when applying.
  4506. atomic_migration = Migration("test", "test_runpythonatomic")
  4507. atomic_migration.operations = [
  4508. migrations.RunPython(inner_method, reverse_code=inner_method)
  4509. ]
  4510. non_atomic_migration = Migration("test", "test_runpythonatomic")
  4511. non_atomic_migration.operations = [
  4512. migrations.RunPython(inner_method, reverse_code=inner_method, atomic=False)
  4513. ]
  4514. # If we're a fully-transactional database, both versions should rollback
  4515. if connection.features.can_rollback_ddl:
  4516. self.assertEqual(
  4517. project_state.apps.get_model(
  4518. "test_runpythonatomic", "Pony"
  4519. ).objects.count(),
  4520. 0,
  4521. )
  4522. with self.assertRaises(ValueError):
  4523. with connection.schema_editor() as editor:
  4524. atomic_migration.apply(project_state, editor)
  4525. self.assertEqual(
  4526. project_state.apps.get_model(
  4527. "test_runpythonatomic", "Pony"
  4528. ).objects.count(),
  4529. 0,
  4530. )
  4531. with self.assertRaises(ValueError):
  4532. with connection.schema_editor() as editor:
  4533. non_atomic_migration.apply(project_state, editor)
  4534. self.assertEqual(
  4535. project_state.apps.get_model(
  4536. "test_runpythonatomic", "Pony"
  4537. ).objects.count(),
  4538. 0,
  4539. )
  4540. # Otherwise, the non-atomic operation should leave a row there
  4541. else:
  4542. self.assertEqual(
  4543. project_state.apps.get_model(
  4544. "test_runpythonatomic", "Pony"
  4545. ).objects.count(),
  4546. 0,
  4547. )
  4548. with self.assertRaises(ValueError):
  4549. with connection.schema_editor() as editor:
  4550. atomic_migration.apply(project_state, editor)
  4551. self.assertEqual(
  4552. project_state.apps.get_model(
  4553. "test_runpythonatomic", "Pony"
  4554. ).objects.count(),
  4555. 0,
  4556. )
  4557. with self.assertRaises(ValueError):
  4558. with connection.schema_editor() as editor:
  4559. non_atomic_migration.apply(project_state, editor)
  4560. self.assertEqual(
  4561. project_state.apps.get_model(
  4562. "test_runpythonatomic", "Pony"
  4563. ).objects.count(),
  4564. 1,
  4565. )
  4566. # Reset object count to zero and verify atomicity when unapplying.
  4567. project_state.apps.get_model(
  4568. "test_runpythonatomic", "Pony"
  4569. ).objects.all().delete()
  4570. # On a fully-transactional database, both versions rollback.
  4571. if connection.features.can_rollback_ddl:
  4572. self.assertEqual(
  4573. project_state.apps.get_model(
  4574. "test_runpythonatomic", "Pony"
  4575. ).objects.count(),
  4576. 0,
  4577. )
  4578. with self.assertRaises(ValueError):
  4579. with connection.schema_editor() as editor:
  4580. atomic_migration.unapply(project_state, editor)
  4581. self.assertEqual(
  4582. project_state.apps.get_model(
  4583. "test_runpythonatomic", "Pony"
  4584. ).objects.count(),
  4585. 0,
  4586. )
  4587. with self.assertRaises(ValueError):
  4588. with connection.schema_editor() as editor:
  4589. non_atomic_migration.unapply(project_state, editor)
  4590. self.assertEqual(
  4591. project_state.apps.get_model(
  4592. "test_runpythonatomic", "Pony"
  4593. ).objects.count(),
  4594. 0,
  4595. )
  4596. # Otherwise, the non-atomic operation leaves a row there.
  4597. else:
  4598. self.assertEqual(
  4599. project_state.apps.get_model(
  4600. "test_runpythonatomic", "Pony"
  4601. ).objects.count(),
  4602. 0,
  4603. )
  4604. with self.assertRaises(ValueError):
  4605. with connection.schema_editor() as editor:
  4606. atomic_migration.unapply(project_state, editor)
  4607. self.assertEqual(
  4608. project_state.apps.get_model(
  4609. "test_runpythonatomic", "Pony"
  4610. ).objects.count(),
  4611. 0,
  4612. )
  4613. with self.assertRaises(ValueError):
  4614. with connection.schema_editor() as editor:
  4615. non_atomic_migration.unapply(project_state, editor)
  4616. self.assertEqual(
  4617. project_state.apps.get_model(
  4618. "test_runpythonatomic", "Pony"
  4619. ).objects.count(),
  4620. 1,
  4621. )
  4622. # Verify deconstruction.
  4623. definition = non_atomic_migration.operations[0].deconstruct()
  4624. self.assertEqual(definition[0], "RunPython")
  4625. self.assertEqual(definition[1], [])
  4626. self.assertEqual(sorted(definition[2]), ["atomic", "code", "reverse_code"])
  4627. def test_run_python_related_assignment(self):
  4628. """
  4629. #24282 - Model changes to a FK reverse side update the model
  4630. on the FK side as well.
  4631. """
  4632. def inner_method(models, schema_editor):
  4633. Author = models.get_model("test_authors", "Author")
  4634. Book = models.get_model("test_books", "Book")
  4635. author = Author.objects.create(name="Hemingway")
  4636. Book.objects.create(title="Old Man and The Sea", author=author)
  4637. create_author = migrations.CreateModel(
  4638. "Author",
  4639. [
  4640. ("id", models.AutoField(primary_key=True)),
  4641. ("name", models.CharField(max_length=100)),
  4642. ],
  4643. options={},
  4644. )
  4645. create_book = migrations.CreateModel(
  4646. "Book",
  4647. [
  4648. ("id", models.AutoField(primary_key=True)),
  4649. ("title", models.CharField(max_length=100)),
  4650. ("author", models.ForeignKey("test_authors.Author", models.CASCADE)),
  4651. ],
  4652. options={},
  4653. )
  4654. add_hometown = migrations.AddField(
  4655. "Author",
  4656. "hometown",
  4657. models.CharField(max_length=100),
  4658. )
  4659. create_old_man = migrations.RunPython(inner_method, inner_method)
  4660. project_state = ProjectState()
  4661. new_state = project_state.clone()
  4662. with connection.schema_editor() as editor:
  4663. create_author.state_forwards("test_authors", new_state)
  4664. create_author.database_forwards(
  4665. "test_authors", editor, project_state, new_state
  4666. )
  4667. project_state = new_state
  4668. new_state = new_state.clone()
  4669. with connection.schema_editor() as editor:
  4670. create_book.state_forwards("test_books", new_state)
  4671. create_book.database_forwards(
  4672. "test_books", editor, project_state, new_state
  4673. )
  4674. project_state = new_state
  4675. new_state = new_state.clone()
  4676. with connection.schema_editor() as editor:
  4677. add_hometown.state_forwards("test_authors", new_state)
  4678. add_hometown.database_forwards(
  4679. "test_authors", editor, project_state, new_state
  4680. )
  4681. project_state = new_state
  4682. new_state = new_state.clone()
  4683. with connection.schema_editor() as editor:
  4684. create_old_man.state_forwards("test_books", new_state)
  4685. create_old_man.database_forwards(
  4686. "test_books", editor, project_state, new_state
  4687. )
  4688. def test_model_with_bigautofield(self):
  4689. """
  4690. A model with BigAutoField can be created.
  4691. """
  4692. def create_data(models, schema_editor):
  4693. Author = models.get_model("test_author", "Author")
  4694. Book = models.get_model("test_book", "Book")
  4695. author1 = Author.objects.create(name="Hemingway")
  4696. Book.objects.create(title="Old Man and The Sea", author=author1)
  4697. Book.objects.create(id=2**33, title="A farewell to arms", author=author1)
  4698. author2 = Author.objects.create(id=2**33, name="Remarque")
  4699. Book.objects.create(title="All quiet on the western front", author=author2)
  4700. Book.objects.create(title="Arc de Triomphe", author=author2)
  4701. create_author = migrations.CreateModel(
  4702. "Author",
  4703. [
  4704. ("id", models.BigAutoField(primary_key=True)),
  4705. ("name", models.CharField(max_length=100)),
  4706. ],
  4707. options={},
  4708. )
  4709. create_book = migrations.CreateModel(
  4710. "Book",
  4711. [
  4712. ("id", models.BigAutoField(primary_key=True)),
  4713. ("title", models.CharField(max_length=100)),
  4714. (
  4715. "author",
  4716. models.ForeignKey(
  4717. to="test_author.Author", on_delete=models.CASCADE
  4718. ),
  4719. ),
  4720. ],
  4721. options={},
  4722. )
  4723. fill_data = migrations.RunPython(create_data)
  4724. project_state = ProjectState()
  4725. new_state = project_state.clone()
  4726. with connection.schema_editor() as editor:
  4727. create_author.state_forwards("test_author", new_state)
  4728. create_author.database_forwards(
  4729. "test_author", editor, project_state, new_state
  4730. )
  4731. project_state = new_state
  4732. new_state = new_state.clone()
  4733. with connection.schema_editor() as editor:
  4734. create_book.state_forwards("test_book", new_state)
  4735. create_book.database_forwards("test_book", editor, project_state, new_state)
  4736. project_state = new_state
  4737. new_state = new_state.clone()
  4738. with connection.schema_editor() as editor:
  4739. fill_data.state_forwards("fill_data", new_state)
  4740. fill_data.database_forwards("fill_data", editor, project_state, new_state)
  4741. def _test_autofield_foreignfield_growth(
  4742. self, source_field, target_field, target_value
  4743. ):
  4744. """
  4745. A field may be migrated in the following ways:
  4746. - AutoField to BigAutoField
  4747. - SmallAutoField to AutoField
  4748. - SmallAutoField to BigAutoField
  4749. """
  4750. def create_initial_data(models, schema_editor):
  4751. Article = models.get_model("test_article", "Article")
  4752. Blog = models.get_model("test_blog", "Blog")
  4753. blog = Blog.objects.create(name="web development done right")
  4754. Article.objects.create(name="Frameworks", blog=blog)
  4755. Article.objects.create(name="Programming Languages", blog=blog)
  4756. def create_big_data(models, schema_editor):
  4757. Article = models.get_model("test_article", "Article")
  4758. Blog = models.get_model("test_blog", "Blog")
  4759. blog2 = Blog.objects.create(name="Frameworks", id=target_value)
  4760. Article.objects.create(name="Django", blog=blog2)
  4761. Article.objects.create(id=target_value, name="Django2", blog=blog2)
  4762. create_blog = migrations.CreateModel(
  4763. "Blog",
  4764. [
  4765. ("id", source_field(primary_key=True)),
  4766. ("name", models.CharField(max_length=100)),
  4767. ],
  4768. options={},
  4769. )
  4770. create_article = migrations.CreateModel(
  4771. "Article",
  4772. [
  4773. ("id", source_field(primary_key=True)),
  4774. (
  4775. "blog",
  4776. models.ForeignKey(to="test_blog.Blog", on_delete=models.CASCADE),
  4777. ),
  4778. ("name", models.CharField(max_length=100)),
  4779. ("data", models.TextField(default="")),
  4780. ],
  4781. options={},
  4782. )
  4783. fill_initial_data = migrations.RunPython(
  4784. create_initial_data, create_initial_data
  4785. )
  4786. fill_big_data = migrations.RunPython(create_big_data, create_big_data)
  4787. grow_article_id = migrations.AlterField(
  4788. "Article", "id", target_field(primary_key=True)
  4789. )
  4790. grow_blog_id = migrations.AlterField(
  4791. "Blog", "id", target_field(primary_key=True)
  4792. )
  4793. project_state = ProjectState()
  4794. new_state = project_state.clone()
  4795. with connection.schema_editor() as editor:
  4796. create_blog.state_forwards("test_blog", new_state)
  4797. create_blog.database_forwards("test_blog", editor, project_state, new_state)
  4798. project_state = new_state
  4799. new_state = new_state.clone()
  4800. with connection.schema_editor() as editor:
  4801. create_article.state_forwards("test_article", new_state)
  4802. create_article.database_forwards(
  4803. "test_article", editor, project_state, new_state
  4804. )
  4805. project_state = new_state
  4806. new_state = new_state.clone()
  4807. with connection.schema_editor() as editor:
  4808. fill_initial_data.state_forwards("fill_initial_data", new_state)
  4809. fill_initial_data.database_forwards(
  4810. "fill_initial_data", editor, project_state, new_state
  4811. )
  4812. project_state = new_state
  4813. new_state = new_state.clone()
  4814. with connection.schema_editor() as editor:
  4815. grow_article_id.state_forwards("test_article", new_state)
  4816. grow_article_id.database_forwards(
  4817. "test_article", editor, project_state, new_state
  4818. )
  4819. state = new_state.clone()
  4820. article = state.apps.get_model("test_article.Article")
  4821. self.assertIsInstance(article._meta.pk, target_field)
  4822. project_state = new_state
  4823. new_state = new_state.clone()
  4824. with connection.schema_editor() as editor:
  4825. grow_blog_id.state_forwards("test_blog", new_state)
  4826. grow_blog_id.database_forwards(
  4827. "test_blog", editor, project_state, new_state
  4828. )
  4829. state = new_state.clone()
  4830. blog = state.apps.get_model("test_blog.Blog")
  4831. self.assertIsInstance(blog._meta.pk, target_field)
  4832. project_state = new_state
  4833. new_state = new_state.clone()
  4834. with connection.schema_editor() as editor:
  4835. fill_big_data.state_forwards("fill_big_data", new_state)
  4836. fill_big_data.database_forwards(
  4837. "fill_big_data", editor, project_state, new_state
  4838. )
  4839. def test_autofield__bigautofield_foreignfield_growth(self):
  4840. """A field may be migrated from AutoField to BigAutoField."""
  4841. self._test_autofield_foreignfield_growth(
  4842. models.AutoField,
  4843. models.BigAutoField,
  4844. 2**33,
  4845. )
  4846. def test_smallfield_autofield_foreignfield_growth(self):
  4847. """A field may be migrated from SmallAutoField to AutoField."""
  4848. self._test_autofield_foreignfield_growth(
  4849. models.SmallAutoField,
  4850. models.AutoField,
  4851. 2**22,
  4852. )
  4853. def test_smallfield_bigautofield_foreignfield_growth(self):
  4854. """A field may be migrated from SmallAutoField to BigAutoField."""
  4855. self._test_autofield_foreignfield_growth(
  4856. models.SmallAutoField,
  4857. models.BigAutoField,
  4858. 2**33,
  4859. )
  4860. def test_run_python_noop(self):
  4861. """
  4862. #24098 - Tests no-op RunPython operations.
  4863. """
  4864. project_state = ProjectState()
  4865. new_state = project_state.clone()
  4866. operation = migrations.RunPython(
  4867. migrations.RunPython.noop, migrations.RunPython.noop
  4868. )
  4869. with connection.schema_editor() as editor:
  4870. operation.database_forwards(
  4871. "test_runpython", editor, project_state, new_state
  4872. )
  4873. operation.database_backwards(
  4874. "test_runpython", editor, new_state, project_state
  4875. )
  4876. def test_separate_database_and_state(self):
  4877. """
  4878. Tests the SeparateDatabaseAndState operation.
  4879. """
  4880. project_state = self.set_up_test_model("test_separatedatabaseandstate")
  4881. # Create the operation
  4882. database_operation = migrations.RunSQL(
  4883. "CREATE TABLE i_love_ponies (id int, special_thing int);",
  4884. "DROP TABLE i_love_ponies;",
  4885. )
  4886. state_operation = migrations.CreateModel(
  4887. "SomethingElse", [("id", models.AutoField(primary_key=True))]
  4888. )
  4889. operation = migrations.SeparateDatabaseAndState(
  4890. state_operations=[state_operation], database_operations=[database_operation]
  4891. )
  4892. self.assertEqual(
  4893. operation.describe(), "Custom state/database change combination"
  4894. )
  4895. # Test the state alteration
  4896. new_state = project_state.clone()
  4897. operation.state_forwards("test_separatedatabaseandstate", new_state)
  4898. self.assertEqual(
  4899. len(
  4900. new_state.models[
  4901. "test_separatedatabaseandstate", "somethingelse"
  4902. ].fields
  4903. ),
  4904. 1,
  4905. )
  4906. # Make sure there's no table
  4907. self.assertTableNotExists("i_love_ponies")
  4908. # Test the database alteration
  4909. with connection.schema_editor() as editor:
  4910. operation.database_forwards(
  4911. "test_separatedatabaseandstate", editor, project_state, new_state
  4912. )
  4913. self.assertTableExists("i_love_ponies")
  4914. # And test reversal
  4915. self.assertTrue(operation.reversible)
  4916. with connection.schema_editor() as editor:
  4917. operation.database_backwards(
  4918. "test_separatedatabaseandstate", editor, new_state, project_state
  4919. )
  4920. self.assertTableNotExists("i_love_ponies")
  4921. # And deconstruction
  4922. definition = operation.deconstruct()
  4923. self.assertEqual(definition[0], "SeparateDatabaseAndState")
  4924. self.assertEqual(definition[1], [])
  4925. self.assertEqual(
  4926. sorted(definition[2]), ["database_operations", "state_operations"]
  4927. )
  4928. def test_separate_database_and_state2(self):
  4929. """
  4930. A complex SeparateDatabaseAndState operation: Multiple operations both
  4931. for state and database. Verify the state dependencies within each list
  4932. and that state ops don't affect the database.
  4933. """
  4934. app_label = "test_separatedatabaseandstate2"
  4935. project_state = self.set_up_test_model(app_label)
  4936. # Create the operation
  4937. database_operations = [
  4938. migrations.CreateModel(
  4939. "ILovePonies",
  4940. [("id", models.AutoField(primary_key=True))],
  4941. options={"db_table": "iloveponies"},
  4942. ),
  4943. migrations.CreateModel(
  4944. "ILoveMorePonies",
  4945. # We use IntegerField and not AutoField because
  4946. # the model is going to be deleted immediately
  4947. # and with an AutoField this fails on Oracle
  4948. [("id", models.IntegerField(primary_key=True))],
  4949. options={"db_table": "ilovemoreponies"},
  4950. ),
  4951. migrations.DeleteModel("ILoveMorePonies"),
  4952. migrations.CreateModel(
  4953. "ILoveEvenMorePonies",
  4954. [("id", models.AutoField(primary_key=True))],
  4955. options={"db_table": "iloveevenmoreponies"},
  4956. ),
  4957. ]
  4958. state_operations = [
  4959. migrations.CreateModel(
  4960. "SomethingElse",
  4961. [("id", models.AutoField(primary_key=True))],
  4962. options={"db_table": "somethingelse"},
  4963. ),
  4964. migrations.DeleteModel("SomethingElse"),
  4965. migrations.CreateModel(
  4966. "SomethingCompletelyDifferent",
  4967. [("id", models.AutoField(primary_key=True))],
  4968. options={"db_table": "somethingcompletelydifferent"},
  4969. ),
  4970. ]
  4971. operation = migrations.SeparateDatabaseAndState(
  4972. state_operations=state_operations,
  4973. database_operations=database_operations,
  4974. )
  4975. # Test the state alteration
  4976. new_state = project_state.clone()
  4977. operation.state_forwards(app_label, new_state)
  4978. def assertModelsAndTables(after_db):
  4979. # Tables and models exist, or don't, as they should:
  4980. self.assertNotIn((app_label, "somethingelse"), new_state.models)
  4981. self.assertEqual(
  4982. len(new_state.models[app_label, "somethingcompletelydifferent"].fields),
  4983. 1,
  4984. )
  4985. self.assertNotIn((app_label, "iloveponiesonies"), new_state.models)
  4986. self.assertNotIn((app_label, "ilovemoreponies"), new_state.models)
  4987. self.assertNotIn((app_label, "iloveevenmoreponies"), new_state.models)
  4988. self.assertTableNotExists("somethingelse")
  4989. self.assertTableNotExists("somethingcompletelydifferent")
  4990. self.assertTableNotExists("ilovemoreponies")
  4991. if after_db:
  4992. self.assertTableExists("iloveponies")
  4993. self.assertTableExists("iloveevenmoreponies")
  4994. else:
  4995. self.assertTableNotExists("iloveponies")
  4996. self.assertTableNotExists("iloveevenmoreponies")
  4997. assertModelsAndTables(after_db=False)
  4998. # Test the database alteration
  4999. with connection.schema_editor() as editor:
  5000. operation.database_forwards(app_label, editor, project_state, new_state)
  5001. assertModelsAndTables(after_db=True)
  5002. # And test reversal
  5003. self.assertTrue(operation.reversible)
  5004. with connection.schema_editor() as editor:
  5005. operation.database_backwards(app_label, editor, new_state, project_state)
  5006. assertModelsAndTables(after_db=False)
  5007. class SwappableOperationTests(OperationTestBase):
  5008. """
  5009. Key operations ignore swappable models
  5010. (we don't want to replicate all of them here, as the functionality
  5011. is in a common base class anyway)
  5012. """
  5013. available_apps = ["migrations"]
  5014. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  5015. def test_create_ignore_swapped(self):
  5016. """
  5017. The CreateTable operation ignores swapped models.
  5018. """
  5019. operation = migrations.CreateModel(
  5020. "Pony",
  5021. [
  5022. ("id", models.AutoField(primary_key=True)),
  5023. ("pink", models.IntegerField(default=1)),
  5024. ],
  5025. options={
  5026. "swappable": "TEST_SWAP_MODEL",
  5027. },
  5028. )
  5029. # Test the state alteration (it should still be there!)
  5030. project_state = ProjectState()
  5031. new_state = project_state.clone()
  5032. operation.state_forwards("test_crigsw", new_state)
  5033. self.assertEqual(new_state.models["test_crigsw", "pony"].name, "Pony")
  5034. self.assertEqual(len(new_state.models["test_crigsw", "pony"].fields), 2)
  5035. # Test the database alteration
  5036. self.assertTableNotExists("test_crigsw_pony")
  5037. with connection.schema_editor() as editor:
  5038. operation.database_forwards("test_crigsw", editor, project_state, new_state)
  5039. self.assertTableNotExists("test_crigsw_pony")
  5040. # And test reversal
  5041. with connection.schema_editor() as editor:
  5042. operation.database_backwards(
  5043. "test_crigsw", editor, new_state, project_state
  5044. )
  5045. self.assertTableNotExists("test_crigsw_pony")
  5046. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  5047. def test_delete_ignore_swapped(self):
  5048. """
  5049. Tests the DeleteModel operation ignores swapped models.
  5050. """
  5051. operation = migrations.DeleteModel("Pony")
  5052. project_state, new_state = self.make_test_state("test_dligsw", operation)
  5053. # Test the database alteration
  5054. self.assertTableNotExists("test_dligsw_pony")
  5055. with connection.schema_editor() as editor:
  5056. operation.database_forwards("test_dligsw", editor, project_state, new_state)
  5057. self.assertTableNotExists("test_dligsw_pony")
  5058. # And test reversal
  5059. with connection.schema_editor() as editor:
  5060. operation.database_backwards(
  5061. "test_dligsw", editor, new_state, project_state
  5062. )
  5063. self.assertTableNotExists("test_dligsw_pony")
  5064. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  5065. def test_add_field_ignore_swapped(self):
  5066. """
  5067. Tests the AddField operation.
  5068. """
  5069. # Test the state alteration
  5070. operation = migrations.AddField(
  5071. "Pony",
  5072. "height",
  5073. models.FloatField(null=True, default=5),
  5074. )
  5075. project_state, new_state = self.make_test_state("test_adfligsw", operation)
  5076. # Test the database alteration
  5077. self.assertTableNotExists("test_adfligsw_pony")
  5078. with connection.schema_editor() as editor:
  5079. operation.database_forwards(
  5080. "test_adfligsw", editor, project_state, new_state
  5081. )
  5082. self.assertTableNotExists("test_adfligsw_pony")
  5083. # And test reversal
  5084. with connection.schema_editor() as editor:
  5085. operation.database_backwards(
  5086. "test_adfligsw", editor, new_state, project_state
  5087. )
  5088. self.assertTableNotExists("test_adfligsw_pony")
  5089. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  5090. def test_indexes_ignore_swapped(self):
  5091. """
  5092. Add/RemoveIndex operations ignore swapped models.
  5093. """
  5094. operation = migrations.AddIndex(
  5095. "Pony", models.Index(fields=["pink"], name="my_name_idx")
  5096. )
  5097. project_state, new_state = self.make_test_state("test_adinigsw", operation)
  5098. with connection.schema_editor() as editor:
  5099. # No database queries should be run for swapped models
  5100. operation.database_forwards(
  5101. "test_adinigsw", editor, project_state, new_state
  5102. )
  5103. operation.database_backwards(
  5104. "test_adinigsw", editor, new_state, project_state
  5105. )
  5106. operation = migrations.RemoveIndex(
  5107. "Pony", models.Index(fields=["pink"], name="my_name_idx")
  5108. )
  5109. project_state, new_state = self.make_test_state("test_rminigsw", operation)
  5110. with connection.schema_editor() as editor:
  5111. operation.database_forwards(
  5112. "test_rminigsw", editor, project_state, new_state
  5113. )
  5114. operation.database_backwards(
  5115. "test_rminigsw", editor, new_state, project_state
  5116. )
  5117. class TestCreateModel(SimpleTestCase):
  5118. def test_references_model_mixin(self):
  5119. migrations.CreateModel(
  5120. "name",
  5121. fields=[],
  5122. bases=(Mixin, models.Model),
  5123. ).references_model("other_model", "migrations")
  5124. class FieldOperationTests(SimpleTestCase):
  5125. def test_references_model(self):
  5126. operation = FieldOperation(
  5127. "MoDel", "field", models.ForeignKey("Other", models.CASCADE)
  5128. )
  5129. # Model name match.
  5130. self.assertIs(operation.references_model("mOdEl", "migrations"), True)
  5131. # Referenced field.
  5132. self.assertIs(operation.references_model("oTher", "migrations"), True)
  5133. # Doesn't reference.
  5134. self.assertIs(operation.references_model("Whatever", "migrations"), False)
  5135. def test_references_field_by_name(self):
  5136. operation = FieldOperation("MoDel", "field", models.BooleanField(default=False))
  5137. self.assertIs(operation.references_field("model", "field", "migrations"), True)
  5138. def test_references_field_by_remote_field_model(self):
  5139. operation = FieldOperation(
  5140. "Model", "field", models.ForeignKey("Other", models.CASCADE)
  5141. )
  5142. self.assertIs(
  5143. operation.references_field("Other", "whatever", "migrations"), True
  5144. )
  5145. self.assertIs(
  5146. operation.references_field("Missing", "whatever", "migrations"), False
  5147. )
  5148. def test_references_field_by_from_fields(self):
  5149. operation = FieldOperation(
  5150. "Model",
  5151. "field",
  5152. models.fields.related.ForeignObject(
  5153. "Other", models.CASCADE, ["from"], ["to"]
  5154. ),
  5155. )
  5156. self.assertIs(operation.references_field("Model", "from", "migrations"), True)
  5157. self.assertIs(operation.references_field("Model", "to", "migrations"), False)
  5158. self.assertIs(operation.references_field("Other", "from", "migrations"), False)
  5159. self.assertIs(operation.references_field("Model", "to", "migrations"), False)
  5160. def test_references_field_by_to_fields(self):
  5161. operation = FieldOperation(
  5162. "Model",
  5163. "field",
  5164. models.ForeignKey("Other", models.CASCADE, to_field="field"),
  5165. )
  5166. self.assertIs(operation.references_field("Other", "field", "migrations"), True)
  5167. self.assertIs(
  5168. operation.references_field("Other", "whatever", "migrations"), False
  5169. )
  5170. self.assertIs(
  5171. operation.references_field("Missing", "whatever", "migrations"), False
  5172. )
  5173. def test_references_field_by_through(self):
  5174. operation = FieldOperation(
  5175. "Model", "field", models.ManyToManyField("Other", through="Through")
  5176. )
  5177. self.assertIs(
  5178. operation.references_field("Other", "whatever", "migrations"), True
  5179. )
  5180. self.assertIs(
  5181. operation.references_field("Through", "whatever", "migrations"), True
  5182. )
  5183. self.assertIs(
  5184. operation.references_field("Missing", "whatever", "migrations"), False
  5185. )
  5186. def test_reference_field_by_through_fields(self):
  5187. operation = FieldOperation(
  5188. "Model",
  5189. "field",
  5190. models.ManyToManyField(
  5191. "Other", through="Through", through_fields=("first", "second")
  5192. ),
  5193. )
  5194. self.assertIs(
  5195. operation.references_field("Other", "whatever", "migrations"), True
  5196. )
  5197. self.assertIs(
  5198. operation.references_field("Through", "whatever", "migrations"), False
  5199. )
  5200. self.assertIs(
  5201. operation.references_field("Through", "first", "migrations"), True
  5202. )
  5203. self.assertIs(
  5204. operation.references_field("Through", "second", "migrations"), True
  5205. )