test_operations.py 251 KB

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