test_operations.py 253 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153
  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. pre_pony_pk = (
  1626. project_state.apps.get_model(app_label, "pony").objects.create(weight=4).pk
  1627. )
  1628. self.assertColumnNotExists(table_name, "height")
  1629. # Add field.
  1630. with connection.schema_editor() as editor:
  1631. operation.database_forwards(app_label, editor, project_state, new_state)
  1632. self.assertColumnExists(table_name, "height")
  1633. post_pony_pk = (
  1634. project_state.apps.get_model(app_label, "pony").objects.create(weight=10).pk
  1635. )
  1636. new_model = new_state.apps.get_model(app_label, "pony")
  1637. pre_pony = new_model.objects.get(pk=pre_pony_pk)
  1638. self.assertEqual(pre_pony.height, 4)
  1639. post_pony = new_model.objects.get(pk=post_pony_pk)
  1640. self.assertEqual(post_pony.height, 4)
  1641. new_pony = new_model.objects.create(weight=5)
  1642. if not connection.features.can_return_columns_from_insert:
  1643. new_pony.refresh_from_db()
  1644. self.assertEqual(new_pony.height, 3)
  1645. # Reversal.
  1646. with connection.schema_editor() as editor:
  1647. operation.database_backwards(app_label, editor, new_state, project_state)
  1648. self.assertColumnNotExists(table_name, "height")
  1649. # Deconstruction.
  1650. definition = operation.deconstruct()
  1651. self.assertEqual(definition[0], "AddField")
  1652. self.assertEqual(definition[1], [])
  1653. self.assertEqual(
  1654. definition[2],
  1655. {
  1656. "field": field,
  1657. "model_name": "Pony",
  1658. "name": "height",
  1659. },
  1660. )
  1661. def test_add_field_m2m(self):
  1662. """
  1663. Tests the AddField operation with a ManyToManyField.
  1664. """
  1665. project_state = self.set_up_test_model("test_adflmm", second_model=True)
  1666. # Test the state alteration
  1667. operation = migrations.AddField(
  1668. "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies")
  1669. )
  1670. new_state = project_state.clone()
  1671. operation.state_forwards("test_adflmm", new_state)
  1672. self.assertEqual(len(new_state.models["test_adflmm", "pony"].fields), 6)
  1673. # Test the database alteration
  1674. self.assertTableNotExists("test_adflmm_pony_stables")
  1675. with connection.schema_editor() as editor:
  1676. operation.database_forwards("test_adflmm", editor, project_state, new_state)
  1677. self.assertTableExists("test_adflmm_pony_stables")
  1678. self.assertColumnNotExists("test_adflmm_pony", "stables")
  1679. # Make sure the M2M field actually works
  1680. with atomic():
  1681. Pony = new_state.apps.get_model("test_adflmm", "Pony")
  1682. p = Pony.objects.create(pink=False, weight=4.55)
  1683. p.stables.create()
  1684. self.assertEqual(p.stables.count(), 1)
  1685. p.stables.all().delete()
  1686. # And test reversal
  1687. with connection.schema_editor() as editor:
  1688. operation.database_backwards(
  1689. "test_adflmm", editor, new_state, project_state
  1690. )
  1691. self.assertTableNotExists("test_adflmm_pony_stables")
  1692. def test_alter_field_m2m(self):
  1693. project_state = self.set_up_test_model("test_alflmm", second_model=True)
  1694. project_state = self.apply_operations(
  1695. "test_alflmm",
  1696. project_state,
  1697. operations=[
  1698. migrations.AddField(
  1699. "Pony",
  1700. "stables",
  1701. models.ManyToManyField("Stable", related_name="ponies"),
  1702. )
  1703. ],
  1704. )
  1705. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1706. self.assertFalse(Pony._meta.get_field("stables").blank)
  1707. project_state = self.apply_operations(
  1708. "test_alflmm",
  1709. project_state,
  1710. operations=[
  1711. migrations.AlterField(
  1712. "Pony",
  1713. "stables",
  1714. models.ManyToManyField(
  1715. to="Stable", related_name="ponies", blank=True
  1716. ),
  1717. )
  1718. ],
  1719. )
  1720. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1721. self.assertTrue(Pony._meta.get_field("stables").blank)
  1722. def test_repoint_field_m2m(self):
  1723. project_state = self.set_up_test_model(
  1724. "test_alflmm", second_model=True, third_model=True
  1725. )
  1726. project_state = self.apply_operations(
  1727. "test_alflmm",
  1728. project_state,
  1729. operations=[
  1730. migrations.AddField(
  1731. "Pony",
  1732. "places",
  1733. models.ManyToManyField("Stable", related_name="ponies"),
  1734. )
  1735. ],
  1736. )
  1737. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1738. project_state = self.apply_operations(
  1739. "test_alflmm",
  1740. project_state,
  1741. operations=[
  1742. migrations.AlterField(
  1743. "Pony",
  1744. "places",
  1745. models.ManyToManyField(to="Van", related_name="ponies"),
  1746. )
  1747. ],
  1748. )
  1749. # Ensure the new field actually works
  1750. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1751. p = Pony.objects.create(pink=False, weight=4.55)
  1752. p.places.create()
  1753. self.assertEqual(p.places.count(), 1)
  1754. p.places.all().delete()
  1755. def test_remove_field_m2m(self):
  1756. project_state = self.set_up_test_model("test_rmflmm", second_model=True)
  1757. project_state = self.apply_operations(
  1758. "test_rmflmm",
  1759. project_state,
  1760. operations=[
  1761. migrations.AddField(
  1762. "Pony",
  1763. "stables",
  1764. models.ManyToManyField("Stable", related_name="ponies"),
  1765. )
  1766. ],
  1767. )
  1768. self.assertTableExists("test_rmflmm_pony_stables")
  1769. with_field_state = project_state.clone()
  1770. operations = [migrations.RemoveField("Pony", "stables")]
  1771. project_state = self.apply_operations(
  1772. "test_rmflmm", project_state, operations=operations
  1773. )
  1774. self.assertTableNotExists("test_rmflmm_pony_stables")
  1775. # And test reversal
  1776. self.unapply_operations("test_rmflmm", with_field_state, operations=operations)
  1777. self.assertTableExists("test_rmflmm_pony_stables")
  1778. def test_remove_field_m2m_with_through(self):
  1779. project_state = self.set_up_test_model("test_rmflmmwt", second_model=True)
  1780. self.assertTableNotExists("test_rmflmmwt_ponystables")
  1781. project_state = self.apply_operations(
  1782. "test_rmflmmwt",
  1783. project_state,
  1784. operations=[
  1785. migrations.CreateModel(
  1786. "PonyStables",
  1787. fields=[
  1788. (
  1789. "pony",
  1790. models.ForeignKey("test_rmflmmwt.Pony", models.CASCADE),
  1791. ),
  1792. (
  1793. "stable",
  1794. models.ForeignKey("test_rmflmmwt.Stable", models.CASCADE),
  1795. ),
  1796. ],
  1797. ),
  1798. migrations.AddField(
  1799. "Pony",
  1800. "stables",
  1801. models.ManyToManyField(
  1802. "Stable",
  1803. related_name="ponies",
  1804. through="test_rmflmmwt.PonyStables",
  1805. ),
  1806. ),
  1807. ],
  1808. )
  1809. self.assertTableExists("test_rmflmmwt_ponystables")
  1810. operations = [
  1811. migrations.RemoveField("Pony", "stables"),
  1812. migrations.DeleteModel("PonyStables"),
  1813. ]
  1814. self.apply_operations("test_rmflmmwt", project_state, operations=operations)
  1815. def test_remove_field(self):
  1816. """
  1817. Tests the RemoveField operation.
  1818. """
  1819. project_state = self.set_up_test_model("test_rmfl")
  1820. # Test the state alteration
  1821. operation = migrations.RemoveField("Pony", "pink")
  1822. self.assertEqual(operation.describe(), "Remove field pink from Pony")
  1823. self.assertEqual(operation.migration_name_fragment, "remove_pony_pink")
  1824. new_state = project_state.clone()
  1825. operation.state_forwards("test_rmfl", new_state)
  1826. self.assertEqual(len(new_state.models["test_rmfl", "pony"].fields), 4)
  1827. # Test the database alteration
  1828. self.assertColumnExists("test_rmfl_pony", "pink")
  1829. with connection.schema_editor() as editor:
  1830. operation.database_forwards("test_rmfl", editor, project_state, new_state)
  1831. self.assertColumnNotExists("test_rmfl_pony", "pink")
  1832. # And test reversal
  1833. with connection.schema_editor() as editor:
  1834. operation.database_backwards("test_rmfl", editor, new_state, project_state)
  1835. self.assertColumnExists("test_rmfl_pony", "pink")
  1836. # And deconstruction
  1837. definition = operation.deconstruct()
  1838. self.assertEqual(definition[0], "RemoveField")
  1839. self.assertEqual(definition[1], [])
  1840. self.assertEqual(definition[2], {"model_name": "Pony", "name": "pink"})
  1841. def test_remove_fk(self):
  1842. """
  1843. Tests the RemoveField operation on a foreign key.
  1844. """
  1845. project_state = self.set_up_test_model("test_rfk", related_model=True)
  1846. self.assertColumnExists("test_rfk_rider", "pony_id")
  1847. operation = migrations.RemoveField("Rider", "pony")
  1848. new_state = project_state.clone()
  1849. operation.state_forwards("test_rfk", new_state)
  1850. with connection.schema_editor() as editor:
  1851. operation.database_forwards("test_rfk", editor, project_state, new_state)
  1852. self.assertColumnNotExists("test_rfk_rider", "pony_id")
  1853. with connection.schema_editor() as editor:
  1854. operation.database_backwards("test_rfk", editor, new_state, project_state)
  1855. self.assertColumnExists("test_rfk_rider", "pony_id")
  1856. def test_alter_model_table(self):
  1857. """
  1858. Tests the AlterModelTable operation.
  1859. """
  1860. project_state = self.set_up_test_model("test_almota")
  1861. # Test the state alteration
  1862. operation = migrations.AlterModelTable("Pony", "test_almota_pony_2")
  1863. self.assertEqual(
  1864. operation.describe(), "Rename table for Pony to test_almota_pony_2"
  1865. )
  1866. self.assertEqual(operation.migration_name_fragment, "alter_pony_table")
  1867. new_state = project_state.clone()
  1868. operation.state_forwards("test_almota", new_state)
  1869. self.assertEqual(
  1870. new_state.models["test_almota", "pony"].options["db_table"],
  1871. "test_almota_pony_2",
  1872. )
  1873. # Test the database alteration
  1874. self.assertTableExists("test_almota_pony")
  1875. self.assertTableNotExists("test_almota_pony_2")
  1876. with connection.schema_editor() as editor:
  1877. operation.database_forwards("test_almota", editor, project_state, new_state)
  1878. self.assertTableNotExists("test_almota_pony")
  1879. self.assertTableExists("test_almota_pony_2")
  1880. # And test reversal
  1881. with connection.schema_editor() as editor:
  1882. operation.database_backwards(
  1883. "test_almota", editor, new_state, project_state
  1884. )
  1885. self.assertTableExists("test_almota_pony")
  1886. self.assertTableNotExists("test_almota_pony_2")
  1887. # And deconstruction
  1888. definition = operation.deconstruct()
  1889. self.assertEqual(definition[0], "AlterModelTable")
  1890. self.assertEqual(definition[1], [])
  1891. self.assertEqual(definition[2], {"name": "Pony", "table": "test_almota_pony_2"})
  1892. def test_alter_model_table_none(self):
  1893. """
  1894. Tests the AlterModelTable operation if the table name is set to None.
  1895. """
  1896. operation = migrations.AlterModelTable("Pony", None)
  1897. self.assertEqual(operation.describe(), "Rename table for Pony to (default)")
  1898. def test_alter_model_table_noop(self):
  1899. """
  1900. Tests the AlterModelTable operation if the table name is not changed.
  1901. """
  1902. project_state = self.set_up_test_model("test_almota")
  1903. # Test the state alteration
  1904. operation = migrations.AlterModelTable("Pony", "test_almota_pony")
  1905. new_state = project_state.clone()
  1906. operation.state_forwards("test_almota", new_state)
  1907. self.assertEqual(
  1908. new_state.models["test_almota", "pony"].options["db_table"],
  1909. "test_almota_pony",
  1910. )
  1911. # Test the database alteration
  1912. self.assertTableExists("test_almota_pony")
  1913. with connection.schema_editor() as editor:
  1914. operation.database_forwards("test_almota", editor, project_state, new_state)
  1915. self.assertTableExists("test_almota_pony")
  1916. # And test reversal
  1917. with connection.schema_editor() as editor:
  1918. operation.database_backwards(
  1919. "test_almota", editor, new_state, project_state
  1920. )
  1921. self.assertTableExists("test_almota_pony")
  1922. def test_alter_model_table_m2m(self):
  1923. """
  1924. AlterModelTable should rename auto-generated M2M tables.
  1925. """
  1926. app_label = "test_talflmltlm2m"
  1927. pony_db_table = "pony_foo"
  1928. project_state = self.set_up_test_model(
  1929. app_label, second_model=True, db_table=pony_db_table
  1930. )
  1931. # Add the M2M field
  1932. first_state = project_state.clone()
  1933. operation = migrations.AddField(
  1934. "Pony", "stables", models.ManyToManyField("Stable")
  1935. )
  1936. operation.state_forwards(app_label, first_state)
  1937. with connection.schema_editor() as editor:
  1938. operation.database_forwards(app_label, editor, project_state, first_state)
  1939. original_m2m_table = "%s_%s" % (pony_db_table, "stables")
  1940. new_m2m_table = "%s_%s" % (app_label, "pony_stables")
  1941. self.assertTableExists(original_m2m_table)
  1942. self.assertTableNotExists(new_m2m_table)
  1943. # Rename the Pony db_table which should also rename the m2m table.
  1944. second_state = first_state.clone()
  1945. operation = migrations.AlterModelTable(name="pony", table=None)
  1946. operation.state_forwards(app_label, second_state)
  1947. with connection.schema_editor() as editor:
  1948. operation.database_forwards(app_label, editor, first_state, second_state)
  1949. self.assertTableExists(new_m2m_table)
  1950. self.assertTableNotExists(original_m2m_table)
  1951. # And test reversal
  1952. with connection.schema_editor() as editor:
  1953. operation.database_backwards(app_label, editor, second_state, first_state)
  1954. self.assertTableExists(original_m2m_table)
  1955. self.assertTableNotExists(new_m2m_table)
  1956. def test_alter_model_table_m2m_field(self):
  1957. app_label = "test_talm2mfl"
  1958. project_state = self.set_up_test_model(app_label, second_model=True)
  1959. # Add the M2M field.
  1960. project_state = self.apply_operations(
  1961. app_label,
  1962. project_state,
  1963. operations=[
  1964. migrations.AddField(
  1965. "Pony",
  1966. "stables",
  1967. models.ManyToManyField("Stable"),
  1968. )
  1969. ],
  1970. )
  1971. m2m_table = f"{app_label}_pony_stables"
  1972. self.assertColumnExists(m2m_table, "pony_id")
  1973. self.assertColumnExists(m2m_table, "stable_id")
  1974. # Point the M2M field to self.
  1975. with_field_state = project_state.clone()
  1976. operations = [
  1977. migrations.AlterField(
  1978. model_name="Pony",
  1979. name="stables",
  1980. field=models.ManyToManyField("self"),
  1981. )
  1982. ]
  1983. project_state = self.apply_operations(
  1984. app_label, project_state, operations=operations
  1985. )
  1986. self.assertColumnExists(m2m_table, "from_pony_id")
  1987. self.assertColumnExists(m2m_table, "to_pony_id")
  1988. # Reversal.
  1989. self.unapply_operations(app_label, with_field_state, operations=operations)
  1990. self.assertColumnExists(m2m_table, "pony_id")
  1991. self.assertColumnExists(m2m_table, "stable_id")
  1992. def test_alter_field(self):
  1993. """
  1994. Tests the AlterField operation.
  1995. """
  1996. project_state = self.set_up_test_model("test_alfl")
  1997. # Test the state alteration
  1998. operation = migrations.AlterField(
  1999. "Pony", "pink", models.IntegerField(null=True)
  2000. )
  2001. self.assertEqual(operation.describe(), "Alter field pink on Pony")
  2002. self.assertEqual(operation.migration_name_fragment, "alter_pony_pink")
  2003. new_state = project_state.clone()
  2004. operation.state_forwards("test_alfl", new_state)
  2005. self.assertIs(
  2006. project_state.models["test_alfl", "pony"].fields["pink"].null, False
  2007. )
  2008. self.assertIs(new_state.models["test_alfl", "pony"].fields["pink"].null, True)
  2009. # Test the database alteration
  2010. self.assertColumnNotNull("test_alfl_pony", "pink")
  2011. with connection.schema_editor() as editor:
  2012. operation.database_forwards("test_alfl", editor, project_state, new_state)
  2013. self.assertColumnNull("test_alfl_pony", "pink")
  2014. # And test reversal
  2015. with connection.schema_editor() as editor:
  2016. operation.database_backwards("test_alfl", editor, new_state, project_state)
  2017. self.assertColumnNotNull("test_alfl_pony", "pink")
  2018. # And deconstruction
  2019. definition = operation.deconstruct()
  2020. self.assertEqual(definition[0], "AlterField")
  2021. self.assertEqual(definition[1], [])
  2022. self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"])
  2023. def test_alter_field_add_database_default(self):
  2024. app_label = "test_alfladd"
  2025. project_state = self.set_up_test_model(app_label)
  2026. operation = migrations.AlterField(
  2027. "Pony", "weight", models.FloatField(db_default=4.5)
  2028. )
  2029. new_state = project_state.clone()
  2030. operation.state_forwards(app_label, new_state)
  2031. old_weight = project_state.models[app_label, "pony"].fields["weight"]
  2032. self.assertIs(old_weight.db_default, models.NOT_PROVIDED)
  2033. new_weight = new_state.models[app_label, "pony"].fields["weight"]
  2034. self.assertEqual(new_weight.db_default, Value(4.5))
  2035. with self.assertRaises(IntegrityError), transaction.atomic():
  2036. project_state.apps.get_model(app_label, "pony").objects.create()
  2037. # Alter field.
  2038. with connection.schema_editor() as editor:
  2039. operation.database_forwards(app_label, editor, project_state, new_state)
  2040. pony = new_state.apps.get_model(app_label, "pony").objects.create()
  2041. if not connection.features.can_return_columns_from_insert:
  2042. pony.refresh_from_db()
  2043. self.assertEqual(pony.weight, 4.5)
  2044. # Reversal.
  2045. with connection.schema_editor() as editor:
  2046. operation.database_backwards(app_label, editor, new_state, project_state)
  2047. with self.assertRaises(IntegrityError), transaction.atomic():
  2048. project_state.apps.get_model(app_label, "pony").objects.create()
  2049. # Deconstruction.
  2050. definition = operation.deconstruct()
  2051. self.assertEqual(definition[0], "AlterField")
  2052. self.assertEqual(definition[1], [])
  2053. self.assertEqual(
  2054. definition[2],
  2055. {
  2056. "field": new_weight,
  2057. "model_name": "Pony",
  2058. "name": "weight",
  2059. },
  2060. )
  2061. def test_alter_field_change_default_to_database_default(self):
  2062. """The AlterField operation changing default to db_default."""
  2063. app_label = "test_alflcdtdd"
  2064. project_state = self.set_up_test_model(app_label)
  2065. operation = migrations.AlterField(
  2066. "Pony", "pink", models.IntegerField(db_default=4)
  2067. )
  2068. new_state = project_state.clone()
  2069. operation.state_forwards(app_label, new_state)
  2070. old_pink = project_state.models[app_label, "pony"].fields["pink"]
  2071. self.assertEqual(old_pink.default, 3)
  2072. self.assertIs(old_pink.db_default, models.NOT_PROVIDED)
  2073. new_pink = new_state.models[app_label, "pony"].fields["pink"]
  2074. self.assertIs(new_pink.default, models.NOT_PROVIDED)
  2075. self.assertEqual(new_pink.db_default, Value(4))
  2076. pony = project_state.apps.get_model(app_label, "pony").objects.create(weight=1)
  2077. self.assertEqual(pony.pink, 3)
  2078. # Alter field.
  2079. with connection.schema_editor() as editor:
  2080. operation.database_forwards(app_label, editor, project_state, new_state)
  2081. pony = new_state.apps.get_model(app_label, "pony").objects.create(weight=1)
  2082. if not connection.features.can_return_columns_from_insert:
  2083. pony.refresh_from_db()
  2084. self.assertEqual(pony.pink, 4)
  2085. # Reversal.
  2086. with connection.schema_editor() as editor:
  2087. operation.database_backwards(app_label, editor, new_state, project_state)
  2088. pony = project_state.apps.get_model(app_label, "pony").objects.create(weight=1)
  2089. self.assertEqual(pony.pink, 3)
  2090. def test_alter_field_change_nullable_to_database_default_not_null(self):
  2091. """
  2092. The AlterField operation changing a null field to db_default.
  2093. """
  2094. app_label = "test_alflcntddnn"
  2095. project_state = self.set_up_test_model(app_label)
  2096. operation = migrations.AlterField(
  2097. "Pony", "green", models.IntegerField(db_default=4)
  2098. )
  2099. new_state = project_state.clone()
  2100. operation.state_forwards(app_label, new_state)
  2101. old_green = project_state.models[app_label, "pony"].fields["green"]
  2102. self.assertIs(old_green.db_default, models.NOT_PROVIDED)
  2103. new_green = new_state.models[app_label, "pony"].fields["green"]
  2104. self.assertEqual(new_green.db_default, Value(4))
  2105. old_pony = project_state.apps.get_model(app_label, "pony").objects.create(
  2106. weight=1
  2107. )
  2108. self.assertIsNone(old_pony.green)
  2109. # Alter field.
  2110. with connection.schema_editor() as editor:
  2111. operation.database_forwards(app_label, editor, project_state, new_state)
  2112. old_pony.refresh_from_db()
  2113. self.assertEqual(old_pony.green, 4)
  2114. pony = new_state.apps.get_model(app_label, "pony").objects.create(weight=1)
  2115. if not connection.features.can_return_columns_from_insert:
  2116. pony.refresh_from_db()
  2117. self.assertEqual(pony.green, 4)
  2118. # Reversal.
  2119. with connection.schema_editor() as editor:
  2120. operation.database_backwards(app_label, editor, new_state, project_state)
  2121. pony = project_state.apps.get_model(app_label, "pony").objects.create(weight=1)
  2122. self.assertIsNone(pony.green)
  2123. @skipIfDBFeature("interprets_empty_strings_as_nulls")
  2124. def test_alter_field_change_blank_nullable_database_default_to_not_null(self):
  2125. app_label = "test_alflcbnddnn"
  2126. table_name = f"{app_label}_pony"
  2127. project_state = self.set_up_test_model(app_label)
  2128. default = "Yellow"
  2129. operation = migrations.AlterField(
  2130. "Pony",
  2131. "yellow",
  2132. models.CharField(blank=True, db_default=default, max_length=20),
  2133. )
  2134. new_state = project_state.clone()
  2135. operation.state_forwards(app_label, new_state)
  2136. self.assertColumnNull(table_name, "yellow")
  2137. pony = project_state.apps.get_model(app_label, "pony").objects.create(
  2138. weight=1, yellow=None
  2139. )
  2140. self.assertIsNone(pony.yellow)
  2141. # Alter field.
  2142. with connection.schema_editor() as editor:
  2143. operation.database_forwards(app_label, editor, project_state, new_state)
  2144. self.assertColumnNotNull(table_name, "yellow")
  2145. pony.refresh_from_db()
  2146. self.assertEqual(pony.yellow, default)
  2147. pony = new_state.apps.get_model(app_label, "pony").objects.create(weight=1)
  2148. if not connection.features.can_return_columns_from_insert:
  2149. pony.refresh_from_db()
  2150. self.assertEqual(pony.yellow, default)
  2151. # Reversal.
  2152. with connection.schema_editor() as editor:
  2153. operation.database_backwards(app_label, editor, new_state, project_state)
  2154. self.assertColumnNull(table_name, "yellow")
  2155. pony = project_state.apps.get_model(app_label, "pony").objects.create(
  2156. weight=1, yellow=None
  2157. )
  2158. self.assertIsNone(pony.yellow)
  2159. def test_alter_field_add_db_column_noop(self):
  2160. """
  2161. AlterField operation is a noop when adding only a db_column and the
  2162. column name is not changed.
  2163. """
  2164. app_label = "test_afadbn"
  2165. project_state = self.set_up_test_model(app_label, related_model=True)
  2166. pony_table = "%s_pony" % app_label
  2167. new_state = project_state.clone()
  2168. operation = migrations.AlterField(
  2169. "Pony", "weight", models.FloatField(db_column="weight")
  2170. )
  2171. operation.state_forwards(app_label, new_state)
  2172. self.assertIsNone(
  2173. project_state.models[app_label, "pony"].fields["weight"].db_column,
  2174. )
  2175. self.assertEqual(
  2176. new_state.models[app_label, "pony"].fields["weight"].db_column,
  2177. "weight",
  2178. )
  2179. self.assertColumnExists(pony_table, "weight")
  2180. with connection.schema_editor() as editor:
  2181. with self.assertNumQueries(0):
  2182. operation.database_forwards(app_label, editor, project_state, new_state)
  2183. self.assertColumnExists(pony_table, "weight")
  2184. with connection.schema_editor() as editor:
  2185. with self.assertNumQueries(0):
  2186. operation.database_backwards(
  2187. app_label, editor, new_state, project_state
  2188. )
  2189. self.assertColumnExists(pony_table, "weight")
  2190. rider_table = "%s_rider" % app_label
  2191. new_state = project_state.clone()
  2192. operation = migrations.AlterField(
  2193. "Rider",
  2194. "pony",
  2195. models.ForeignKey("Pony", models.CASCADE, db_column="pony_id"),
  2196. )
  2197. operation.state_forwards(app_label, new_state)
  2198. self.assertIsNone(
  2199. project_state.models[app_label, "rider"].fields["pony"].db_column,
  2200. )
  2201. self.assertIs(
  2202. new_state.models[app_label, "rider"].fields["pony"].db_column,
  2203. "pony_id",
  2204. )
  2205. self.assertColumnExists(rider_table, "pony_id")
  2206. with connection.schema_editor() as editor:
  2207. with self.assertNumQueries(0):
  2208. operation.database_forwards(app_label, editor, project_state, new_state)
  2209. self.assertColumnExists(rider_table, "pony_id")
  2210. with connection.schema_editor() as editor:
  2211. with self.assertNumQueries(0):
  2212. operation.database_forwards(app_label, editor, new_state, project_state)
  2213. self.assertColumnExists(rider_table, "pony_id")
  2214. def test_alter_field_foreignobject_noop(self):
  2215. app_label = "test_alflfo_noop"
  2216. project_state = self.set_up_test_model(app_label)
  2217. project_state = self.apply_operations(
  2218. app_label,
  2219. project_state,
  2220. [
  2221. migrations.CreateModel(
  2222. "Rider",
  2223. fields=[
  2224. ("pony_id", models.IntegerField()),
  2225. (
  2226. "pony",
  2227. models.ForeignObject(
  2228. f"{app_label}.Pony",
  2229. models.CASCADE,
  2230. from_fields=("pony_id",),
  2231. to_fields=("id",),
  2232. ),
  2233. ),
  2234. ],
  2235. ),
  2236. ],
  2237. )
  2238. operation = migrations.AlterField(
  2239. "Rider",
  2240. "pony",
  2241. models.ForeignObject(
  2242. f"{app_label}.Pony",
  2243. models.CASCADE,
  2244. from_fields=("pony_id",),
  2245. to_fields=("id",),
  2246. null=True,
  2247. ),
  2248. )
  2249. new_state = project_state.clone()
  2250. operation.state_forwards(app_label, new_state)
  2251. with (
  2252. CaptureQueriesContext(connection) as ctx,
  2253. connection.schema_editor() as editor,
  2254. ):
  2255. operation.database_forwards(app_label, editor, project_state, new_state)
  2256. self.assertIs(
  2257. any("ALTER" in query["sql"] for query in ctx.captured_queries), False
  2258. )
  2259. @skipUnlessDBFeature("supports_comments")
  2260. def test_alter_model_table_comment(self):
  2261. app_label = "test_almotaco"
  2262. project_state = self.set_up_test_model(app_label)
  2263. pony_table = f"{app_label}_pony"
  2264. # Add table comment.
  2265. operation = migrations.AlterModelTableComment("Pony", "Custom pony comment")
  2266. self.assertEqual(operation.describe(), "Alter Pony table comment")
  2267. self.assertEqual(operation.migration_name_fragment, "alter_pony_table_comment")
  2268. new_state = project_state.clone()
  2269. operation.state_forwards(app_label, new_state)
  2270. self.assertEqual(
  2271. new_state.models[app_label, "pony"].options["db_table_comment"],
  2272. "Custom pony comment",
  2273. )
  2274. self.assertTableCommentNotExists(pony_table)
  2275. with connection.schema_editor() as editor:
  2276. operation.database_forwards(app_label, editor, project_state, new_state)
  2277. self.assertTableComment(pony_table, "Custom pony comment")
  2278. # Reversal.
  2279. with connection.schema_editor() as editor:
  2280. operation.database_backwards(app_label, editor, new_state, project_state)
  2281. self.assertTableCommentNotExists(pony_table)
  2282. # Deconstruction.
  2283. definition = operation.deconstruct()
  2284. self.assertEqual(definition[0], "AlterModelTableComment")
  2285. self.assertEqual(definition[1], [])
  2286. self.assertEqual(
  2287. definition[2], {"name": "Pony", "table_comment": "Custom pony comment"}
  2288. )
  2289. def test_alter_field_pk(self):
  2290. """
  2291. The AlterField operation on primary keys (things like PostgreSQL's
  2292. SERIAL weirdness).
  2293. """
  2294. project_state = self.set_up_test_model("test_alflpk")
  2295. # Test the state alteration
  2296. operation = migrations.AlterField(
  2297. "Pony", "id", models.IntegerField(primary_key=True)
  2298. )
  2299. new_state = project_state.clone()
  2300. operation.state_forwards("test_alflpk", new_state)
  2301. self.assertIsInstance(
  2302. project_state.models["test_alflpk", "pony"].fields["id"],
  2303. models.AutoField,
  2304. )
  2305. self.assertIsInstance(
  2306. new_state.models["test_alflpk", "pony"].fields["id"],
  2307. models.IntegerField,
  2308. )
  2309. # Test the database alteration
  2310. with connection.schema_editor() as editor:
  2311. operation.database_forwards("test_alflpk", editor, project_state, new_state)
  2312. # And test reversal
  2313. with connection.schema_editor() as editor:
  2314. operation.database_backwards(
  2315. "test_alflpk", editor, new_state, project_state
  2316. )
  2317. @skipUnlessDBFeature("supports_foreign_keys")
  2318. def test_alter_field_pk_fk(self):
  2319. """
  2320. Tests the AlterField operation on primary keys changes any FKs pointing to it.
  2321. """
  2322. project_state = self.set_up_test_model("test_alflpkfk", related_model=True)
  2323. project_state = self.apply_operations(
  2324. "test_alflpkfk",
  2325. project_state,
  2326. [
  2327. migrations.CreateModel(
  2328. "Stable",
  2329. fields=[
  2330. ("ponies", models.ManyToManyField("Pony")),
  2331. ],
  2332. ),
  2333. migrations.AddField(
  2334. "Pony",
  2335. "stables",
  2336. models.ManyToManyField("Stable"),
  2337. ),
  2338. ],
  2339. )
  2340. # Test the state alteration
  2341. operation = migrations.AlterField(
  2342. "Pony", "id", models.FloatField(primary_key=True)
  2343. )
  2344. new_state = project_state.clone()
  2345. operation.state_forwards("test_alflpkfk", new_state)
  2346. self.assertIsInstance(
  2347. project_state.models["test_alflpkfk", "pony"].fields["id"],
  2348. models.AutoField,
  2349. )
  2350. self.assertIsInstance(
  2351. new_state.models["test_alflpkfk", "pony"].fields["id"],
  2352. models.FloatField,
  2353. )
  2354. def assertIdTypeEqualsFkType():
  2355. with connection.cursor() as cursor:
  2356. id_type, id_null = [
  2357. (c.type_code, c.null_ok)
  2358. for c in connection.introspection.get_table_description(
  2359. cursor, "test_alflpkfk_pony"
  2360. )
  2361. if c.name == "id"
  2362. ][0]
  2363. fk_type, fk_null = [
  2364. (c.type_code, c.null_ok)
  2365. for c in connection.introspection.get_table_description(
  2366. cursor, "test_alflpkfk_rider"
  2367. )
  2368. if c.name == "pony_id"
  2369. ][0]
  2370. m2m_fk_type, m2m_fk_null = [
  2371. (c.type_code, c.null_ok)
  2372. for c in connection.introspection.get_table_description(
  2373. cursor,
  2374. "test_alflpkfk_pony_stables",
  2375. )
  2376. if c.name == "pony_id"
  2377. ][0]
  2378. remote_m2m_fk_type, remote_m2m_fk_null = [
  2379. (c.type_code, c.null_ok)
  2380. for c in connection.introspection.get_table_description(
  2381. cursor,
  2382. "test_alflpkfk_stable_ponies",
  2383. )
  2384. if c.name == "pony_id"
  2385. ][0]
  2386. self.assertEqual(id_type, fk_type)
  2387. self.assertEqual(id_type, m2m_fk_type)
  2388. self.assertEqual(id_type, remote_m2m_fk_type)
  2389. self.assertEqual(id_null, fk_null)
  2390. self.assertEqual(id_null, m2m_fk_null)
  2391. self.assertEqual(id_null, remote_m2m_fk_null)
  2392. assertIdTypeEqualsFkType()
  2393. # Test the database alteration
  2394. with connection.schema_editor() as editor:
  2395. operation.database_forwards(
  2396. "test_alflpkfk", editor, project_state, new_state
  2397. )
  2398. assertIdTypeEqualsFkType()
  2399. if connection.features.supports_foreign_keys:
  2400. self.assertFKExists(
  2401. "test_alflpkfk_pony_stables",
  2402. ["pony_id"],
  2403. ("test_alflpkfk_pony", "id"),
  2404. )
  2405. self.assertFKExists(
  2406. "test_alflpkfk_stable_ponies",
  2407. ["pony_id"],
  2408. ("test_alflpkfk_pony", "id"),
  2409. )
  2410. # And test reversal
  2411. with connection.schema_editor() as editor:
  2412. operation.database_backwards(
  2413. "test_alflpkfk", editor, new_state, project_state
  2414. )
  2415. assertIdTypeEqualsFkType()
  2416. if connection.features.supports_foreign_keys:
  2417. self.assertFKExists(
  2418. "test_alflpkfk_pony_stables",
  2419. ["pony_id"],
  2420. ("test_alflpkfk_pony", "id"),
  2421. )
  2422. self.assertFKExists(
  2423. "test_alflpkfk_stable_ponies",
  2424. ["pony_id"],
  2425. ("test_alflpkfk_pony", "id"),
  2426. )
  2427. @skipUnlessDBFeature("supports_collation_on_charfield", "supports_foreign_keys")
  2428. def test_alter_field_pk_fk_db_collation(self):
  2429. """
  2430. AlterField operation of db_collation on primary keys changes any FKs
  2431. pointing to it.
  2432. """
  2433. collation = connection.features.test_collations.get("non_default")
  2434. if not collation:
  2435. self.skipTest("Language collations are not supported.")
  2436. app_label = "test_alflpkfkdbc"
  2437. project_state = self.apply_operations(
  2438. app_label,
  2439. ProjectState(),
  2440. [
  2441. migrations.CreateModel(
  2442. "Pony",
  2443. [
  2444. ("id", models.CharField(primary_key=True, max_length=10)),
  2445. ],
  2446. ),
  2447. migrations.CreateModel(
  2448. "Rider",
  2449. [
  2450. ("pony", models.ForeignKey("Pony", models.CASCADE)),
  2451. ],
  2452. ),
  2453. migrations.CreateModel(
  2454. "Stable",
  2455. [
  2456. ("ponies", models.ManyToManyField("Pony")),
  2457. ],
  2458. ),
  2459. ],
  2460. )
  2461. # State alteration.
  2462. operation = migrations.AlterField(
  2463. "Pony",
  2464. "id",
  2465. models.CharField(
  2466. primary_key=True,
  2467. max_length=10,
  2468. db_collation=collation,
  2469. ),
  2470. )
  2471. new_state = project_state.clone()
  2472. operation.state_forwards(app_label, new_state)
  2473. # Database alteration.
  2474. with connection.schema_editor() as editor:
  2475. operation.database_forwards(app_label, editor, project_state, new_state)
  2476. self.assertColumnCollation(f"{app_label}_pony", "id", collation)
  2477. self.assertColumnCollation(f"{app_label}_rider", "pony_id", collation)
  2478. self.assertColumnCollation(f"{app_label}_stable_ponies", "pony_id", collation)
  2479. # Reversal.
  2480. with connection.schema_editor() as editor:
  2481. operation.database_backwards(app_label, editor, new_state, project_state)
  2482. def test_alter_field_pk_mti_fk(self):
  2483. app_label = "test_alflpkmtifk"
  2484. project_state = self.set_up_test_model(app_label, mti_model=True)
  2485. project_state = self.apply_operations(
  2486. app_label,
  2487. project_state,
  2488. [
  2489. migrations.CreateModel(
  2490. "ShetlandRider",
  2491. fields=[
  2492. (
  2493. "pony",
  2494. models.ForeignKey(
  2495. f"{app_label}.ShetlandPony", models.CASCADE
  2496. ),
  2497. ),
  2498. ],
  2499. ),
  2500. ],
  2501. )
  2502. operation = migrations.AlterField(
  2503. "Pony",
  2504. "id",
  2505. models.BigAutoField(primary_key=True),
  2506. )
  2507. new_state = project_state.clone()
  2508. operation.state_forwards(app_label, new_state)
  2509. self.assertIsInstance(
  2510. new_state.models[app_label, "pony"].fields["id"],
  2511. models.BigAutoField,
  2512. )
  2513. def _get_column_id_type(cursor, table, column):
  2514. return [
  2515. c.type_code
  2516. for c in connection.introspection.get_table_description(
  2517. cursor,
  2518. f"{app_label}_{table}",
  2519. )
  2520. if c.name == column
  2521. ][0]
  2522. def assertIdTypeEqualsMTIFkType():
  2523. with connection.cursor() as cursor:
  2524. parent_id_type = _get_column_id_type(cursor, "pony", "id")
  2525. child_id_type = _get_column_id_type(
  2526. cursor, "shetlandpony", "pony_ptr_id"
  2527. )
  2528. mti_id_type = _get_column_id_type(cursor, "shetlandrider", "pony_id")
  2529. self.assertEqual(parent_id_type, child_id_type)
  2530. self.assertEqual(parent_id_type, mti_id_type)
  2531. assertIdTypeEqualsMTIFkType()
  2532. # Alter primary key.
  2533. with connection.schema_editor() as editor:
  2534. operation.database_forwards(app_label, editor, project_state, new_state)
  2535. assertIdTypeEqualsMTIFkType()
  2536. if connection.features.supports_foreign_keys:
  2537. self.assertFKExists(
  2538. f"{app_label}_shetlandpony",
  2539. ["pony_ptr_id"],
  2540. (f"{app_label}_pony", "id"),
  2541. )
  2542. self.assertFKExists(
  2543. f"{app_label}_shetlandrider",
  2544. ["pony_id"],
  2545. (f"{app_label}_shetlandpony", "pony_ptr_id"),
  2546. )
  2547. # Reversal.
  2548. with connection.schema_editor() as editor:
  2549. operation.database_backwards(app_label, editor, new_state, project_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}_shetlandrider",
  2559. ["pony_id"],
  2560. (f"{app_label}_shetlandpony", "pony_ptr_id"),
  2561. )
  2562. def test_alter_field_pk_mti_and_fk_to_base(self):
  2563. app_label = "test_alflpkmtiftb"
  2564. project_state = self.set_up_test_model(
  2565. app_label,
  2566. mti_model=True,
  2567. related_model=True,
  2568. )
  2569. operation = migrations.AlterField(
  2570. "Pony",
  2571. "id",
  2572. models.BigAutoField(primary_key=True),
  2573. )
  2574. new_state = project_state.clone()
  2575. operation.state_forwards(app_label, new_state)
  2576. self.assertIsInstance(
  2577. new_state.models[app_label, "pony"].fields["id"],
  2578. models.BigAutoField,
  2579. )
  2580. def _get_column_id_type(cursor, table, column):
  2581. return [
  2582. c.type_code
  2583. for c in connection.introspection.get_table_description(
  2584. cursor,
  2585. f"{app_label}_{table}",
  2586. )
  2587. if c.name == column
  2588. ][0]
  2589. def assertIdTypeEqualsMTIFkType():
  2590. with connection.cursor() as cursor:
  2591. parent_id_type = _get_column_id_type(cursor, "pony", "id")
  2592. fk_id_type = _get_column_id_type(cursor, "rider", "pony_id")
  2593. child_id_type = _get_column_id_type(
  2594. cursor, "shetlandpony", "pony_ptr_id"
  2595. )
  2596. self.assertEqual(parent_id_type, child_id_type)
  2597. self.assertEqual(parent_id_type, fk_id_type)
  2598. assertIdTypeEqualsMTIFkType()
  2599. # Alter primary key.
  2600. with connection.schema_editor() as editor:
  2601. operation.database_forwards(app_label, editor, project_state, new_state)
  2602. assertIdTypeEqualsMTIFkType()
  2603. if connection.features.supports_foreign_keys:
  2604. self.assertFKExists(
  2605. f"{app_label}_shetlandpony",
  2606. ["pony_ptr_id"],
  2607. (f"{app_label}_pony", "id"),
  2608. )
  2609. self.assertFKExists(
  2610. f"{app_label}_rider",
  2611. ["pony_id"],
  2612. (f"{app_label}_pony", "id"),
  2613. )
  2614. # Reversal.
  2615. with connection.schema_editor() as editor:
  2616. operation.database_backwards(app_label, editor, new_state, project_state)
  2617. assertIdTypeEqualsMTIFkType()
  2618. if connection.features.supports_foreign_keys:
  2619. self.assertFKExists(
  2620. f"{app_label}_shetlandpony",
  2621. ["pony_ptr_id"],
  2622. (f"{app_label}_pony", "id"),
  2623. )
  2624. self.assertFKExists(
  2625. f"{app_label}_rider",
  2626. ["pony_id"],
  2627. (f"{app_label}_pony", "id"),
  2628. )
  2629. @skipUnlessDBFeature("supports_foreign_keys")
  2630. def test_alter_field_reloads_state_on_fk_with_to_field_target_type_change(self):
  2631. app_label = "test_alflrsfkwtflttc"
  2632. project_state = self.apply_operations(
  2633. app_label,
  2634. ProjectState(),
  2635. operations=[
  2636. migrations.CreateModel(
  2637. "Rider",
  2638. fields=[
  2639. ("id", models.AutoField(primary_key=True)),
  2640. ("code", models.IntegerField(unique=True)),
  2641. ],
  2642. ),
  2643. migrations.CreateModel(
  2644. "Pony",
  2645. fields=[
  2646. ("id", models.AutoField(primary_key=True)),
  2647. (
  2648. "rider",
  2649. models.ForeignKey(
  2650. "%s.Rider" % app_label, models.CASCADE, to_field="code"
  2651. ),
  2652. ),
  2653. ],
  2654. ),
  2655. ],
  2656. )
  2657. operation = migrations.AlterField(
  2658. "Rider",
  2659. "code",
  2660. models.CharField(max_length=100, unique=True),
  2661. )
  2662. self.apply_operations(app_label, project_state, operations=[operation])
  2663. id_type, id_null = [
  2664. (c.type_code, c.null_ok)
  2665. for c in self.get_table_description("%s_rider" % app_label)
  2666. if c.name == "code"
  2667. ][0]
  2668. fk_type, fk_null = [
  2669. (c.type_code, c.null_ok)
  2670. for c in self.get_table_description("%s_pony" % app_label)
  2671. if c.name == "rider_id"
  2672. ][0]
  2673. self.assertEqual(id_type, fk_type)
  2674. self.assertEqual(id_null, fk_null)
  2675. @skipUnlessDBFeature("supports_foreign_keys")
  2676. def test_alter_field_reloads_state_fk_with_to_field_related_name_target_type_change(
  2677. self,
  2678. ):
  2679. app_label = "test_alflrsfkwtflrnttc"
  2680. project_state = self.apply_operations(
  2681. app_label,
  2682. ProjectState(),
  2683. operations=[
  2684. migrations.CreateModel(
  2685. "Rider",
  2686. fields=[
  2687. ("id", models.AutoField(primary_key=True)),
  2688. ("code", models.PositiveIntegerField(unique=True)),
  2689. ],
  2690. ),
  2691. migrations.CreateModel(
  2692. "Pony",
  2693. fields=[
  2694. ("id", models.AutoField(primary_key=True)),
  2695. (
  2696. "rider",
  2697. models.ForeignKey(
  2698. "%s.Rider" % app_label,
  2699. models.CASCADE,
  2700. to_field="code",
  2701. related_name="+",
  2702. ),
  2703. ),
  2704. ],
  2705. ),
  2706. ],
  2707. )
  2708. operation = migrations.AlterField(
  2709. "Rider",
  2710. "code",
  2711. models.CharField(max_length=100, unique=True),
  2712. )
  2713. self.apply_operations(app_label, project_state, operations=[operation])
  2714. def test_alter_field_reloads_state_on_fk_target_changes(self):
  2715. """
  2716. If AlterField doesn't reload state appropriately, the second AlterField
  2717. crashes on MySQL due to not dropping the PonyRider.pony foreign key
  2718. constraint before modifying the column.
  2719. """
  2720. app_label = "alter_alter_field_reloads_state_on_fk_target_changes"
  2721. project_state = self.apply_operations(
  2722. app_label,
  2723. ProjectState(),
  2724. operations=[
  2725. migrations.CreateModel(
  2726. "Rider",
  2727. fields=[
  2728. ("id", models.CharField(primary_key=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("%s.Rider" % app_label, models.CASCADE),
  2738. ),
  2739. ],
  2740. ),
  2741. migrations.CreateModel(
  2742. "PonyRider",
  2743. fields=[
  2744. ("id", models.AutoField(primary_key=True)),
  2745. (
  2746. "pony",
  2747. models.ForeignKey("%s.Pony" % app_label, models.CASCADE),
  2748. ),
  2749. ],
  2750. ),
  2751. ],
  2752. )
  2753. project_state = self.apply_operations(
  2754. app_label,
  2755. project_state,
  2756. operations=[
  2757. migrations.AlterField(
  2758. "Rider", "id", models.CharField(primary_key=True, max_length=99)
  2759. ),
  2760. migrations.AlterField(
  2761. "Pony", "id", models.CharField(primary_key=True, max_length=99)
  2762. ),
  2763. ],
  2764. )
  2765. def test_alter_field_reloads_state_on_fk_with_to_field_target_changes(self):
  2766. """
  2767. If AlterField doesn't reload state appropriately, the second AlterField
  2768. crashes on MySQL due to not dropping the PonyRider.pony foreign key
  2769. constraint before modifying the column.
  2770. """
  2771. app_label = "alter_alter_field_reloads_state_on_fk_with_to_field_target_changes"
  2772. project_state = self.apply_operations(
  2773. app_label,
  2774. ProjectState(),
  2775. operations=[
  2776. migrations.CreateModel(
  2777. "Rider",
  2778. fields=[
  2779. ("id", models.CharField(primary_key=True, max_length=100)),
  2780. ("slug", models.CharField(unique=True, max_length=100)),
  2781. ],
  2782. ),
  2783. migrations.CreateModel(
  2784. "Pony",
  2785. fields=[
  2786. ("id", models.CharField(primary_key=True, max_length=100)),
  2787. (
  2788. "rider",
  2789. models.ForeignKey(
  2790. "%s.Rider" % app_label, models.CASCADE, to_field="slug"
  2791. ),
  2792. ),
  2793. ("slug", models.CharField(unique=True, max_length=100)),
  2794. ],
  2795. ),
  2796. migrations.CreateModel(
  2797. "PonyRider",
  2798. fields=[
  2799. ("id", models.AutoField(primary_key=True)),
  2800. (
  2801. "pony",
  2802. models.ForeignKey(
  2803. "%s.Pony" % app_label, models.CASCADE, to_field="slug"
  2804. ),
  2805. ),
  2806. ],
  2807. ),
  2808. ],
  2809. )
  2810. project_state = self.apply_operations(
  2811. app_label,
  2812. project_state,
  2813. operations=[
  2814. migrations.AlterField(
  2815. "Rider", "slug", models.CharField(unique=True, max_length=99)
  2816. ),
  2817. migrations.AlterField(
  2818. "Pony", "slug", models.CharField(unique=True, max_length=99)
  2819. ),
  2820. ],
  2821. )
  2822. def test_alter_field_pk_fk_char_to_int(self):
  2823. app_label = "alter_field_pk_fk_char_to_int"
  2824. project_state = self.apply_operations(
  2825. app_label,
  2826. ProjectState(),
  2827. operations=[
  2828. migrations.CreateModel(
  2829. name="Parent",
  2830. fields=[
  2831. ("id", models.CharField(max_length=255, primary_key=True)),
  2832. ],
  2833. ),
  2834. migrations.CreateModel(
  2835. name="Child",
  2836. fields=[
  2837. ("id", models.BigAutoField(primary_key=True)),
  2838. (
  2839. "parent",
  2840. models.ForeignKey(
  2841. f"{app_label}.Parent",
  2842. on_delete=models.CASCADE,
  2843. ),
  2844. ),
  2845. ],
  2846. ),
  2847. ],
  2848. )
  2849. self.apply_operations(
  2850. app_label,
  2851. project_state,
  2852. operations=[
  2853. migrations.AlterField(
  2854. model_name="parent",
  2855. name="id",
  2856. field=models.BigIntegerField(primary_key=True),
  2857. ),
  2858. ],
  2859. )
  2860. def test_rename_field_reloads_state_on_fk_target_changes(self):
  2861. """
  2862. If RenameField doesn't reload state appropriately, the AlterField
  2863. crashes on MySQL due to not dropping the PonyRider.pony foreign key
  2864. constraint before modifying the column.
  2865. """
  2866. app_label = "alter_rename_field_reloads_state_on_fk_target_changes"
  2867. project_state = self.apply_operations(
  2868. app_label,
  2869. ProjectState(),
  2870. operations=[
  2871. migrations.CreateModel(
  2872. "Rider",
  2873. fields=[
  2874. ("id", models.CharField(primary_key=True, max_length=100)),
  2875. ],
  2876. ),
  2877. migrations.CreateModel(
  2878. "Pony",
  2879. fields=[
  2880. ("id", models.CharField(primary_key=True, max_length=100)),
  2881. (
  2882. "rider",
  2883. models.ForeignKey("%s.Rider" % app_label, models.CASCADE),
  2884. ),
  2885. ],
  2886. ),
  2887. migrations.CreateModel(
  2888. "PonyRider",
  2889. fields=[
  2890. ("id", models.AutoField(primary_key=True)),
  2891. (
  2892. "pony",
  2893. models.ForeignKey("%s.Pony" % app_label, models.CASCADE),
  2894. ),
  2895. ],
  2896. ),
  2897. ],
  2898. )
  2899. project_state = self.apply_operations(
  2900. app_label,
  2901. project_state,
  2902. operations=[
  2903. migrations.RenameField("Rider", "id", "id2"),
  2904. migrations.AlterField(
  2905. "Pony", "id", models.CharField(primary_key=True, max_length=99)
  2906. ),
  2907. ],
  2908. )
  2909. def test_rename_field(self):
  2910. """
  2911. Tests the RenameField operation.
  2912. """
  2913. project_state = self.set_up_test_model("test_rnfl")
  2914. operation = migrations.RenameField("Pony", "pink", "blue")
  2915. self.assertEqual(operation.describe(), "Rename field pink on Pony to blue")
  2916. self.assertEqual(operation.migration_name_fragment, "rename_pink_pony_blue")
  2917. new_state = project_state.clone()
  2918. operation.state_forwards("test_rnfl", new_state)
  2919. self.assertIn("blue", new_state.models["test_rnfl", "pony"].fields)
  2920. self.assertNotIn("pink", new_state.models["test_rnfl", "pony"].fields)
  2921. # Rename field.
  2922. self.assertColumnExists("test_rnfl_pony", "pink")
  2923. self.assertColumnNotExists("test_rnfl_pony", "blue")
  2924. with connection.schema_editor() as editor:
  2925. operation.database_forwards("test_rnfl", editor, project_state, new_state)
  2926. self.assertColumnExists("test_rnfl_pony", "blue")
  2927. self.assertColumnNotExists("test_rnfl_pony", "pink")
  2928. # Reversal.
  2929. with connection.schema_editor() as editor:
  2930. operation.database_backwards("test_rnfl", editor, new_state, project_state)
  2931. self.assertColumnExists("test_rnfl_pony", "pink")
  2932. self.assertColumnNotExists("test_rnfl_pony", "blue")
  2933. # Deconstruction.
  2934. definition = operation.deconstruct()
  2935. self.assertEqual(definition[0], "RenameField")
  2936. self.assertEqual(definition[1], [])
  2937. self.assertEqual(
  2938. definition[2],
  2939. {"model_name": "Pony", "old_name": "pink", "new_name": "blue"},
  2940. )
  2941. def test_rename_field_unique_together(self):
  2942. project_state = self.set_up_test_model("test_rnflut", unique_together=True)
  2943. operation = migrations.RenameField("Pony", "pink", "blue")
  2944. new_state = project_state.clone()
  2945. operation.state_forwards("test_rnflut", new_state)
  2946. # unique_together has the renamed column.
  2947. self.assertIn(
  2948. "blue",
  2949. new_state.models["test_rnflut", "pony"].options["unique_together"][0],
  2950. )
  2951. self.assertNotIn(
  2952. "pink",
  2953. new_state.models["test_rnflut", "pony"].options["unique_together"][0],
  2954. )
  2955. # Rename field.
  2956. self.assertColumnExists("test_rnflut_pony", "pink")
  2957. self.assertColumnNotExists("test_rnflut_pony", "blue")
  2958. with connection.schema_editor() as editor:
  2959. operation.database_forwards("test_rnflut", editor, project_state, new_state)
  2960. self.assertColumnExists("test_rnflut_pony", "blue")
  2961. self.assertColumnNotExists("test_rnflut_pony", "pink")
  2962. # The unique constraint has been ported over.
  2963. with connection.cursor() as cursor:
  2964. cursor.execute("INSERT INTO test_rnflut_pony (blue, weight) VALUES (1, 1)")
  2965. with self.assertRaises(IntegrityError):
  2966. with atomic():
  2967. cursor.execute(
  2968. "INSERT INTO test_rnflut_pony (blue, weight) VALUES (1, 1)"
  2969. )
  2970. cursor.execute("DELETE FROM test_rnflut_pony")
  2971. # Reversal.
  2972. with connection.schema_editor() as editor:
  2973. operation.database_backwards(
  2974. "test_rnflut", editor, new_state, project_state
  2975. )
  2976. self.assertColumnExists("test_rnflut_pony", "pink")
  2977. self.assertColumnNotExists("test_rnflut_pony", "blue")
  2978. @ignore_warnings(category=RemovedInDjango51Warning)
  2979. def test_rename_field_index_together(self):
  2980. project_state = self.set_up_test_model("test_rnflit", index_together=True)
  2981. operation = migrations.RenameField("Pony", "pink", "blue")
  2982. new_state = project_state.clone()
  2983. operation.state_forwards("test_rnflit", new_state)
  2984. self.assertIn("blue", new_state.models["test_rnflit", "pony"].fields)
  2985. self.assertNotIn("pink", new_state.models["test_rnflit", "pony"].fields)
  2986. # index_together has the renamed column.
  2987. self.assertIn(
  2988. "blue", new_state.models["test_rnflit", "pony"].options["index_together"][0]
  2989. )
  2990. self.assertNotIn(
  2991. "pink", new_state.models["test_rnflit", "pony"].options["index_together"][0]
  2992. )
  2993. # Rename field.
  2994. self.assertColumnExists("test_rnflit_pony", "pink")
  2995. self.assertColumnNotExists("test_rnflit_pony", "blue")
  2996. with connection.schema_editor() as editor:
  2997. operation.database_forwards("test_rnflit", editor, project_state, new_state)
  2998. self.assertColumnExists("test_rnflit_pony", "blue")
  2999. self.assertColumnNotExists("test_rnflit_pony", "pink")
  3000. # The index constraint has been ported over.
  3001. self.assertIndexExists("test_rnflit_pony", ["weight", "blue"])
  3002. # Reversal.
  3003. with connection.schema_editor() as editor:
  3004. operation.database_backwards(
  3005. "test_rnflit", editor, new_state, project_state
  3006. )
  3007. self.assertIndexExists("test_rnflit_pony", ["weight", "pink"])
  3008. def test_rename_field_with_db_column(self):
  3009. project_state = self.apply_operations(
  3010. "test_rfwdbc",
  3011. ProjectState(),
  3012. operations=[
  3013. migrations.CreateModel(
  3014. "Pony",
  3015. fields=[
  3016. ("id", models.AutoField(primary_key=True)),
  3017. ("field", models.IntegerField(db_column="db_field")),
  3018. (
  3019. "fk_field",
  3020. models.ForeignKey(
  3021. "Pony",
  3022. models.CASCADE,
  3023. db_column="db_fk_field",
  3024. ),
  3025. ),
  3026. ],
  3027. ),
  3028. ],
  3029. )
  3030. new_state = project_state.clone()
  3031. operation = migrations.RenameField("Pony", "field", "renamed_field")
  3032. operation.state_forwards("test_rfwdbc", new_state)
  3033. self.assertIn("renamed_field", new_state.models["test_rfwdbc", "pony"].fields)
  3034. self.assertNotIn("field", new_state.models["test_rfwdbc", "pony"].fields)
  3035. self.assertColumnExists("test_rfwdbc_pony", "db_field")
  3036. with connection.schema_editor() as editor:
  3037. with self.assertNumQueries(0):
  3038. operation.database_forwards(
  3039. "test_rfwdbc", editor, project_state, new_state
  3040. )
  3041. self.assertColumnExists("test_rfwdbc_pony", "db_field")
  3042. with connection.schema_editor() as editor:
  3043. with self.assertNumQueries(0):
  3044. operation.database_backwards(
  3045. "test_rfwdbc", editor, new_state, project_state
  3046. )
  3047. self.assertColumnExists("test_rfwdbc_pony", "db_field")
  3048. new_state = project_state.clone()
  3049. operation = migrations.RenameField("Pony", "fk_field", "renamed_fk_field")
  3050. operation.state_forwards("test_rfwdbc", new_state)
  3051. self.assertIn(
  3052. "renamed_fk_field", new_state.models["test_rfwdbc", "pony"].fields
  3053. )
  3054. self.assertNotIn("fk_field", new_state.models["test_rfwdbc", "pony"].fields)
  3055. self.assertColumnExists("test_rfwdbc_pony", "db_fk_field")
  3056. with connection.schema_editor() as editor:
  3057. with self.assertNumQueries(0):
  3058. operation.database_forwards(
  3059. "test_rfwdbc", editor, project_state, new_state
  3060. )
  3061. self.assertColumnExists("test_rfwdbc_pony", "db_fk_field")
  3062. with connection.schema_editor() as editor:
  3063. with self.assertNumQueries(0):
  3064. operation.database_backwards(
  3065. "test_rfwdbc", editor, new_state, project_state
  3066. )
  3067. self.assertColumnExists("test_rfwdbc_pony", "db_fk_field")
  3068. def test_rename_field_case(self):
  3069. project_state = self.apply_operations(
  3070. "test_rfmx",
  3071. ProjectState(),
  3072. operations=[
  3073. migrations.CreateModel(
  3074. "Pony",
  3075. fields=[
  3076. ("id", models.AutoField(primary_key=True)),
  3077. ("field", models.IntegerField()),
  3078. ],
  3079. ),
  3080. ],
  3081. )
  3082. new_state = project_state.clone()
  3083. operation = migrations.RenameField("Pony", "field", "FiElD")
  3084. operation.state_forwards("test_rfmx", new_state)
  3085. self.assertIn("FiElD", new_state.models["test_rfmx", "pony"].fields)
  3086. self.assertColumnExists("test_rfmx_pony", "field")
  3087. with connection.schema_editor() as editor:
  3088. operation.database_forwards("test_rfmx", editor, project_state, new_state)
  3089. self.assertColumnExists(
  3090. "test_rfmx_pony",
  3091. connection.introspection.identifier_converter("FiElD"),
  3092. )
  3093. with connection.schema_editor() as editor:
  3094. operation.database_backwards("test_rfmx", editor, new_state, project_state)
  3095. self.assertColumnExists("test_rfmx_pony", "field")
  3096. def test_rename_missing_field(self):
  3097. state = ProjectState()
  3098. state.add_model(ModelState("app", "model", []))
  3099. with self.assertRaisesMessage(
  3100. FieldDoesNotExist, "app.model has no field named 'field'"
  3101. ):
  3102. migrations.RenameField("model", "field", "new_field").state_forwards(
  3103. "app", state
  3104. )
  3105. def test_rename_referenced_field_state_forward(self):
  3106. state = ProjectState()
  3107. state.add_model(
  3108. ModelState(
  3109. "app",
  3110. "Model",
  3111. [
  3112. ("id", models.AutoField(primary_key=True)),
  3113. ("field", models.IntegerField(unique=True)),
  3114. ],
  3115. )
  3116. )
  3117. state.add_model(
  3118. ModelState(
  3119. "app",
  3120. "OtherModel",
  3121. [
  3122. ("id", models.AutoField(primary_key=True)),
  3123. (
  3124. "fk",
  3125. models.ForeignKey("Model", models.CASCADE, to_field="field"),
  3126. ),
  3127. (
  3128. "fo",
  3129. models.ForeignObject(
  3130. "Model",
  3131. models.CASCADE,
  3132. from_fields=("fk",),
  3133. to_fields=("field",),
  3134. ),
  3135. ),
  3136. ],
  3137. )
  3138. )
  3139. operation = migrations.RenameField("Model", "field", "renamed")
  3140. new_state = state.clone()
  3141. operation.state_forwards("app", new_state)
  3142. self.assertEqual(
  3143. new_state.models["app", "othermodel"].fields["fk"].remote_field.field_name,
  3144. "renamed",
  3145. )
  3146. self.assertEqual(
  3147. new_state.models["app", "othermodel"].fields["fk"].from_fields, ["self"]
  3148. )
  3149. self.assertEqual(
  3150. new_state.models["app", "othermodel"].fields["fk"].to_fields, ("renamed",)
  3151. )
  3152. self.assertEqual(
  3153. new_state.models["app", "othermodel"].fields["fo"].from_fields, ("fk",)
  3154. )
  3155. self.assertEqual(
  3156. new_state.models["app", "othermodel"].fields["fo"].to_fields, ("renamed",)
  3157. )
  3158. operation = migrations.RenameField("OtherModel", "fk", "renamed_fk")
  3159. new_state = state.clone()
  3160. operation.state_forwards("app", new_state)
  3161. self.assertEqual(
  3162. new_state.models["app", "othermodel"]
  3163. .fields["renamed_fk"]
  3164. .remote_field.field_name,
  3165. "renamed",
  3166. )
  3167. self.assertEqual(
  3168. new_state.models["app", "othermodel"].fields["renamed_fk"].from_fields,
  3169. ("self",),
  3170. )
  3171. self.assertEqual(
  3172. new_state.models["app", "othermodel"].fields["renamed_fk"].to_fields,
  3173. ("renamed",),
  3174. )
  3175. self.assertEqual(
  3176. new_state.models["app", "othermodel"].fields["fo"].from_fields,
  3177. ("renamed_fk",),
  3178. )
  3179. self.assertEqual(
  3180. new_state.models["app", "othermodel"].fields["fo"].to_fields, ("renamed",)
  3181. )
  3182. def test_alter_unique_together(self):
  3183. """
  3184. Tests the AlterUniqueTogether operation.
  3185. """
  3186. project_state = self.set_up_test_model("test_alunto")
  3187. # Test the state alteration
  3188. operation = migrations.AlterUniqueTogether("Pony", [("pink", "weight")])
  3189. self.assertEqual(
  3190. operation.describe(), "Alter unique_together for Pony (1 constraint(s))"
  3191. )
  3192. self.assertEqual(
  3193. operation.migration_name_fragment,
  3194. "alter_pony_unique_together",
  3195. )
  3196. new_state = project_state.clone()
  3197. operation.state_forwards("test_alunto", new_state)
  3198. self.assertEqual(
  3199. len(
  3200. project_state.models["test_alunto", "pony"].options.get(
  3201. "unique_together", set()
  3202. )
  3203. ),
  3204. 0,
  3205. )
  3206. self.assertEqual(
  3207. len(
  3208. new_state.models["test_alunto", "pony"].options.get(
  3209. "unique_together", set()
  3210. )
  3211. ),
  3212. 1,
  3213. )
  3214. # Make sure we can insert duplicate rows
  3215. with connection.cursor() as cursor:
  3216. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  3217. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  3218. cursor.execute("DELETE FROM test_alunto_pony")
  3219. # Test the database alteration
  3220. with connection.schema_editor() as editor:
  3221. operation.database_forwards(
  3222. "test_alunto", editor, project_state, new_state
  3223. )
  3224. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  3225. with self.assertRaises(IntegrityError):
  3226. with atomic():
  3227. cursor.execute(
  3228. "INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)"
  3229. )
  3230. cursor.execute("DELETE FROM test_alunto_pony")
  3231. # And test reversal
  3232. with connection.schema_editor() as editor:
  3233. operation.database_backwards(
  3234. "test_alunto", editor, new_state, project_state
  3235. )
  3236. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  3237. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  3238. cursor.execute("DELETE FROM test_alunto_pony")
  3239. # Test flat unique_together
  3240. operation = migrations.AlterUniqueTogether("Pony", ("pink", "weight"))
  3241. operation.state_forwards("test_alunto", new_state)
  3242. self.assertEqual(
  3243. len(
  3244. new_state.models["test_alunto", "pony"].options.get(
  3245. "unique_together", set()
  3246. )
  3247. ),
  3248. 1,
  3249. )
  3250. # And deconstruction
  3251. definition = operation.deconstruct()
  3252. self.assertEqual(definition[0], "AlterUniqueTogether")
  3253. self.assertEqual(definition[1], [])
  3254. self.assertEqual(
  3255. definition[2], {"name": "Pony", "unique_together": {("pink", "weight")}}
  3256. )
  3257. def test_alter_unique_together_remove(self):
  3258. operation = migrations.AlterUniqueTogether("Pony", None)
  3259. self.assertEqual(
  3260. operation.describe(), "Alter unique_together for Pony (0 constraint(s))"
  3261. )
  3262. @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields")
  3263. def test_remove_unique_together_on_pk_field(self):
  3264. app_label = "test_rutopkf"
  3265. project_state = self.apply_operations(
  3266. app_label,
  3267. ProjectState(),
  3268. operations=[
  3269. migrations.CreateModel(
  3270. "Pony",
  3271. fields=[("id", models.AutoField(primary_key=True))],
  3272. options={"unique_together": {("id",)}},
  3273. ),
  3274. ],
  3275. )
  3276. table_name = f"{app_label}_pony"
  3277. pk_constraint_name = f"{table_name}_pkey"
  3278. unique_together_constraint_name = f"{table_name}_id_fb61f881_uniq"
  3279. self.assertConstraintExists(table_name, pk_constraint_name, value=False)
  3280. self.assertConstraintExists(
  3281. table_name, unique_together_constraint_name, value=False
  3282. )
  3283. new_state = project_state.clone()
  3284. operation = migrations.AlterUniqueTogether("Pony", set())
  3285. operation.state_forwards(app_label, new_state)
  3286. with connection.schema_editor() as editor:
  3287. operation.database_forwards(app_label, editor, project_state, new_state)
  3288. self.assertConstraintExists(table_name, pk_constraint_name, value=False)
  3289. self.assertConstraintNotExists(table_name, unique_together_constraint_name)
  3290. @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields")
  3291. def test_remove_unique_together_on_unique_field(self):
  3292. app_label = "test_rutouf"
  3293. project_state = self.apply_operations(
  3294. app_label,
  3295. ProjectState(),
  3296. operations=[
  3297. migrations.CreateModel(
  3298. "Pony",
  3299. fields=[
  3300. ("id", models.AutoField(primary_key=True)),
  3301. ("name", models.CharField(max_length=30, unique=True)),
  3302. ],
  3303. options={"unique_together": {("name",)}},
  3304. ),
  3305. ],
  3306. )
  3307. table_name = f"{app_label}_pony"
  3308. unique_constraint_name = f"{table_name}_name_key"
  3309. unique_together_constraint_name = f"{table_name}_name_694f3b9f_uniq"
  3310. self.assertConstraintExists(table_name, unique_constraint_name, value=False)
  3311. self.assertConstraintExists(
  3312. table_name, unique_together_constraint_name, value=False
  3313. )
  3314. new_state = project_state.clone()
  3315. operation = migrations.AlterUniqueTogether("Pony", set())
  3316. operation.state_forwards(app_label, new_state)
  3317. with connection.schema_editor() as editor:
  3318. operation.database_forwards(app_label, editor, project_state, new_state)
  3319. self.assertConstraintExists(table_name, unique_constraint_name, value=False)
  3320. self.assertConstraintNotExists(table_name, unique_together_constraint_name)
  3321. def test_add_index(self):
  3322. """
  3323. Test the AddIndex operation.
  3324. """
  3325. project_state = self.set_up_test_model("test_adin")
  3326. msg = (
  3327. "Indexes passed to AddIndex operations require a name argument. "
  3328. "<Index: fields=['pink']> doesn't have one."
  3329. )
  3330. with self.assertRaisesMessage(ValueError, msg):
  3331. migrations.AddIndex("Pony", models.Index(fields=["pink"]))
  3332. index = models.Index(fields=["pink"], name="test_adin_pony_pink_idx")
  3333. operation = migrations.AddIndex("Pony", index)
  3334. self.assertEqual(
  3335. operation.describe(),
  3336. "Create index test_adin_pony_pink_idx on field(s) pink of model Pony",
  3337. )
  3338. self.assertEqual(
  3339. operation.migration_name_fragment,
  3340. "pony_test_adin_pony_pink_idx",
  3341. )
  3342. new_state = project_state.clone()
  3343. operation.state_forwards("test_adin", new_state)
  3344. # Test the database alteration
  3345. self.assertEqual(
  3346. len(new_state.models["test_adin", "pony"].options["indexes"]), 1
  3347. )
  3348. self.assertIndexNotExists("test_adin_pony", ["pink"])
  3349. with connection.schema_editor() as editor:
  3350. operation.database_forwards("test_adin", editor, project_state, new_state)
  3351. self.assertIndexExists("test_adin_pony", ["pink"])
  3352. # And test reversal
  3353. with connection.schema_editor() as editor:
  3354. operation.database_backwards("test_adin", editor, new_state, project_state)
  3355. self.assertIndexNotExists("test_adin_pony", ["pink"])
  3356. # And deconstruction
  3357. definition = operation.deconstruct()
  3358. self.assertEqual(definition[0], "AddIndex")
  3359. self.assertEqual(definition[1], [])
  3360. self.assertEqual(definition[2], {"model_name": "Pony", "index": index})
  3361. def test_remove_index(self):
  3362. """
  3363. Test the RemoveIndex operation.
  3364. """
  3365. project_state = self.set_up_test_model("test_rmin", multicol_index=True)
  3366. self.assertTableExists("test_rmin_pony")
  3367. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  3368. operation = migrations.RemoveIndex("Pony", "pony_test_idx")
  3369. self.assertEqual(operation.describe(), "Remove index pony_test_idx from Pony")
  3370. self.assertEqual(
  3371. operation.migration_name_fragment,
  3372. "remove_pony_pony_test_idx",
  3373. )
  3374. new_state = project_state.clone()
  3375. operation.state_forwards("test_rmin", new_state)
  3376. # Test the state alteration
  3377. self.assertEqual(
  3378. len(new_state.models["test_rmin", "pony"].options["indexes"]), 0
  3379. )
  3380. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  3381. # Test the database alteration
  3382. with connection.schema_editor() as editor:
  3383. operation.database_forwards("test_rmin", editor, project_state, new_state)
  3384. self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"])
  3385. # And test reversal
  3386. with connection.schema_editor() as editor:
  3387. operation.database_backwards("test_rmin", editor, new_state, project_state)
  3388. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  3389. # And deconstruction
  3390. definition = operation.deconstruct()
  3391. self.assertEqual(definition[0], "RemoveIndex")
  3392. self.assertEqual(definition[1], [])
  3393. self.assertEqual(definition[2], {"model_name": "Pony", "name": "pony_test_idx"})
  3394. # Also test a field dropped with index - sqlite remake issue
  3395. operations = [
  3396. migrations.RemoveIndex("Pony", "pony_test_idx"),
  3397. migrations.RemoveField("Pony", "pink"),
  3398. ]
  3399. self.assertColumnExists("test_rmin_pony", "pink")
  3400. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  3401. # Test database alteration
  3402. new_state = project_state.clone()
  3403. self.apply_operations("test_rmin", new_state, operations=operations)
  3404. self.assertColumnNotExists("test_rmin_pony", "pink")
  3405. self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"])
  3406. # And test reversal
  3407. self.unapply_operations("test_rmin", project_state, operations=operations)
  3408. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  3409. def test_rename_index(self):
  3410. app_label = "test_rnin"
  3411. project_state = self.set_up_test_model(app_label, index=True)
  3412. table_name = app_label + "_pony"
  3413. self.assertIndexNameExists(table_name, "pony_pink_idx")
  3414. self.assertIndexNameNotExists(table_name, "new_pony_test_idx")
  3415. operation = migrations.RenameIndex(
  3416. "Pony", new_name="new_pony_test_idx", old_name="pony_pink_idx"
  3417. )
  3418. self.assertEqual(
  3419. operation.describe(),
  3420. "Rename index pony_pink_idx on Pony to new_pony_test_idx",
  3421. )
  3422. self.assertEqual(
  3423. operation.migration_name_fragment,
  3424. "rename_pony_pink_idx_new_pony_test_idx",
  3425. )
  3426. new_state = project_state.clone()
  3427. operation.state_forwards(app_label, new_state)
  3428. # Rename index.
  3429. expected_queries = 1 if connection.features.can_rename_index else 2
  3430. with connection.schema_editor() as editor, self.assertNumQueries(
  3431. expected_queries
  3432. ):
  3433. operation.database_forwards(app_label, editor, project_state, new_state)
  3434. self.assertIndexNameNotExists(table_name, "pony_pink_idx")
  3435. self.assertIndexNameExists(table_name, "new_pony_test_idx")
  3436. # Reversal.
  3437. with connection.schema_editor() as editor, self.assertNumQueries(
  3438. expected_queries
  3439. ):
  3440. operation.database_backwards(app_label, editor, new_state, project_state)
  3441. self.assertIndexNameExists(table_name, "pony_pink_idx")
  3442. self.assertIndexNameNotExists(table_name, "new_pony_test_idx")
  3443. # Deconstruction.
  3444. definition = operation.deconstruct()
  3445. self.assertEqual(definition[0], "RenameIndex")
  3446. self.assertEqual(definition[1], [])
  3447. self.assertEqual(
  3448. definition[2],
  3449. {
  3450. "model_name": "Pony",
  3451. "old_name": "pony_pink_idx",
  3452. "new_name": "new_pony_test_idx",
  3453. },
  3454. )
  3455. def test_rename_index_arguments(self):
  3456. msg = "RenameIndex.old_name and old_fields are mutually exclusive."
  3457. with self.assertRaisesMessage(ValueError, msg):
  3458. migrations.RenameIndex(
  3459. "Pony",
  3460. new_name="new_idx_name",
  3461. old_name="old_idx_name",
  3462. old_fields=("weight", "pink"),
  3463. )
  3464. msg = "RenameIndex requires one of old_name and old_fields arguments to be set."
  3465. with self.assertRaisesMessage(ValueError, msg):
  3466. migrations.RenameIndex("Pony", new_name="new_idx_name")
  3467. @ignore_warnings(category=RemovedInDjango51Warning)
  3468. def test_rename_index_unnamed_index(self):
  3469. app_label = "test_rninui"
  3470. project_state = self.set_up_test_model(app_label, index_together=True)
  3471. table_name = app_label + "_pony"
  3472. self.assertIndexNameNotExists(table_name, "new_pony_test_idx")
  3473. operation = migrations.RenameIndex(
  3474. "Pony", new_name="new_pony_test_idx", old_fields=("weight", "pink")
  3475. )
  3476. self.assertEqual(
  3477. operation.describe(),
  3478. "Rename unnamed index for ('weight', 'pink') on Pony to new_pony_test_idx",
  3479. )
  3480. self.assertEqual(
  3481. operation.migration_name_fragment,
  3482. "rename_pony_weight_pink_new_pony_test_idx",
  3483. )
  3484. new_state = project_state.clone()
  3485. operation.state_forwards(app_label, new_state)
  3486. # Rename index.
  3487. with connection.schema_editor() as editor:
  3488. operation.database_forwards(app_label, editor, project_state, new_state)
  3489. self.assertIndexNameExists(table_name, "new_pony_test_idx")
  3490. # Reverse is a no-op.
  3491. with connection.schema_editor() as editor, self.assertNumQueries(0):
  3492. operation.database_backwards(app_label, editor, new_state, project_state)
  3493. self.assertIndexNameExists(table_name, "new_pony_test_idx")
  3494. # Reapply, RenameIndex operation is a noop when the old and new name
  3495. # match.
  3496. with connection.schema_editor() as editor:
  3497. operation.database_forwards(app_label, editor, new_state, project_state)
  3498. self.assertIndexNameExists(table_name, "new_pony_test_idx")
  3499. # Deconstruction.
  3500. definition = operation.deconstruct()
  3501. self.assertEqual(definition[0], "RenameIndex")
  3502. self.assertEqual(definition[1], [])
  3503. self.assertEqual(
  3504. definition[2],
  3505. {
  3506. "model_name": "Pony",
  3507. "new_name": "new_pony_test_idx",
  3508. "old_fields": ("weight", "pink"),
  3509. },
  3510. )
  3511. def test_rename_index_unknown_unnamed_index(self):
  3512. app_label = "test_rninuui"
  3513. project_state = self.set_up_test_model(app_label)
  3514. operation = migrations.RenameIndex(
  3515. "Pony", new_name="new_pony_test_idx", old_fields=("weight", "pink")
  3516. )
  3517. new_state = project_state.clone()
  3518. operation.state_forwards(app_label, new_state)
  3519. msg = "Found wrong number (0) of indexes for test_rninuui_pony(weight, pink)."
  3520. with connection.schema_editor() as editor:
  3521. with self.assertRaisesMessage(ValueError, msg):
  3522. operation.database_forwards(app_label, editor, project_state, new_state)
  3523. def test_add_index_state_forwards(self):
  3524. project_state = self.set_up_test_model("test_adinsf")
  3525. index = models.Index(fields=["pink"], name="test_adinsf_pony_pink_idx")
  3526. old_model = project_state.apps.get_model("test_adinsf", "Pony")
  3527. new_state = project_state.clone()
  3528. operation = migrations.AddIndex("Pony", index)
  3529. operation.state_forwards("test_adinsf", new_state)
  3530. new_model = new_state.apps.get_model("test_adinsf", "Pony")
  3531. self.assertIsNot(old_model, new_model)
  3532. def test_remove_index_state_forwards(self):
  3533. project_state = self.set_up_test_model("test_rminsf")
  3534. index = models.Index(fields=["pink"], name="test_rminsf_pony_pink_idx")
  3535. migrations.AddIndex("Pony", index).state_forwards("test_rminsf", project_state)
  3536. old_model = project_state.apps.get_model("test_rminsf", "Pony")
  3537. new_state = project_state.clone()
  3538. operation = migrations.RemoveIndex("Pony", "test_rminsf_pony_pink_idx")
  3539. operation.state_forwards("test_rminsf", new_state)
  3540. new_model = new_state.apps.get_model("test_rminsf", "Pony")
  3541. self.assertIsNot(old_model, new_model)
  3542. def test_rename_index_state_forwards(self):
  3543. app_label = "test_rnidsf"
  3544. project_state = self.set_up_test_model(app_label, index=True)
  3545. old_model = project_state.apps.get_model(app_label, "Pony")
  3546. new_state = project_state.clone()
  3547. operation = migrations.RenameIndex(
  3548. "Pony", new_name="new_pony_pink_idx", old_name="pony_pink_idx"
  3549. )
  3550. operation.state_forwards(app_label, new_state)
  3551. new_model = new_state.apps.get_model(app_label, "Pony")
  3552. self.assertIsNot(old_model, new_model)
  3553. self.assertEqual(new_model._meta.indexes[0].name, "new_pony_pink_idx")
  3554. @ignore_warnings(category=RemovedInDjango51Warning)
  3555. def test_rename_index_state_forwards_unnamed_index(self):
  3556. app_label = "test_rnidsfui"
  3557. project_state = self.set_up_test_model(app_label, index_together=True)
  3558. old_model = project_state.apps.get_model(app_label, "Pony")
  3559. new_state = project_state.clone()
  3560. operation = migrations.RenameIndex(
  3561. "Pony", new_name="new_pony_pink_idx", old_fields=("weight", "pink")
  3562. )
  3563. operation.state_forwards(app_label, new_state)
  3564. new_model = new_state.apps.get_model(app_label, "Pony")
  3565. self.assertIsNot(old_model, new_model)
  3566. self.assertEqual(new_model._meta.index_together, tuple())
  3567. self.assertEqual(new_model._meta.indexes[0].name, "new_pony_pink_idx")
  3568. @skipUnlessDBFeature("supports_expression_indexes")
  3569. def test_add_func_index(self):
  3570. app_label = "test_addfuncin"
  3571. index_name = f"{app_label}_pony_abs_idx"
  3572. table_name = f"{app_label}_pony"
  3573. project_state = self.set_up_test_model(app_label)
  3574. index = models.Index(Abs("weight"), name=index_name)
  3575. operation = migrations.AddIndex("Pony", index)
  3576. self.assertEqual(
  3577. operation.describe(),
  3578. "Create index test_addfuncin_pony_abs_idx on Abs(F(weight)) on model Pony",
  3579. )
  3580. self.assertEqual(
  3581. operation.migration_name_fragment,
  3582. "pony_test_addfuncin_pony_abs_idx",
  3583. )
  3584. new_state = project_state.clone()
  3585. operation.state_forwards(app_label, new_state)
  3586. self.assertEqual(len(new_state.models[app_label, "pony"].options["indexes"]), 1)
  3587. self.assertIndexNameNotExists(table_name, index_name)
  3588. # Add index.
  3589. with connection.schema_editor() as editor:
  3590. operation.database_forwards(app_label, editor, project_state, new_state)
  3591. self.assertIndexNameExists(table_name, index_name)
  3592. # Reversal.
  3593. with connection.schema_editor() as editor:
  3594. operation.database_backwards(app_label, editor, new_state, project_state)
  3595. self.assertIndexNameNotExists(table_name, index_name)
  3596. # Deconstruction.
  3597. definition = operation.deconstruct()
  3598. self.assertEqual(definition[0], "AddIndex")
  3599. self.assertEqual(definition[1], [])
  3600. self.assertEqual(definition[2], {"model_name": "Pony", "index": index})
  3601. @skipUnlessDBFeature("supports_expression_indexes")
  3602. def test_remove_func_index(self):
  3603. app_label = "test_rmfuncin"
  3604. index_name = f"{app_label}_pony_abs_idx"
  3605. table_name = f"{app_label}_pony"
  3606. project_state = self.set_up_test_model(
  3607. app_label,
  3608. indexes=[
  3609. models.Index(Abs("weight"), name=index_name),
  3610. ],
  3611. )
  3612. self.assertTableExists(table_name)
  3613. self.assertIndexNameExists(table_name, index_name)
  3614. operation = migrations.RemoveIndex("Pony", index_name)
  3615. self.assertEqual(
  3616. operation.describe(),
  3617. "Remove index test_rmfuncin_pony_abs_idx from Pony",
  3618. )
  3619. self.assertEqual(
  3620. operation.migration_name_fragment,
  3621. "remove_pony_test_rmfuncin_pony_abs_idx",
  3622. )
  3623. new_state = project_state.clone()
  3624. operation.state_forwards(app_label, new_state)
  3625. self.assertEqual(len(new_state.models[app_label, "pony"].options["indexes"]), 0)
  3626. # Remove index.
  3627. with connection.schema_editor() as editor:
  3628. operation.database_forwards(app_label, editor, project_state, new_state)
  3629. self.assertIndexNameNotExists(table_name, index_name)
  3630. # Reversal.
  3631. with connection.schema_editor() as editor:
  3632. operation.database_backwards(app_label, editor, new_state, project_state)
  3633. self.assertIndexNameExists(table_name, index_name)
  3634. # Deconstruction.
  3635. definition = operation.deconstruct()
  3636. self.assertEqual(definition[0], "RemoveIndex")
  3637. self.assertEqual(definition[1], [])
  3638. self.assertEqual(definition[2], {"model_name": "Pony", "name": index_name})
  3639. @skipUnlessDBFeature("supports_expression_indexes")
  3640. def test_alter_field_with_func_index(self):
  3641. app_label = "test_alfuncin"
  3642. index_name = f"{app_label}_pony_idx"
  3643. table_name = f"{app_label}_pony"
  3644. project_state = self.set_up_test_model(
  3645. app_label,
  3646. indexes=[models.Index(Abs("pink"), name=index_name)],
  3647. )
  3648. operation = migrations.AlterField(
  3649. "Pony", "pink", models.IntegerField(null=True)
  3650. )
  3651. new_state = project_state.clone()
  3652. operation.state_forwards(app_label, new_state)
  3653. with connection.schema_editor() as editor:
  3654. operation.database_forwards(app_label, editor, project_state, new_state)
  3655. self.assertIndexNameExists(table_name, index_name)
  3656. with connection.schema_editor() as editor:
  3657. operation.database_backwards(app_label, editor, new_state, project_state)
  3658. self.assertIndexNameExists(table_name, index_name)
  3659. def test_alter_field_with_index(self):
  3660. """
  3661. Test AlterField operation with an index to ensure indexes created via
  3662. Meta.indexes don't get dropped with sqlite3 remake.
  3663. """
  3664. project_state = self.set_up_test_model("test_alflin", index=True)
  3665. operation = migrations.AlterField(
  3666. "Pony", "pink", models.IntegerField(null=True)
  3667. )
  3668. new_state = project_state.clone()
  3669. operation.state_forwards("test_alflin", new_state)
  3670. # Test the database alteration
  3671. self.assertColumnNotNull("test_alflin_pony", "pink")
  3672. with connection.schema_editor() as editor:
  3673. operation.database_forwards("test_alflin", editor, project_state, new_state)
  3674. # Index hasn't been dropped
  3675. self.assertIndexExists("test_alflin_pony", ["pink"])
  3676. # And test reversal
  3677. with connection.schema_editor() as editor:
  3678. operation.database_backwards(
  3679. "test_alflin", editor, new_state, project_state
  3680. )
  3681. # Ensure the index is still there
  3682. self.assertIndexExists("test_alflin_pony", ["pink"])
  3683. @ignore_warnings(category=RemovedInDjango51Warning)
  3684. def test_alter_index_together(self):
  3685. """
  3686. Tests the AlterIndexTogether operation.
  3687. """
  3688. project_state = self.set_up_test_model("test_alinto")
  3689. # Test the state alteration
  3690. operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")])
  3691. self.assertEqual(
  3692. operation.describe(), "Alter index_together for Pony (1 constraint(s))"
  3693. )
  3694. self.assertEqual(
  3695. operation.migration_name_fragment,
  3696. "alter_pony_index_together",
  3697. )
  3698. new_state = project_state.clone()
  3699. operation.state_forwards("test_alinto", new_state)
  3700. self.assertEqual(
  3701. len(
  3702. project_state.models["test_alinto", "pony"].options.get(
  3703. "index_together", set()
  3704. )
  3705. ),
  3706. 0,
  3707. )
  3708. self.assertEqual(
  3709. len(
  3710. new_state.models["test_alinto", "pony"].options.get(
  3711. "index_together", set()
  3712. )
  3713. ),
  3714. 1,
  3715. )
  3716. # Make sure there's no matching index
  3717. self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"])
  3718. # Test the database alteration
  3719. with connection.schema_editor() as editor:
  3720. operation.database_forwards("test_alinto", editor, project_state, new_state)
  3721. self.assertIndexExists("test_alinto_pony", ["pink", "weight"])
  3722. # And test reversal
  3723. with connection.schema_editor() as editor:
  3724. operation.database_backwards(
  3725. "test_alinto", editor, new_state, project_state
  3726. )
  3727. self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"])
  3728. # And deconstruction
  3729. definition = operation.deconstruct()
  3730. self.assertEqual(definition[0], "AlterIndexTogether")
  3731. self.assertEqual(definition[1], [])
  3732. self.assertEqual(
  3733. definition[2], {"name": "Pony", "index_together": {("pink", "weight")}}
  3734. )
  3735. def test_alter_index_together_remove(self):
  3736. operation = migrations.AlterIndexTogether("Pony", None)
  3737. self.assertEqual(
  3738. operation.describe(), "Alter index_together for Pony (0 constraint(s))"
  3739. )
  3740. @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields")
  3741. @ignore_warnings(category=RemovedInDjango51Warning)
  3742. def test_alter_index_together_remove_with_unique_together(self):
  3743. app_label = "test_alintoremove_wunto"
  3744. table_name = "%s_pony" % app_label
  3745. project_state = self.set_up_test_model(app_label, unique_together=True)
  3746. self.assertUniqueConstraintExists(table_name, ["pink", "weight"])
  3747. # Add index together.
  3748. new_state = project_state.clone()
  3749. operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")])
  3750. operation.state_forwards(app_label, new_state)
  3751. with connection.schema_editor() as editor:
  3752. operation.database_forwards(app_label, editor, project_state, new_state)
  3753. self.assertIndexExists(table_name, ["pink", "weight"])
  3754. # Remove index together.
  3755. project_state = new_state
  3756. new_state = project_state.clone()
  3757. operation = migrations.AlterIndexTogether("Pony", set())
  3758. operation.state_forwards(app_label, new_state)
  3759. with connection.schema_editor() as editor:
  3760. operation.database_forwards(app_label, editor, project_state, new_state)
  3761. self.assertIndexNotExists(table_name, ["pink", "weight"])
  3762. self.assertUniqueConstraintExists(table_name, ["pink", "weight"])
  3763. def test_add_constraint(self):
  3764. project_state = self.set_up_test_model("test_addconstraint")
  3765. gt_check = models.Q(pink__gt=2)
  3766. gt_constraint = models.CheckConstraint(
  3767. check=gt_check, name="test_add_constraint_pony_pink_gt_2"
  3768. )
  3769. gt_operation = migrations.AddConstraint("Pony", gt_constraint)
  3770. self.assertEqual(
  3771. gt_operation.describe(),
  3772. "Create constraint test_add_constraint_pony_pink_gt_2 on model Pony",
  3773. )
  3774. self.assertEqual(
  3775. gt_operation.migration_name_fragment,
  3776. "pony_test_add_constraint_pony_pink_gt_2",
  3777. )
  3778. # Test the state alteration
  3779. new_state = project_state.clone()
  3780. gt_operation.state_forwards("test_addconstraint", new_state)
  3781. self.assertEqual(
  3782. len(new_state.models["test_addconstraint", "pony"].options["constraints"]),
  3783. 1,
  3784. )
  3785. Pony = new_state.apps.get_model("test_addconstraint", "Pony")
  3786. self.assertEqual(len(Pony._meta.constraints), 1)
  3787. # Test the database alteration
  3788. with (
  3789. CaptureQueriesContext(connection) as ctx,
  3790. connection.schema_editor() as editor,
  3791. ):
  3792. gt_operation.database_forwards(
  3793. "test_addconstraint", editor, project_state, new_state
  3794. )
  3795. if connection.features.supports_table_check_constraints:
  3796. with self.assertRaises(IntegrityError), transaction.atomic():
  3797. Pony.objects.create(pink=1, weight=1.0)
  3798. else:
  3799. self.assertIs(
  3800. any("CHECK" in query["sql"] for query in ctx.captured_queries), False
  3801. )
  3802. Pony.objects.create(pink=1, weight=1.0)
  3803. # Add another one.
  3804. lt_check = models.Q(pink__lt=100)
  3805. lt_constraint = models.CheckConstraint(
  3806. check=lt_check, name="test_add_constraint_pony_pink_lt_100"
  3807. )
  3808. lt_operation = migrations.AddConstraint("Pony", lt_constraint)
  3809. lt_operation.state_forwards("test_addconstraint", new_state)
  3810. self.assertEqual(
  3811. len(new_state.models["test_addconstraint", "pony"].options["constraints"]),
  3812. 2,
  3813. )
  3814. Pony = new_state.apps.get_model("test_addconstraint", "Pony")
  3815. self.assertEqual(len(Pony._meta.constraints), 2)
  3816. with (
  3817. CaptureQueriesContext(connection) as ctx,
  3818. connection.schema_editor() as editor,
  3819. ):
  3820. lt_operation.database_forwards(
  3821. "test_addconstraint", editor, project_state, new_state
  3822. )
  3823. if connection.features.supports_table_check_constraints:
  3824. with self.assertRaises(IntegrityError), transaction.atomic():
  3825. Pony.objects.create(pink=100, weight=1.0)
  3826. else:
  3827. self.assertIs(
  3828. any("CHECK" in query["sql"] for query in ctx.captured_queries), False
  3829. )
  3830. Pony.objects.create(pink=100, weight=1.0)
  3831. # Test reversal
  3832. with connection.schema_editor() as editor:
  3833. gt_operation.database_backwards(
  3834. "test_addconstraint", editor, new_state, project_state
  3835. )
  3836. Pony.objects.create(pink=1, weight=1.0)
  3837. # Test deconstruction
  3838. definition = gt_operation.deconstruct()
  3839. self.assertEqual(definition[0], "AddConstraint")
  3840. self.assertEqual(definition[1], [])
  3841. self.assertEqual(
  3842. definition[2], {"model_name": "Pony", "constraint": gt_constraint}
  3843. )
  3844. @skipUnlessDBFeature("supports_table_check_constraints")
  3845. def test_add_constraint_percent_escaping(self):
  3846. app_label = "add_constraint_string_quoting"
  3847. operations = [
  3848. migrations.CreateModel(
  3849. "Author",
  3850. fields=[
  3851. ("id", models.AutoField(primary_key=True)),
  3852. ("name", models.CharField(max_length=100)),
  3853. ("surname", models.CharField(max_length=100, default="")),
  3854. ("rebate", models.CharField(max_length=100)),
  3855. ],
  3856. ),
  3857. ]
  3858. from_state = self.apply_operations(app_label, ProjectState(), operations)
  3859. checks = [
  3860. # "%" generated in startswith lookup should be escaped in a way
  3861. # that is considered a leading wildcard.
  3862. (
  3863. models.Q(name__startswith="Albert"),
  3864. {"name": "Alberta"},
  3865. {"name": "Artur"},
  3866. ),
  3867. # Literal "%" should be escaped in a way that is not a considered a
  3868. # wildcard.
  3869. (models.Q(rebate__endswith="%"), {"rebate": "10%"}, {"rebate": "10%$"}),
  3870. # Right-hand-side baked "%" literals should not be used for
  3871. # parameters interpolation.
  3872. (
  3873. ~models.Q(surname__startswith=models.F("name")),
  3874. {"name": "Albert"},
  3875. {"name": "Albert", "surname": "Alberto"},
  3876. ),
  3877. # Exact matches against "%" literals should also be supported.
  3878. (
  3879. models.Q(name="%"),
  3880. {"name": "%"},
  3881. {"name": "Albert"},
  3882. ),
  3883. ]
  3884. for check, valid, invalid in checks:
  3885. with self.subTest(check=check, valid=valid, invalid=invalid):
  3886. constraint = models.CheckConstraint(check=check, name="constraint")
  3887. operation = migrations.AddConstraint("Author", constraint)
  3888. to_state = from_state.clone()
  3889. operation.state_forwards(app_label, to_state)
  3890. with connection.schema_editor() as editor:
  3891. operation.database_forwards(app_label, editor, from_state, to_state)
  3892. Author = to_state.apps.get_model(app_label, "Author")
  3893. try:
  3894. with transaction.atomic():
  3895. Author.objects.create(**valid).delete()
  3896. with self.assertRaises(IntegrityError), transaction.atomic():
  3897. Author.objects.create(**invalid)
  3898. finally:
  3899. with connection.schema_editor() as editor:
  3900. operation.database_backwards(
  3901. app_label, editor, from_state, to_state
  3902. )
  3903. @skipUnlessDBFeature("supports_table_check_constraints")
  3904. def test_add_or_constraint(self):
  3905. app_label = "test_addorconstraint"
  3906. constraint_name = "add_constraint_or"
  3907. from_state = self.set_up_test_model(app_label)
  3908. check = models.Q(pink__gt=2, weight__gt=2) | models.Q(weight__lt=0)
  3909. constraint = models.CheckConstraint(check=check, name=constraint_name)
  3910. operation = migrations.AddConstraint("Pony", constraint)
  3911. to_state = from_state.clone()
  3912. operation.state_forwards(app_label, to_state)
  3913. with connection.schema_editor() as editor:
  3914. operation.database_forwards(app_label, editor, from_state, to_state)
  3915. Pony = to_state.apps.get_model(app_label, "Pony")
  3916. with self.assertRaises(IntegrityError), transaction.atomic():
  3917. Pony.objects.create(pink=2, weight=3.0)
  3918. with self.assertRaises(IntegrityError), transaction.atomic():
  3919. Pony.objects.create(pink=3, weight=1.0)
  3920. Pony.objects.bulk_create(
  3921. [
  3922. Pony(pink=3, weight=-1.0),
  3923. Pony(pink=1, weight=-1.0),
  3924. Pony(pink=3, weight=3.0),
  3925. ]
  3926. )
  3927. @skipUnlessDBFeature("supports_table_check_constraints")
  3928. def test_add_constraint_combinable(self):
  3929. app_label = "test_addconstraint_combinable"
  3930. operations = [
  3931. migrations.CreateModel(
  3932. "Book",
  3933. fields=[
  3934. ("id", models.AutoField(primary_key=True)),
  3935. ("read", models.PositiveIntegerField()),
  3936. ("unread", models.PositiveIntegerField()),
  3937. ],
  3938. ),
  3939. ]
  3940. from_state = self.apply_operations(app_label, ProjectState(), operations)
  3941. constraint = models.CheckConstraint(
  3942. check=models.Q(read=(100 - models.F("unread"))),
  3943. name="test_addconstraint_combinable_sum_100",
  3944. )
  3945. operation = migrations.AddConstraint("Book", constraint)
  3946. to_state = from_state.clone()
  3947. operation.state_forwards(app_label, to_state)
  3948. with connection.schema_editor() as editor:
  3949. operation.database_forwards(app_label, editor, from_state, to_state)
  3950. Book = to_state.apps.get_model(app_label, "Book")
  3951. with self.assertRaises(IntegrityError), transaction.atomic():
  3952. Book.objects.create(read=70, unread=10)
  3953. Book.objects.create(read=70, unread=30)
  3954. def test_remove_constraint(self):
  3955. project_state = self.set_up_test_model(
  3956. "test_removeconstraint",
  3957. constraints=[
  3958. models.CheckConstraint(
  3959. check=models.Q(pink__gt=2),
  3960. name="test_remove_constraint_pony_pink_gt_2",
  3961. ),
  3962. models.CheckConstraint(
  3963. check=models.Q(pink__lt=100),
  3964. name="test_remove_constraint_pony_pink_lt_100",
  3965. ),
  3966. ],
  3967. )
  3968. gt_operation = migrations.RemoveConstraint(
  3969. "Pony", "test_remove_constraint_pony_pink_gt_2"
  3970. )
  3971. self.assertEqual(
  3972. gt_operation.describe(),
  3973. "Remove constraint test_remove_constraint_pony_pink_gt_2 from model Pony",
  3974. )
  3975. self.assertEqual(
  3976. gt_operation.migration_name_fragment,
  3977. "remove_pony_test_remove_constraint_pony_pink_gt_2",
  3978. )
  3979. # Test state alteration
  3980. new_state = project_state.clone()
  3981. gt_operation.state_forwards("test_removeconstraint", new_state)
  3982. self.assertEqual(
  3983. len(
  3984. new_state.models["test_removeconstraint", "pony"].options["constraints"]
  3985. ),
  3986. 1,
  3987. )
  3988. Pony = new_state.apps.get_model("test_removeconstraint", "Pony")
  3989. self.assertEqual(len(Pony._meta.constraints), 1)
  3990. # Test database alteration
  3991. with connection.schema_editor() as editor:
  3992. gt_operation.database_forwards(
  3993. "test_removeconstraint", editor, project_state, new_state
  3994. )
  3995. Pony.objects.create(pink=1, weight=1.0).delete()
  3996. if connection.features.supports_table_check_constraints:
  3997. with self.assertRaises(IntegrityError), transaction.atomic():
  3998. Pony.objects.create(pink=100, weight=1.0)
  3999. else:
  4000. Pony.objects.create(pink=100, weight=1.0)
  4001. # Remove the other one.
  4002. lt_operation = migrations.RemoveConstraint(
  4003. "Pony", "test_remove_constraint_pony_pink_lt_100"
  4004. )
  4005. lt_operation.state_forwards("test_removeconstraint", new_state)
  4006. self.assertEqual(
  4007. len(
  4008. new_state.models["test_removeconstraint", "pony"].options["constraints"]
  4009. ),
  4010. 0,
  4011. )
  4012. Pony = new_state.apps.get_model("test_removeconstraint", "Pony")
  4013. self.assertEqual(len(Pony._meta.constraints), 0)
  4014. with connection.schema_editor() as editor:
  4015. lt_operation.database_forwards(
  4016. "test_removeconstraint", editor, project_state, new_state
  4017. )
  4018. Pony.objects.create(pink=100, weight=1.0).delete()
  4019. # Test reversal
  4020. with connection.schema_editor() as editor:
  4021. gt_operation.database_backwards(
  4022. "test_removeconstraint", editor, new_state, project_state
  4023. )
  4024. if connection.features.supports_table_check_constraints:
  4025. with self.assertRaises(IntegrityError), transaction.atomic():
  4026. Pony.objects.create(pink=1, weight=1.0)
  4027. else:
  4028. Pony.objects.create(pink=1, weight=1.0)
  4029. # Test deconstruction
  4030. definition = gt_operation.deconstruct()
  4031. self.assertEqual(definition[0], "RemoveConstraint")
  4032. self.assertEqual(definition[1], [])
  4033. self.assertEqual(
  4034. definition[2],
  4035. {"model_name": "Pony", "name": "test_remove_constraint_pony_pink_gt_2"},
  4036. )
  4037. def test_add_partial_unique_constraint(self):
  4038. project_state = self.set_up_test_model("test_addpartialuniqueconstraint")
  4039. partial_unique_constraint = models.UniqueConstraint(
  4040. fields=["pink"],
  4041. condition=models.Q(weight__gt=5),
  4042. name="test_constraint_pony_pink_for_weight_gt_5_uniq",
  4043. )
  4044. operation = migrations.AddConstraint("Pony", partial_unique_constraint)
  4045. self.assertEqual(
  4046. operation.describe(),
  4047. "Create constraint test_constraint_pony_pink_for_weight_gt_5_uniq "
  4048. "on model Pony",
  4049. )
  4050. # Test the state alteration
  4051. new_state = project_state.clone()
  4052. operation.state_forwards("test_addpartialuniqueconstraint", new_state)
  4053. self.assertEqual(
  4054. len(
  4055. new_state.models["test_addpartialuniqueconstraint", "pony"].options[
  4056. "constraints"
  4057. ]
  4058. ),
  4059. 1,
  4060. )
  4061. Pony = new_state.apps.get_model("test_addpartialuniqueconstraint", "Pony")
  4062. self.assertEqual(len(Pony._meta.constraints), 1)
  4063. # Test the database alteration
  4064. with connection.schema_editor() as editor:
  4065. operation.database_forwards(
  4066. "test_addpartialuniqueconstraint", editor, project_state, new_state
  4067. )
  4068. # Test constraint works
  4069. Pony.objects.create(pink=1, weight=4.0)
  4070. Pony.objects.create(pink=1, weight=4.0)
  4071. Pony.objects.create(pink=1, weight=6.0)
  4072. if connection.features.supports_partial_indexes:
  4073. with self.assertRaises(IntegrityError), transaction.atomic():
  4074. Pony.objects.create(pink=1, weight=7.0)
  4075. else:
  4076. Pony.objects.create(pink=1, weight=7.0)
  4077. # Test reversal
  4078. with connection.schema_editor() as editor:
  4079. operation.database_backwards(
  4080. "test_addpartialuniqueconstraint", editor, new_state, project_state
  4081. )
  4082. # Test constraint doesn't work
  4083. Pony.objects.create(pink=1, weight=7.0)
  4084. # Test deconstruction
  4085. definition = operation.deconstruct()
  4086. self.assertEqual(definition[0], "AddConstraint")
  4087. self.assertEqual(definition[1], [])
  4088. self.assertEqual(
  4089. definition[2],
  4090. {"model_name": "Pony", "constraint": partial_unique_constraint},
  4091. )
  4092. def test_remove_partial_unique_constraint(self):
  4093. project_state = self.set_up_test_model(
  4094. "test_removepartialuniqueconstraint",
  4095. constraints=[
  4096. models.UniqueConstraint(
  4097. fields=["pink"],
  4098. condition=models.Q(weight__gt=5),
  4099. name="test_constraint_pony_pink_for_weight_gt_5_uniq",
  4100. ),
  4101. ],
  4102. )
  4103. gt_operation = migrations.RemoveConstraint(
  4104. "Pony", "test_constraint_pony_pink_for_weight_gt_5_uniq"
  4105. )
  4106. self.assertEqual(
  4107. gt_operation.describe(),
  4108. "Remove constraint test_constraint_pony_pink_for_weight_gt_5_uniq from "
  4109. "model Pony",
  4110. )
  4111. # Test state alteration
  4112. new_state = project_state.clone()
  4113. gt_operation.state_forwards("test_removepartialuniqueconstraint", new_state)
  4114. self.assertEqual(
  4115. len(
  4116. new_state.models["test_removepartialuniqueconstraint", "pony"].options[
  4117. "constraints"
  4118. ]
  4119. ),
  4120. 0,
  4121. )
  4122. Pony = new_state.apps.get_model("test_removepartialuniqueconstraint", "Pony")
  4123. self.assertEqual(len(Pony._meta.constraints), 0)
  4124. # Test database alteration
  4125. with connection.schema_editor() as editor:
  4126. gt_operation.database_forwards(
  4127. "test_removepartialuniqueconstraint", editor, project_state, new_state
  4128. )
  4129. # Test constraint doesn't work
  4130. Pony.objects.create(pink=1, weight=4.0)
  4131. Pony.objects.create(pink=1, weight=4.0)
  4132. Pony.objects.create(pink=1, weight=6.0)
  4133. Pony.objects.create(pink=1, weight=7.0).delete()
  4134. # Test reversal
  4135. with connection.schema_editor() as editor:
  4136. gt_operation.database_backwards(
  4137. "test_removepartialuniqueconstraint", editor, new_state, project_state
  4138. )
  4139. # Test constraint works
  4140. if connection.features.supports_partial_indexes:
  4141. with self.assertRaises(IntegrityError), transaction.atomic():
  4142. Pony.objects.create(pink=1, weight=7.0)
  4143. else:
  4144. Pony.objects.create(pink=1, weight=7.0)
  4145. # Test deconstruction
  4146. definition = gt_operation.deconstruct()
  4147. self.assertEqual(definition[0], "RemoveConstraint")
  4148. self.assertEqual(definition[1], [])
  4149. self.assertEqual(
  4150. definition[2],
  4151. {
  4152. "model_name": "Pony",
  4153. "name": "test_constraint_pony_pink_for_weight_gt_5_uniq",
  4154. },
  4155. )
  4156. def test_add_deferred_unique_constraint(self):
  4157. app_label = "test_adddeferred_uc"
  4158. project_state = self.set_up_test_model(app_label)
  4159. deferred_unique_constraint = models.UniqueConstraint(
  4160. fields=["pink"],
  4161. name="deferred_pink_constraint_add",
  4162. deferrable=models.Deferrable.DEFERRED,
  4163. )
  4164. operation = migrations.AddConstraint("Pony", deferred_unique_constraint)
  4165. self.assertEqual(
  4166. operation.describe(),
  4167. "Create constraint deferred_pink_constraint_add on model Pony",
  4168. )
  4169. # Add constraint.
  4170. new_state = project_state.clone()
  4171. operation.state_forwards(app_label, new_state)
  4172. self.assertEqual(
  4173. len(new_state.models[app_label, "pony"].options["constraints"]), 1
  4174. )
  4175. Pony = new_state.apps.get_model(app_label, "Pony")
  4176. self.assertEqual(len(Pony._meta.constraints), 1)
  4177. with connection.schema_editor() as editor, CaptureQueriesContext(
  4178. connection
  4179. ) as ctx:
  4180. operation.database_forwards(app_label, editor, project_state, new_state)
  4181. Pony.objects.create(pink=1, weight=4.0)
  4182. if connection.features.supports_deferrable_unique_constraints:
  4183. # Unique constraint is deferred.
  4184. with transaction.atomic():
  4185. obj = Pony.objects.create(pink=1, weight=4.0)
  4186. obj.pink = 2
  4187. obj.save()
  4188. # Constraint behavior can be changed with SET CONSTRAINTS.
  4189. with self.assertRaises(IntegrityError):
  4190. with transaction.atomic(), connection.cursor() as cursor:
  4191. quoted_name = connection.ops.quote_name(
  4192. deferred_unique_constraint.name
  4193. )
  4194. cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name)
  4195. obj = Pony.objects.create(pink=1, weight=4.0)
  4196. obj.pink = 3
  4197. obj.save()
  4198. else:
  4199. self.assertEqual(len(ctx), 0)
  4200. Pony.objects.create(pink=1, weight=4.0)
  4201. # Reversal.
  4202. with connection.schema_editor() as editor:
  4203. operation.database_backwards(app_label, editor, new_state, project_state)
  4204. # Constraint doesn't work.
  4205. Pony.objects.create(pink=1, weight=4.0)
  4206. # Deconstruction.
  4207. definition = operation.deconstruct()
  4208. self.assertEqual(definition[0], "AddConstraint")
  4209. self.assertEqual(definition[1], [])
  4210. self.assertEqual(
  4211. definition[2],
  4212. {"model_name": "Pony", "constraint": deferred_unique_constraint},
  4213. )
  4214. def test_remove_deferred_unique_constraint(self):
  4215. app_label = "test_removedeferred_uc"
  4216. deferred_unique_constraint = models.UniqueConstraint(
  4217. fields=["pink"],
  4218. name="deferred_pink_constraint_rm",
  4219. deferrable=models.Deferrable.DEFERRED,
  4220. )
  4221. project_state = self.set_up_test_model(
  4222. app_label, constraints=[deferred_unique_constraint]
  4223. )
  4224. operation = migrations.RemoveConstraint("Pony", deferred_unique_constraint.name)
  4225. self.assertEqual(
  4226. operation.describe(),
  4227. "Remove constraint deferred_pink_constraint_rm from model Pony",
  4228. )
  4229. # Remove constraint.
  4230. new_state = project_state.clone()
  4231. operation.state_forwards(app_label, new_state)
  4232. self.assertEqual(
  4233. len(new_state.models[app_label, "pony"].options["constraints"]), 0
  4234. )
  4235. Pony = new_state.apps.get_model(app_label, "Pony")
  4236. self.assertEqual(len(Pony._meta.constraints), 0)
  4237. with connection.schema_editor() as editor, CaptureQueriesContext(
  4238. connection
  4239. ) as ctx:
  4240. operation.database_forwards(app_label, editor, project_state, new_state)
  4241. # Constraint doesn't work.
  4242. Pony.objects.create(pink=1, weight=4.0)
  4243. Pony.objects.create(pink=1, weight=4.0).delete()
  4244. if not connection.features.supports_deferrable_unique_constraints:
  4245. self.assertEqual(len(ctx), 0)
  4246. # Reversal.
  4247. with connection.schema_editor() as editor:
  4248. operation.database_backwards(app_label, editor, new_state, project_state)
  4249. if connection.features.supports_deferrable_unique_constraints:
  4250. # Unique constraint is deferred.
  4251. with transaction.atomic():
  4252. obj = Pony.objects.create(pink=1, weight=4.0)
  4253. obj.pink = 2
  4254. obj.save()
  4255. # Constraint behavior can be changed with SET CONSTRAINTS.
  4256. with self.assertRaises(IntegrityError):
  4257. with transaction.atomic(), connection.cursor() as cursor:
  4258. quoted_name = connection.ops.quote_name(
  4259. deferred_unique_constraint.name
  4260. )
  4261. cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name)
  4262. obj = Pony.objects.create(pink=1, weight=4.0)
  4263. obj.pink = 3
  4264. obj.save()
  4265. else:
  4266. Pony.objects.create(pink=1, weight=4.0)
  4267. # Deconstruction.
  4268. definition = operation.deconstruct()
  4269. self.assertEqual(definition[0], "RemoveConstraint")
  4270. self.assertEqual(definition[1], [])
  4271. self.assertEqual(
  4272. definition[2],
  4273. {
  4274. "model_name": "Pony",
  4275. "name": "deferred_pink_constraint_rm",
  4276. },
  4277. )
  4278. def test_add_covering_unique_constraint(self):
  4279. app_label = "test_addcovering_uc"
  4280. project_state = self.set_up_test_model(app_label)
  4281. covering_unique_constraint = models.UniqueConstraint(
  4282. fields=["pink"],
  4283. name="covering_pink_constraint_add",
  4284. include=["weight"],
  4285. )
  4286. operation = migrations.AddConstraint("Pony", covering_unique_constraint)
  4287. self.assertEqual(
  4288. operation.describe(),
  4289. "Create constraint covering_pink_constraint_add on model Pony",
  4290. )
  4291. # Add constraint.
  4292. new_state = project_state.clone()
  4293. operation.state_forwards(app_label, new_state)
  4294. self.assertEqual(
  4295. len(new_state.models[app_label, "pony"].options["constraints"]), 1
  4296. )
  4297. Pony = new_state.apps.get_model(app_label, "Pony")
  4298. self.assertEqual(len(Pony._meta.constraints), 1)
  4299. with connection.schema_editor() as editor, CaptureQueriesContext(
  4300. connection
  4301. ) as ctx:
  4302. operation.database_forwards(app_label, editor, project_state, new_state)
  4303. Pony.objects.create(pink=1, weight=4.0)
  4304. if connection.features.supports_covering_indexes:
  4305. with self.assertRaises(IntegrityError):
  4306. Pony.objects.create(pink=1, weight=4.0)
  4307. else:
  4308. self.assertEqual(len(ctx), 0)
  4309. Pony.objects.create(pink=1, weight=4.0)
  4310. # Reversal.
  4311. with connection.schema_editor() as editor:
  4312. operation.database_backwards(app_label, editor, new_state, project_state)
  4313. # Constraint doesn't work.
  4314. Pony.objects.create(pink=1, weight=4.0)
  4315. # Deconstruction.
  4316. definition = operation.deconstruct()
  4317. self.assertEqual(definition[0], "AddConstraint")
  4318. self.assertEqual(definition[1], [])
  4319. self.assertEqual(
  4320. definition[2],
  4321. {"model_name": "Pony", "constraint": covering_unique_constraint},
  4322. )
  4323. def test_remove_covering_unique_constraint(self):
  4324. app_label = "test_removecovering_uc"
  4325. covering_unique_constraint = models.UniqueConstraint(
  4326. fields=["pink"],
  4327. name="covering_pink_constraint_rm",
  4328. include=["weight"],
  4329. )
  4330. project_state = self.set_up_test_model(
  4331. app_label, constraints=[covering_unique_constraint]
  4332. )
  4333. operation = migrations.RemoveConstraint("Pony", covering_unique_constraint.name)
  4334. self.assertEqual(
  4335. operation.describe(),
  4336. "Remove constraint covering_pink_constraint_rm from model Pony",
  4337. )
  4338. # Remove constraint.
  4339. new_state = project_state.clone()
  4340. operation.state_forwards(app_label, new_state)
  4341. self.assertEqual(
  4342. len(new_state.models[app_label, "pony"].options["constraints"]), 0
  4343. )
  4344. Pony = new_state.apps.get_model(app_label, "Pony")
  4345. self.assertEqual(len(Pony._meta.constraints), 0)
  4346. with connection.schema_editor() as editor, CaptureQueriesContext(
  4347. connection
  4348. ) as ctx:
  4349. operation.database_forwards(app_label, editor, project_state, new_state)
  4350. # Constraint doesn't work.
  4351. Pony.objects.create(pink=1, weight=4.0)
  4352. Pony.objects.create(pink=1, weight=4.0).delete()
  4353. if not connection.features.supports_covering_indexes:
  4354. self.assertEqual(len(ctx), 0)
  4355. # Reversal.
  4356. with connection.schema_editor() as editor:
  4357. operation.database_backwards(app_label, editor, new_state, project_state)
  4358. if connection.features.supports_covering_indexes:
  4359. with self.assertRaises(IntegrityError):
  4360. Pony.objects.create(pink=1, weight=4.0)
  4361. else:
  4362. Pony.objects.create(pink=1, weight=4.0)
  4363. # Deconstruction.
  4364. definition = operation.deconstruct()
  4365. self.assertEqual(definition[0], "RemoveConstraint")
  4366. self.assertEqual(definition[1], [])
  4367. self.assertEqual(
  4368. definition[2],
  4369. {
  4370. "model_name": "Pony",
  4371. "name": "covering_pink_constraint_rm",
  4372. },
  4373. )
  4374. def test_alter_field_with_func_unique_constraint(self):
  4375. app_label = "test_alfuncuc"
  4376. constraint_name = f"{app_label}_pony_uq"
  4377. table_name = f"{app_label}_pony"
  4378. project_state = self.set_up_test_model(
  4379. app_label,
  4380. constraints=[
  4381. models.UniqueConstraint("pink", "weight", name=constraint_name)
  4382. ],
  4383. )
  4384. operation = migrations.AlterField(
  4385. "Pony", "pink", models.IntegerField(null=True)
  4386. )
  4387. new_state = project_state.clone()
  4388. operation.state_forwards(app_label, new_state)
  4389. with connection.schema_editor() as editor:
  4390. operation.database_forwards(app_label, editor, project_state, new_state)
  4391. if connection.features.supports_expression_indexes:
  4392. self.assertIndexNameExists(table_name, constraint_name)
  4393. with connection.schema_editor() as editor:
  4394. operation.database_backwards(app_label, editor, new_state, project_state)
  4395. if connection.features.supports_expression_indexes:
  4396. self.assertIndexNameExists(table_name, constraint_name)
  4397. def test_add_func_unique_constraint(self):
  4398. app_label = "test_adfuncuc"
  4399. constraint_name = f"{app_label}_pony_abs_uq"
  4400. table_name = f"{app_label}_pony"
  4401. project_state = self.set_up_test_model(app_label)
  4402. constraint = models.UniqueConstraint(Abs("weight"), name=constraint_name)
  4403. operation = migrations.AddConstraint("Pony", constraint)
  4404. self.assertEqual(
  4405. operation.describe(),
  4406. "Create constraint test_adfuncuc_pony_abs_uq on model Pony",
  4407. )
  4408. self.assertEqual(
  4409. operation.migration_name_fragment,
  4410. "pony_test_adfuncuc_pony_abs_uq",
  4411. )
  4412. new_state = project_state.clone()
  4413. operation.state_forwards(app_label, new_state)
  4414. self.assertEqual(
  4415. len(new_state.models[app_label, "pony"].options["constraints"]), 1
  4416. )
  4417. self.assertIndexNameNotExists(table_name, constraint_name)
  4418. # Add constraint.
  4419. with connection.schema_editor() as editor:
  4420. operation.database_forwards(app_label, editor, project_state, new_state)
  4421. Pony = new_state.apps.get_model(app_label, "Pony")
  4422. Pony.objects.create(weight=4.0)
  4423. if connection.features.supports_expression_indexes:
  4424. self.assertIndexNameExists(table_name, constraint_name)
  4425. with self.assertRaises(IntegrityError):
  4426. Pony.objects.create(weight=-4.0)
  4427. else:
  4428. self.assertIndexNameNotExists(table_name, constraint_name)
  4429. Pony.objects.create(weight=-4.0)
  4430. # Reversal.
  4431. with connection.schema_editor() as editor:
  4432. operation.database_backwards(app_label, editor, new_state, project_state)
  4433. self.assertIndexNameNotExists(table_name, constraint_name)
  4434. # Constraint doesn't work.
  4435. Pony.objects.create(weight=-4.0)
  4436. # Deconstruction.
  4437. definition = operation.deconstruct()
  4438. self.assertEqual(definition[0], "AddConstraint")
  4439. self.assertEqual(definition[1], [])
  4440. self.assertEqual(
  4441. definition[2],
  4442. {"model_name": "Pony", "constraint": constraint},
  4443. )
  4444. def test_remove_func_unique_constraint(self):
  4445. app_label = "test_rmfuncuc"
  4446. constraint_name = f"{app_label}_pony_abs_uq"
  4447. table_name = f"{app_label}_pony"
  4448. project_state = self.set_up_test_model(
  4449. app_label,
  4450. constraints=[
  4451. models.UniqueConstraint(Abs("weight"), name=constraint_name),
  4452. ],
  4453. )
  4454. self.assertTableExists(table_name)
  4455. if connection.features.supports_expression_indexes:
  4456. self.assertIndexNameExists(table_name, constraint_name)
  4457. operation = migrations.RemoveConstraint("Pony", constraint_name)
  4458. self.assertEqual(
  4459. operation.describe(),
  4460. "Remove constraint test_rmfuncuc_pony_abs_uq from model Pony",
  4461. )
  4462. self.assertEqual(
  4463. operation.migration_name_fragment,
  4464. "remove_pony_test_rmfuncuc_pony_abs_uq",
  4465. )
  4466. new_state = project_state.clone()
  4467. operation.state_forwards(app_label, new_state)
  4468. self.assertEqual(
  4469. len(new_state.models[app_label, "pony"].options["constraints"]), 0
  4470. )
  4471. Pony = new_state.apps.get_model(app_label, "Pony")
  4472. self.assertEqual(len(Pony._meta.constraints), 0)
  4473. # Remove constraint.
  4474. with connection.schema_editor() as editor:
  4475. operation.database_forwards(app_label, editor, project_state, new_state)
  4476. self.assertIndexNameNotExists(table_name, constraint_name)
  4477. # Constraint doesn't work.
  4478. Pony.objects.create(pink=1, weight=4.0)
  4479. Pony.objects.create(pink=1, weight=-4.0).delete()
  4480. # Reversal.
  4481. with connection.schema_editor() as editor:
  4482. operation.database_backwards(app_label, editor, new_state, project_state)
  4483. if connection.features.supports_expression_indexes:
  4484. self.assertIndexNameExists(table_name, constraint_name)
  4485. with self.assertRaises(IntegrityError):
  4486. Pony.objects.create(weight=-4.0)
  4487. else:
  4488. self.assertIndexNameNotExists(table_name, constraint_name)
  4489. Pony.objects.create(weight=-4.0)
  4490. # Deconstruction.
  4491. definition = operation.deconstruct()
  4492. self.assertEqual(definition[0], "RemoveConstraint")
  4493. self.assertEqual(definition[1], [])
  4494. self.assertEqual(definition[2], {"model_name": "Pony", "name": constraint_name})
  4495. def test_alter_model_options(self):
  4496. """
  4497. Tests the AlterModelOptions operation.
  4498. """
  4499. project_state = self.set_up_test_model("test_almoop")
  4500. # Test the state alteration (no DB alteration to test)
  4501. operation = migrations.AlterModelOptions(
  4502. "Pony", {"permissions": [("can_groom", "Can groom")]}
  4503. )
  4504. self.assertEqual(operation.describe(), "Change Meta options on Pony")
  4505. self.assertEqual(operation.migration_name_fragment, "alter_pony_options")
  4506. new_state = project_state.clone()
  4507. operation.state_forwards("test_almoop", new_state)
  4508. self.assertEqual(
  4509. len(
  4510. project_state.models["test_almoop", "pony"].options.get(
  4511. "permissions", []
  4512. )
  4513. ),
  4514. 0,
  4515. )
  4516. self.assertEqual(
  4517. len(new_state.models["test_almoop", "pony"].options.get("permissions", [])),
  4518. 1,
  4519. )
  4520. self.assertEqual(
  4521. new_state.models["test_almoop", "pony"].options["permissions"][0][0],
  4522. "can_groom",
  4523. )
  4524. # And deconstruction
  4525. definition = operation.deconstruct()
  4526. self.assertEqual(definition[0], "AlterModelOptions")
  4527. self.assertEqual(definition[1], [])
  4528. self.assertEqual(
  4529. definition[2],
  4530. {"name": "Pony", "options": {"permissions": [("can_groom", "Can groom")]}},
  4531. )
  4532. def test_alter_model_options_emptying(self):
  4533. """
  4534. The AlterModelOptions operation removes keys from the dict (#23121)
  4535. """
  4536. project_state = self.set_up_test_model("test_almoop", options=True)
  4537. # Test the state alteration (no DB alteration to test)
  4538. operation = migrations.AlterModelOptions("Pony", {})
  4539. self.assertEqual(operation.describe(), "Change Meta options on Pony")
  4540. new_state = project_state.clone()
  4541. operation.state_forwards("test_almoop", new_state)
  4542. self.assertEqual(
  4543. len(
  4544. project_state.models["test_almoop", "pony"].options.get(
  4545. "permissions", []
  4546. )
  4547. ),
  4548. 1,
  4549. )
  4550. self.assertEqual(
  4551. len(new_state.models["test_almoop", "pony"].options.get("permissions", [])),
  4552. 0,
  4553. )
  4554. # And deconstruction
  4555. definition = operation.deconstruct()
  4556. self.assertEqual(definition[0], "AlterModelOptions")
  4557. self.assertEqual(definition[1], [])
  4558. self.assertEqual(definition[2], {"name": "Pony", "options": {}})
  4559. def test_alter_order_with_respect_to(self):
  4560. """
  4561. Tests the AlterOrderWithRespectTo operation.
  4562. """
  4563. project_state = self.set_up_test_model("test_alorwrtto", related_model=True)
  4564. # Test the state alteration
  4565. operation = migrations.AlterOrderWithRespectTo("Rider", "pony")
  4566. self.assertEqual(
  4567. operation.describe(), "Set order_with_respect_to on Rider to pony"
  4568. )
  4569. self.assertEqual(
  4570. operation.migration_name_fragment,
  4571. "alter_rider_order_with_respect_to",
  4572. )
  4573. new_state = project_state.clone()
  4574. operation.state_forwards("test_alorwrtto", new_state)
  4575. self.assertIsNone(
  4576. project_state.models["test_alorwrtto", "rider"].options.get(
  4577. "order_with_respect_to", None
  4578. )
  4579. )
  4580. self.assertEqual(
  4581. new_state.models["test_alorwrtto", "rider"].options.get(
  4582. "order_with_respect_to", None
  4583. ),
  4584. "pony",
  4585. )
  4586. # Make sure there's no matching index
  4587. self.assertColumnNotExists("test_alorwrtto_rider", "_order")
  4588. # Create some rows before alteration
  4589. rendered_state = project_state.apps
  4590. pony = rendered_state.get_model("test_alorwrtto", "Pony").objects.create(
  4591. weight=50
  4592. )
  4593. rider1 = rendered_state.get_model("test_alorwrtto", "Rider").objects.create(
  4594. pony=pony
  4595. )
  4596. rider1.friend = rider1
  4597. rider1.save()
  4598. rider2 = rendered_state.get_model("test_alorwrtto", "Rider").objects.create(
  4599. pony=pony
  4600. )
  4601. rider2.friend = rider2
  4602. rider2.save()
  4603. # Test the database alteration
  4604. with connection.schema_editor() as editor:
  4605. operation.database_forwards(
  4606. "test_alorwrtto", editor, project_state, new_state
  4607. )
  4608. self.assertColumnExists("test_alorwrtto_rider", "_order")
  4609. # Check for correct value in rows
  4610. updated_riders = new_state.apps.get_model(
  4611. "test_alorwrtto", "Rider"
  4612. ).objects.all()
  4613. self.assertEqual(updated_riders[0]._order, 0)
  4614. self.assertEqual(updated_riders[1]._order, 0)
  4615. # And test reversal
  4616. with connection.schema_editor() as editor:
  4617. operation.database_backwards(
  4618. "test_alorwrtto", editor, new_state, project_state
  4619. )
  4620. self.assertColumnNotExists("test_alorwrtto_rider", "_order")
  4621. # And deconstruction
  4622. definition = operation.deconstruct()
  4623. self.assertEqual(definition[0], "AlterOrderWithRespectTo")
  4624. self.assertEqual(definition[1], [])
  4625. self.assertEqual(
  4626. definition[2], {"name": "Rider", "order_with_respect_to": "pony"}
  4627. )
  4628. def test_alter_model_managers(self):
  4629. """
  4630. The managers on a model are set.
  4631. """
  4632. project_state = self.set_up_test_model("test_almoma")
  4633. # Test the state alteration
  4634. operation = migrations.AlterModelManagers(
  4635. "Pony",
  4636. managers=[
  4637. ("food_qs", FoodQuerySet.as_manager()),
  4638. ("food_mgr", FoodManager("a", "b")),
  4639. ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)),
  4640. ],
  4641. )
  4642. self.assertEqual(operation.describe(), "Change managers on Pony")
  4643. self.assertEqual(operation.migration_name_fragment, "alter_pony_managers")
  4644. managers = project_state.models["test_almoma", "pony"].managers
  4645. self.assertEqual(managers, [])
  4646. new_state = project_state.clone()
  4647. operation.state_forwards("test_almoma", new_state)
  4648. self.assertIn(("test_almoma", "pony"), new_state.models)
  4649. managers = new_state.models["test_almoma", "pony"].managers
  4650. self.assertEqual(managers[0][0], "food_qs")
  4651. self.assertIsInstance(managers[0][1], models.Manager)
  4652. self.assertEqual(managers[1][0], "food_mgr")
  4653. self.assertIsInstance(managers[1][1], FoodManager)
  4654. self.assertEqual(managers[1][1].args, ("a", "b", 1, 2))
  4655. self.assertEqual(managers[2][0], "food_mgr_kwargs")
  4656. self.assertIsInstance(managers[2][1], FoodManager)
  4657. self.assertEqual(managers[2][1].args, ("x", "y", 3, 4))
  4658. rendered_state = new_state.apps
  4659. model = rendered_state.get_model("test_almoma", "pony")
  4660. self.assertIsInstance(model.food_qs, models.Manager)
  4661. self.assertIsInstance(model.food_mgr, FoodManager)
  4662. self.assertIsInstance(model.food_mgr_kwargs, FoodManager)
  4663. def test_alter_model_managers_emptying(self):
  4664. """
  4665. The managers on a model are set.
  4666. """
  4667. project_state = self.set_up_test_model("test_almomae", manager_model=True)
  4668. # Test the state alteration
  4669. operation = migrations.AlterModelManagers("Food", managers=[])
  4670. self.assertEqual(operation.describe(), "Change managers on Food")
  4671. self.assertIn(("test_almomae", "food"), project_state.models)
  4672. managers = project_state.models["test_almomae", "food"].managers
  4673. self.assertEqual(managers[0][0], "food_qs")
  4674. self.assertIsInstance(managers[0][1], models.Manager)
  4675. self.assertEqual(managers[1][0], "food_mgr")
  4676. self.assertIsInstance(managers[1][1], FoodManager)
  4677. self.assertEqual(managers[1][1].args, ("a", "b", 1, 2))
  4678. self.assertEqual(managers[2][0], "food_mgr_kwargs")
  4679. self.assertIsInstance(managers[2][1], FoodManager)
  4680. self.assertEqual(managers[2][1].args, ("x", "y", 3, 4))
  4681. new_state = project_state.clone()
  4682. operation.state_forwards("test_almomae", new_state)
  4683. managers = new_state.models["test_almomae", "food"].managers
  4684. self.assertEqual(managers, [])
  4685. def test_alter_fk(self):
  4686. """
  4687. Creating and then altering an FK works correctly
  4688. and deals with the pending SQL (#23091)
  4689. """
  4690. project_state = self.set_up_test_model("test_alfk")
  4691. # Test adding and then altering the FK in one go
  4692. create_operation = migrations.CreateModel(
  4693. name="Rider",
  4694. fields=[
  4695. ("id", models.AutoField(primary_key=True)),
  4696. ("pony", models.ForeignKey("Pony", models.CASCADE)),
  4697. ],
  4698. )
  4699. create_state = project_state.clone()
  4700. create_operation.state_forwards("test_alfk", create_state)
  4701. alter_operation = migrations.AlterField(
  4702. model_name="Rider",
  4703. name="pony",
  4704. field=models.ForeignKey("Pony", models.CASCADE, editable=False),
  4705. )
  4706. alter_state = create_state.clone()
  4707. alter_operation.state_forwards("test_alfk", alter_state)
  4708. with connection.schema_editor() as editor:
  4709. create_operation.database_forwards(
  4710. "test_alfk", editor, project_state, create_state
  4711. )
  4712. alter_operation.database_forwards(
  4713. "test_alfk", editor, create_state, alter_state
  4714. )
  4715. def test_alter_fk_non_fk(self):
  4716. """
  4717. Altering an FK to a non-FK works (#23244)
  4718. """
  4719. # Test the state alteration
  4720. operation = migrations.AlterField(
  4721. model_name="Rider",
  4722. name="pony",
  4723. field=models.FloatField(),
  4724. )
  4725. project_state, new_state = self.make_test_state(
  4726. "test_afknfk", operation, related_model=True
  4727. )
  4728. # Test the database alteration
  4729. self.assertColumnExists("test_afknfk_rider", "pony_id")
  4730. self.assertColumnNotExists("test_afknfk_rider", "pony")
  4731. with connection.schema_editor() as editor:
  4732. operation.database_forwards("test_afknfk", editor, project_state, new_state)
  4733. self.assertColumnExists("test_afknfk_rider", "pony")
  4734. self.assertColumnNotExists("test_afknfk_rider", "pony_id")
  4735. # And test reversal
  4736. with connection.schema_editor() as editor:
  4737. operation.database_backwards(
  4738. "test_afknfk", editor, new_state, project_state
  4739. )
  4740. self.assertColumnExists("test_afknfk_rider", "pony_id")
  4741. self.assertColumnNotExists("test_afknfk_rider", "pony")
  4742. def test_run_sql(self):
  4743. """
  4744. Tests the RunSQL operation.
  4745. """
  4746. project_state = self.set_up_test_model("test_runsql")
  4747. # Create the operation
  4748. operation = migrations.RunSQL(
  4749. # Use a multi-line string with a comment to test splitting on
  4750. # SQLite and MySQL respectively.
  4751. "CREATE TABLE i_love_ponies (id int, special_thing varchar(15));\n"
  4752. "INSERT INTO i_love_ponies (id, special_thing) "
  4753. "VALUES (1, 'i love ponies'); -- this is magic!\n"
  4754. "INSERT INTO i_love_ponies (id, special_thing) "
  4755. "VALUES (2, 'i love django');\n"
  4756. "UPDATE i_love_ponies SET special_thing = 'Ponies' "
  4757. "WHERE special_thing LIKE '%%ponies';"
  4758. "UPDATE i_love_ponies SET special_thing = 'Django' "
  4759. "WHERE special_thing LIKE '%django';",
  4760. # Run delete queries to test for parameter substitution failure
  4761. # reported in #23426
  4762. "DELETE FROM i_love_ponies WHERE special_thing LIKE '%Django%';"
  4763. "DELETE FROM i_love_ponies WHERE special_thing LIKE '%%Ponies%%';"
  4764. "DROP TABLE i_love_ponies",
  4765. state_operations=[
  4766. migrations.CreateModel(
  4767. "SomethingElse", [("id", models.AutoField(primary_key=True))]
  4768. )
  4769. ],
  4770. )
  4771. self.assertEqual(operation.describe(), "Raw SQL operation")
  4772. # Test the state alteration
  4773. new_state = project_state.clone()
  4774. operation.state_forwards("test_runsql", new_state)
  4775. self.assertEqual(
  4776. len(new_state.models["test_runsql", "somethingelse"].fields), 1
  4777. )
  4778. # Make sure there's no table
  4779. self.assertTableNotExists("i_love_ponies")
  4780. # Test SQL collection
  4781. with connection.schema_editor(collect_sql=True) as editor:
  4782. operation.database_forwards("test_runsql", editor, project_state, new_state)
  4783. self.assertIn("LIKE '%%ponies';", "\n".join(editor.collected_sql))
  4784. operation.database_backwards(
  4785. "test_runsql", editor, project_state, new_state
  4786. )
  4787. self.assertIn("LIKE '%%Ponies%%';", "\n".join(editor.collected_sql))
  4788. # Test the database alteration
  4789. with connection.schema_editor() as editor:
  4790. operation.database_forwards("test_runsql", editor, project_state, new_state)
  4791. self.assertTableExists("i_love_ponies")
  4792. # Make sure all the SQL was processed
  4793. with connection.cursor() as cursor:
  4794. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  4795. self.assertEqual(cursor.fetchall()[0][0], 2)
  4796. cursor.execute(
  4797. "SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Django'"
  4798. )
  4799. self.assertEqual(cursor.fetchall()[0][0], 1)
  4800. cursor.execute(
  4801. "SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Ponies'"
  4802. )
  4803. self.assertEqual(cursor.fetchall()[0][0], 1)
  4804. # And test reversal
  4805. self.assertTrue(operation.reversible)
  4806. with connection.schema_editor() as editor:
  4807. operation.database_backwards(
  4808. "test_runsql", editor, new_state, project_state
  4809. )
  4810. self.assertTableNotExists("i_love_ponies")
  4811. # And deconstruction
  4812. definition = operation.deconstruct()
  4813. self.assertEqual(definition[0], "RunSQL")
  4814. self.assertEqual(definition[1], [])
  4815. self.assertEqual(
  4816. sorted(definition[2]), ["reverse_sql", "sql", "state_operations"]
  4817. )
  4818. # And elidable reduction
  4819. self.assertIs(False, operation.reduce(operation, []))
  4820. elidable_operation = migrations.RunSQL("SELECT 1 FROM void;", elidable=True)
  4821. self.assertEqual(elidable_operation.reduce(operation, []), [operation])
  4822. def test_run_sql_params(self):
  4823. """
  4824. #23426 - RunSQL should accept parameters.
  4825. """
  4826. project_state = self.set_up_test_model("test_runsql")
  4827. # Create the operation
  4828. operation = migrations.RunSQL(
  4829. ["CREATE TABLE i_love_ponies (id int, special_thing varchar(15));"],
  4830. ["DROP TABLE i_love_ponies"],
  4831. )
  4832. param_operation = migrations.RunSQL(
  4833. # forwards
  4834. (
  4835. "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 'Django');",
  4836. [
  4837. "INSERT INTO i_love_ponies (id, special_thing) VALUES (2, %s);",
  4838. ["Ponies"],
  4839. ],
  4840. (
  4841. "INSERT INTO i_love_ponies (id, special_thing) VALUES (%s, %s);",
  4842. (
  4843. 3,
  4844. "Python",
  4845. ),
  4846. ),
  4847. ),
  4848. # backwards
  4849. [
  4850. "DELETE FROM i_love_ponies WHERE special_thing = 'Django';",
  4851. ["DELETE FROM i_love_ponies WHERE special_thing = 'Ponies';", None],
  4852. (
  4853. "DELETE FROM i_love_ponies WHERE id = %s OR special_thing = %s;",
  4854. [3, "Python"],
  4855. ),
  4856. ],
  4857. )
  4858. # Make sure there's no table
  4859. self.assertTableNotExists("i_love_ponies")
  4860. new_state = project_state.clone()
  4861. # Test the database alteration
  4862. with connection.schema_editor() as editor:
  4863. operation.database_forwards("test_runsql", editor, project_state, new_state)
  4864. # Test parameter passing
  4865. with connection.schema_editor() as editor:
  4866. param_operation.database_forwards(
  4867. "test_runsql", editor, project_state, new_state
  4868. )
  4869. # Make sure all the SQL was processed
  4870. with connection.cursor() as cursor:
  4871. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  4872. self.assertEqual(cursor.fetchall()[0][0], 3)
  4873. with connection.schema_editor() as editor:
  4874. param_operation.database_backwards(
  4875. "test_runsql", editor, new_state, project_state
  4876. )
  4877. with connection.cursor() as cursor:
  4878. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  4879. self.assertEqual(cursor.fetchall()[0][0], 0)
  4880. # And test reversal
  4881. with connection.schema_editor() as editor:
  4882. operation.database_backwards(
  4883. "test_runsql", editor, new_state, project_state
  4884. )
  4885. self.assertTableNotExists("i_love_ponies")
  4886. def test_run_sql_params_invalid(self):
  4887. """
  4888. #23426 - RunSQL should fail when a list of statements with an incorrect
  4889. number of tuples is given.
  4890. """
  4891. project_state = self.set_up_test_model("test_runsql")
  4892. new_state = project_state.clone()
  4893. operation = migrations.RunSQL(
  4894. # forwards
  4895. [["INSERT INTO foo (bar) VALUES ('buz');"]],
  4896. # backwards
  4897. (("DELETE FROM foo WHERE bar = 'buz';", "invalid", "parameter count"),),
  4898. )
  4899. with connection.schema_editor() as editor:
  4900. with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 1"):
  4901. operation.database_forwards(
  4902. "test_runsql", editor, project_state, new_state
  4903. )
  4904. with connection.schema_editor() as editor:
  4905. with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 3"):
  4906. operation.database_backwards(
  4907. "test_runsql", editor, new_state, project_state
  4908. )
  4909. def test_run_sql_noop(self):
  4910. """
  4911. #24098 - Tests no-op RunSQL operations.
  4912. """
  4913. operation = migrations.RunSQL(migrations.RunSQL.noop, migrations.RunSQL.noop)
  4914. with connection.schema_editor() as editor:
  4915. operation.database_forwards("test_runsql", editor, None, None)
  4916. operation.database_backwards("test_runsql", editor, None, None)
  4917. def test_run_sql_add_missing_semicolon_on_collect_sql(self):
  4918. project_state = self.set_up_test_model("test_runsql")
  4919. new_state = project_state.clone()
  4920. tests = [
  4921. "INSERT INTO test_runsql_pony (pink, weight) VALUES (1, 1);\n",
  4922. "INSERT INTO test_runsql_pony (pink, weight) VALUES (1, 1)\n",
  4923. ]
  4924. for sql in tests:
  4925. with self.subTest(sql=sql):
  4926. operation = migrations.RunSQL(sql, migrations.RunPython.noop)
  4927. with connection.schema_editor(collect_sql=True) as editor:
  4928. operation.database_forwards(
  4929. "test_runsql", editor, project_state, new_state
  4930. )
  4931. collected_sql = "\n".join(editor.collected_sql)
  4932. self.assertEqual(collected_sql.count(";"), 1)
  4933. def test_run_python(self):
  4934. """
  4935. Tests the RunPython operation
  4936. """
  4937. project_state = self.set_up_test_model("test_runpython", mti_model=True)
  4938. # Create the operation
  4939. def inner_method(models, schema_editor):
  4940. Pony = models.get_model("test_runpython", "Pony")
  4941. Pony.objects.create(pink=1, weight=3.55)
  4942. Pony.objects.create(weight=5)
  4943. def inner_method_reverse(models, schema_editor):
  4944. Pony = models.get_model("test_runpython", "Pony")
  4945. Pony.objects.filter(pink=1, weight=3.55).delete()
  4946. Pony.objects.filter(weight=5).delete()
  4947. operation = migrations.RunPython(
  4948. inner_method, reverse_code=inner_method_reverse
  4949. )
  4950. self.assertEqual(operation.describe(), "Raw Python operation")
  4951. # Test the state alteration does nothing
  4952. new_state = project_state.clone()
  4953. operation.state_forwards("test_runpython", new_state)
  4954. self.assertEqual(new_state, project_state)
  4955. # Test the database alteration
  4956. self.assertEqual(
  4957. project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0
  4958. )
  4959. with connection.schema_editor() as editor:
  4960. operation.database_forwards(
  4961. "test_runpython", editor, project_state, new_state
  4962. )
  4963. self.assertEqual(
  4964. project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2
  4965. )
  4966. # Now test reversal
  4967. self.assertTrue(operation.reversible)
  4968. with connection.schema_editor() as editor:
  4969. operation.database_backwards(
  4970. "test_runpython", editor, project_state, new_state
  4971. )
  4972. self.assertEqual(
  4973. project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0
  4974. )
  4975. # Now test we can't use a string
  4976. with self.assertRaisesMessage(
  4977. ValueError, "RunPython must be supplied with a callable"
  4978. ):
  4979. migrations.RunPython("print 'ahahaha'")
  4980. # And deconstruction
  4981. definition = operation.deconstruct()
  4982. self.assertEqual(definition[0], "RunPython")
  4983. self.assertEqual(definition[1], [])
  4984. self.assertEqual(sorted(definition[2]), ["code", "reverse_code"])
  4985. # Also test reversal fails, with an operation identical to above but
  4986. # without reverse_code set.
  4987. no_reverse_operation = migrations.RunPython(inner_method)
  4988. self.assertFalse(no_reverse_operation.reversible)
  4989. with connection.schema_editor() as editor:
  4990. no_reverse_operation.database_forwards(
  4991. "test_runpython", editor, project_state, new_state
  4992. )
  4993. with self.assertRaises(NotImplementedError):
  4994. no_reverse_operation.database_backwards(
  4995. "test_runpython", editor, new_state, project_state
  4996. )
  4997. self.assertEqual(
  4998. project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2
  4999. )
  5000. def create_ponies(models, schema_editor):
  5001. Pony = models.get_model("test_runpython", "Pony")
  5002. pony1 = Pony.objects.create(pink=1, weight=3.55)
  5003. self.assertIsNot(pony1.pk, None)
  5004. pony2 = Pony.objects.create(weight=5)
  5005. self.assertIsNot(pony2.pk, None)
  5006. self.assertNotEqual(pony1.pk, pony2.pk)
  5007. operation = migrations.RunPython(create_ponies)
  5008. with connection.schema_editor() as editor:
  5009. operation.database_forwards(
  5010. "test_runpython", editor, project_state, new_state
  5011. )
  5012. self.assertEqual(
  5013. project_state.apps.get_model("test_runpython", "Pony").objects.count(), 4
  5014. )
  5015. # And deconstruction
  5016. definition = operation.deconstruct()
  5017. self.assertEqual(definition[0], "RunPython")
  5018. self.assertEqual(definition[1], [])
  5019. self.assertEqual(sorted(definition[2]), ["code"])
  5020. def create_shetlandponies(models, schema_editor):
  5021. ShetlandPony = models.get_model("test_runpython", "ShetlandPony")
  5022. pony1 = ShetlandPony.objects.create(weight=4.0)
  5023. self.assertIsNot(pony1.pk, None)
  5024. pony2 = ShetlandPony.objects.create(weight=5.0)
  5025. self.assertIsNot(pony2.pk, None)
  5026. self.assertNotEqual(pony1.pk, pony2.pk)
  5027. operation = migrations.RunPython(create_shetlandponies)
  5028. with connection.schema_editor() as editor:
  5029. operation.database_forwards(
  5030. "test_runpython", editor, project_state, new_state
  5031. )
  5032. self.assertEqual(
  5033. project_state.apps.get_model("test_runpython", "Pony").objects.count(), 6
  5034. )
  5035. self.assertEqual(
  5036. project_state.apps.get_model(
  5037. "test_runpython", "ShetlandPony"
  5038. ).objects.count(),
  5039. 2,
  5040. )
  5041. # And elidable reduction
  5042. self.assertIs(False, operation.reduce(operation, []))
  5043. elidable_operation = migrations.RunPython(inner_method, elidable=True)
  5044. self.assertEqual(elidable_operation.reduce(operation, []), [operation])
  5045. def test_run_python_atomic(self):
  5046. """
  5047. Tests the RunPython operation correctly handles the "atomic" keyword
  5048. """
  5049. project_state = self.set_up_test_model("test_runpythonatomic", mti_model=True)
  5050. def inner_method(models, schema_editor):
  5051. Pony = models.get_model("test_runpythonatomic", "Pony")
  5052. Pony.objects.create(pink=1, weight=3.55)
  5053. raise ValueError("Adrian hates ponies.")
  5054. # Verify atomicity when applying.
  5055. atomic_migration = Migration("test", "test_runpythonatomic")
  5056. atomic_migration.operations = [
  5057. migrations.RunPython(inner_method, reverse_code=inner_method)
  5058. ]
  5059. non_atomic_migration = Migration("test", "test_runpythonatomic")
  5060. non_atomic_migration.operations = [
  5061. migrations.RunPython(inner_method, reverse_code=inner_method, atomic=False)
  5062. ]
  5063. # If we're a fully-transactional database, both versions should rollback
  5064. if connection.features.can_rollback_ddl:
  5065. self.assertEqual(
  5066. project_state.apps.get_model(
  5067. "test_runpythonatomic", "Pony"
  5068. ).objects.count(),
  5069. 0,
  5070. )
  5071. with self.assertRaises(ValueError):
  5072. with connection.schema_editor() as editor:
  5073. atomic_migration.apply(project_state, editor)
  5074. self.assertEqual(
  5075. project_state.apps.get_model(
  5076. "test_runpythonatomic", "Pony"
  5077. ).objects.count(),
  5078. 0,
  5079. )
  5080. with self.assertRaises(ValueError):
  5081. with connection.schema_editor() as editor:
  5082. non_atomic_migration.apply(project_state, editor)
  5083. self.assertEqual(
  5084. project_state.apps.get_model(
  5085. "test_runpythonatomic", "Pony"
  5086. ).objects.count(),
  5087. 0,
  5088. )
  5089. # Otherwise, the non-atomic operation should leave a row there
  5090. else:
  5091. self.assertEqual(
  5092. project_state.apps.get_model(
  5093. "test_runpythonatomic", "Pony"
  5094. ).objects.count(),
  5095. 0,
  5096. )
  5097. with self.assertRaises(ValueError):
  5098. with connection.schema_editor() as editor:
  5099. atomic_migration.apply(project_state, editor)
  5100. self.assertEqual(
  5101. project_state.apps.get_model(
  5102. "test_runpythonatomic", "Pony"
  5103. ).objects.count(),
  5104. 0,
  5105. )
  5106. with self.assertRaises(ValueError):
  5107. with connection.schema_editor() as editor:
  5108. non_atomic_migration.apply(project_state, editor)
  5109. self.assertEqual(
  5110. project_state.apps.get_model(
  5111. "test_runpythonatomic", "Pony"
  5112. ).objects.count(),
  5113. 1,
  5114. )
  5115. # Reset object count to zero and verify atomicity when unapplying.
  5116. project_state.apps.get_model(
  5117. "test_runpythonatomic", "Pony"
  5118. ).objects.all().delete()
  5119. # On a fully-transactional database, both versions rollback.
  5120. if connection.features.can_rollback_ddl:
  5121. self.assertEqual(
  5122. project_state.apps.get_model(
  5123. "test_runpythonatomic", "Pony"
  5124. ).objects.count(),
  5125. 0,
  5126. )
  5127. with self.assertRaises(ValueError):
  5128. with connection.schema_editor() as editor:
  5129. atomic_migration.unapply(project_state, editor)
  5130. self.assertEqual(
  5131. project_state.apps.get_model(
  5132. "test_runpythonatomic", "Pony"
  5133. ).objects.count(),
  5134. 0,
  5135. )
  5136. with self.assertRaises(ValueError):
  5137. with connection.schema_editor() as editor:
  5138. non_atomic_migration.unapply(project_state, editor)
  5139. self.assertEqual(
  5140. project_state.apps.get_model(
  5141. "test_runpythonatomic", "Pony"
  5142. ).objects.count(),
  5143. 0,
  5144. )
  5145. # Otherwise, the non-atomic operation leaves a row there.
  5146. else:
  5147. self.assertEqual(
  5148. project_state.apps.get_model(
  5149. "test_runpythonatomic", "Pony"
  5150. ).objects.count(),
  5151. 0,
  5152. )
  5153. with self.assertRaises(ValueError):
  5154. with connection.schema_editor() as editor:
  5155. atomic_migration.unapply(project_state, editor)
  5156. self.assertEqual(
  5157. project_state.apps.get_model(
  5158. "test_runpythonatomic", "Pony"
  5159. ).objects.count(),
  5160. 0,
  5161. )
  5162. with self.assertRaises(ValueError):
  5163. with connection.schema_editor() as editor:
  5164. non_atomic_migration.unapply(project_state, editor)
  5165. self.assertEqual(
  5166. project_state.apps.get_model(
  5167. "test_runpythonatomic", "Pony"
  5168. ).objects.count(),
  5169. 1,
  5170. )
  5171. # Verify deconstruction.
  5172. definition = non_atomic_migration.operations[0].deconstruct()
  5173. self.assertEqual(definition[0], "RunPython")
  5174. self.assertEqual(definition[1], [])
  5175. self.assertEqual(sorted(definition[2]), ["atomic", "code", "reverse_code"])
  5176. def test_run_python_related_assignment(self):
  5177. """
  5178. #24282 - Model changes to a FK reverse side update the model
  5179. on the FK side as well.
  5180. """
  5181. def inner_method(models, schema_editor):
  5182. Author = models.get_model("test_authors", "Author")
  5183. Book = models.get_model("test_books", "Book")
  5184. author = Author.objects.create(name="Hemingway")
  5185. Book.objects.create(title="Old Man and The Sea", author=author)
  5186. create_author = migrations.CreateModel(
  5187. "Author",
  5188. [
  5189. ("id", models.AutoField(primary_key=True)),
  5190. ("name", models.CharField(max_length=100)),
  5191. ],
  5192. options={},
  5193. )
  5194. create_book = migrations.CreateModel(
  5195. "Book",
  5196. [
  5197. ("id", models.AutoField(primary_key=True)),
  5198. ("title", models.CharField(max_length=100)),
  5199. ("author", models.ForeignKey("test_authors.Author", models.CASCADE)),
  5200. ],
  5201. options={},
  5202. )
  5203. add_hometown = migrations.AddField(
  5204. "Author",
  5205. "hometown",
  5206. models.CharField(max_length=100),
  5207. )
  5208. create_old_man = migrations.RunPython(inner_method, inner_method)
  5209. project_state = ProjectState()
  5210. new_state = project_state.clone()
  5211. with connection.schema_editor() as editor:
  5212. create_author.state_forwards("test_authors", new_state)
  5213. create_author.database_forwards(
  5214. "test_authors", editor, project_state, new_state
  5215. )
  5216. project_state = new_state
  5217. new_state = new_state.clone()
  5218. with connection.schema_editor() as editor:
  5219. create_book.state_forwards("test_books", new_state)
  5220. create_book.database_forwards(
  5221. "test_books", editor, project_state, new_state
  5222. )
  5223. project_state = new_state
  5224. new_state = new_state.clone()
  5225. with connection.schema_editor() as editor:
  5226. add_hometown.state_forwards("test_authors", new_state)
  5227. add_hometown.database_forwards(
  5228. "test_authors", editor, project_state, new_state
  5229. )
  5230. project_state = new_state
  5231. new_state = new_state.clone()
  5232. with connection.schema_editor() as editor:
  5233. create_old_man.state_forwards("test_books", new_state)
  5234. create_old_man.database_forwards(
  5235. "test_books", editor, project_state, new_state
  5236. )
  5237. def test_model_with_bigautofield(self):
  5238. """
  5239. A model with BigAutoField can be created.
  5240. """
  5241. def create_data(models, schema_editor):
  5242. Author = models.get_model("test_author", "Author")
  5243. Book = models.get_model("test_book", "Book")
  5244. author1 = Author.objects.create(name="Hemingway")
  5245. Book.objects.create(title="Old Man and The Sea", author=author1)
  5246. Book.objects.create(id=2**33, title="A farewell to arms", author=author1)
  5247. author2 = Author.objects.create(id=2**33, name="Remarque")
  5248. Book.objects.create(title="All quiet on the western front", author=author2)
  5249. Book.objects.create(title="Arc de Triomphe", author=author2)
  5250. create_author = migrations.CreateModel(
  5251. "Author",
  5252. [
  5253. ("id", models.BigAutoField(primary_key=True)),
  5254. ("name", models.CharField(max_length=100)),
  5255. ],
  5256. options={},
  5257. )
  5258. create_book = migrations.CreateModel(
  5259. "Book",
  5260. [
  5261. ("id", models.BigAutoField(primary_key=True)),
  5262. ("title", models.CharField(max_length=100)),
  5263. (
  5264. "author",
  5265. models.ForeignKey(
  5266. to="test_author.Author", on_delete=models.CASCADE
  5267. ),
  5268. ),
  5269. ],
  5270. options={},
  5271. )
  5272. fill_data = migrations.RunPython(create_data)
  5273. project_state = ProjectState()
  5274. new_state = project_state.clone()
  5275. with connection.schema_editor() as editor:
  5276. create_author.state_forwards("test_author", new_state)
  5277. create_author.database_forwards(
  5278. "test_author", editor, project_state, new_state
  5279. )
  5280. project_state = new_state
  5281. new_state = new_state.clone()
  5282. with connection.schema_editor() as editor:
  5283. create_book.state_forwards("test_book", new_state)
  5284. create_book.database_forwards("test_book", editor, project_state, new_state)
  5285. project_state = new_state
  5286. new_state = new_state.clone()
  5287. with connection.schema_editor() as editor:
  5288. fill_data.state_forwards("fill_data", new_state)
  5289. fill_data.database_forwards("fill_data", editor, project_state, new_state)
  5290. def _test_autofield_foreignfield_growth(
  5291. self, source_field, target_field, target_value
  5292. ):
  5293. """
  5294. A field may be migrated in the following ways:
  5295. - AutoField to BigAutoField
  5296. - SmallAutoField to AutoField
  5297. - SmallAutoField to BigAutoField
  5298. """
  5299. def create_initial_data(models, schema_editor):
  5300. Article = models.get_model("test_article", "Article")
  5301. Blog = models.get_model("test_blog", "Blog")
  5302. blog = Blog.objects.create(name="web development done right")
  5303. Article.objects.create(name="Frameworks", blog=blog)
  5304. Article.objects.create(name="Programming Languages", blog=blog)
  5305. def create_big_data(models, schema_editor):
  5306. Article = models.get_model("test_article", "Article")
  5307. Blog = models.get_model("test_blog", "Blog")
  5308. blog2 = Blog.objects.create(name="Frameworks", id=target_value)
  5309. Article.objects.create(name="Django", blog=blog2)
  5310. Article.objects.create(id=target_value, name="Django2", blog=blog2)
  5311. create_blog = migrations.CreateModel(
  5312. "Blog",
  5313. [
  5314. ("id", source_field(primary_key=True)),
  5315. ("name", models.CharField(max_length=100)),
  5316. ],
  5317. options={},
  5318. )
  5319. create_article = migrations.CreateModel(
  5320. "Article",
  5321. [
  5322. ("id", source_field(primary_key=True)),
  5323. (
  5324. "blog",
  5325. models.ForeignKey(to="test_blog.Blog", on_delete=models.CASCADE),
  5326. ),
  5327. ("name", models.CharField(max_length=100)),
  5328. ("data", models.TextField(default="")),
  5329. ],
  5330. options={},
  5331. )
  5332. fill_initial_data = migrations.RunPython(
  5333. create_initial_data, create_initial_data
  5334. )
  5335. fill_big_data = migrations.RunPython(create_big_data, create_big_data)
  5336. grow_article_id = migrations.AlterField(
  5337. "Article", "id", target_field(primary_key=True)
  5338. )
  5339. grow_blog_id = migrations.AlterField(
  5340. "Blog", "id", target_field(primary_key=True)
  5341. )
  5342. project_state = ProjectState()
  5343. new_state = project_state.clone()
  5344. with connection.schema_editor() as editor:
  5345. create_blog.state_forwards("test_blog", new_state)
  5346. create_blog.database_forwards("test_blog", editor, project_state, new_state)
  5347. project_state = new_state
  5348. new_state = new_state.clone()
  5349. with connection.schema_editor() as editor:
  5350. create_article.state_forwards("test_article", new_state)
  5351. create_article.database_forwards(
  5352. "test_article", editor, project_state, new_state
  5353. )
  5354. project_state = new_state
  5355. new_state = new_state.clone()
  5356. with connection.schema_editor() as editor:
  5357. fill_initial_data.state_forwards("fill_initial_data", new_state)
  5358. fill_initial_data.database_forwards(
  5359. "fill_initial_data", editor, project_state, new_state
  5360. )
  5361. project_state = new_state
  5362. new_state = new_state.clone()
  5363. with connection.schema_editor() as editor:
  5364. grow_article_id.state_forwards("test_article", new_state)
  5365. grow_article_id.database_forwards(
  5366. "test_article", editor, project_state, new_state
  5367. )
  5368. state = new_state.clone()
  5369. article = state.apps.get_model("test_article.Article")
  5370. self.assertIsInstance(article._meta.pk, target_field)
  5371. project_state = new_state
  5372. new_state = new_state.clone()
  5373. with connection.schema_editor() as editor:
  5374. grow_blog_id.state_forwards("test_blog", new_state)
  5375. grow_blog_id.database_forwards(
  5376. "test_blog", editor, project_state, new_state
  5377. )
  5378. state = new_state.clone()
  5379. blog = state.apps.get_model("test_blog.Blog")
  5380. self.assertIsInstance(blog._meta.pk, target_field)
  5381. project_state = new_state
  5382. new_state = new_state.clone()
  5383. with connection.schema_editor() as editor:
  5384. fill_big_data.state_forwards("fill_big_data", new_state)
  5385. fill_big_data.database_forwards(
  5386. "fill_big_data", editor, project_state, new_state
  5387. )
  5388. def test_autofield__bigautofield_foreignfield_growth(self):
  5389. """A field may be migrated from AutoField to BigAutoField."""
  5390. self._test_autofield_foreignfield_growth(
  5391. models.AutoField,
  5392. models.BigAutoField,
  5393. 2**33,
  5394. )
  5395. def test_smallfield_autofield_foreignfield_growth(self):
  5396. """A field may be migrated from SmallAutoField to AutoField."""
  5397. self._test_autofield_foreignfield_growth(
  5398. models.SmallAutoField,
  5399. models.AutoField,
  5400. 2**22,
  5401. )
  5402. def test_smallfield_bigautofield_foreignfield_growth(self):
  5403. """A field may be migrated from SmallAutoField to BigAutoField."""
  5404. self._test_autofield_foreignfield_growth(
  5405. models.SmallAutoField,
  5406. models.BigAutoField,
  5407. 2**33,
  5408. )
  5409. def test_run_python_noop(self):
  5410. """
  5411. #24098 - Tests no-op RunPython operations.
  5412. """
  5413. project_state = ProjectState()
  5414. new_state = project_state.clone()
  5415. operation = migrations.RunPython(
  5416. migrations.RunPython.noop, migrations.RunPython.noop
  5417. )
  5418. with connection.schema_editor() as editor:
  5419. operation.database_forwards(
  5420. "test_runpython", editor, project_state, new_state
  5421. )
  5422. operation.database_backwards(
  5423. "test_runpython", editor, new_state, project_state
  5424. )
  5425. def test_separate_database_and_state(self):
  5426. """
  5427. Tests the SeparateDatabaseAndState operation.
  5428. """
  5429. project_state = self.set_up_test_model("test_separatedatabaseandstate")
  5430. # Create the operation
  5431. database_operation = migrations.RunSQL(
  5432. "CREATE TABLE i_love_ponies (id int, special_thing int);",
  5433. "DROP TABLE i_love_ponies;",
  5434. )
  5435. state_operation = migrations.CreateModel(
  5436. "SomethingElse", [("id", models.AutoField(primary_key=True))]
  5437. )
  5438. operation = migrations.SeparateDatabaseAndState(
  5439. state_operations=[state_operation], database_operations=[database_operation]
  5440. )
  5441. self.assertEqual(
  5442. operation.describe(), "Custom state/database change combination"
  5443. )
  5444. # Test the state alteration
  5445. new_state = project_state.clone()
  5446. operation.state_forwards("test_separatedatabaseandstate", new_state)
  5447. self.assertEqual(
  5448. len(
  5449. new_state.models[
  5450. "test_separatedatabaseandstate", "somethingelse"
  5451. ].fields
  5452. ),
  5453. 1,
  5454. )
  5455. # Make sure there's no table
  5456. self.assertTableNotExists("i_love_ponies")
  5457. # Test the database alteration
  5458. with connection.schema_editor() as editor:
  5459. operation.database_forwards(
  5460. "test_separatedatabaseandstate", editor, project_state, new_state
  5461. )
  5462. self.assertTableExists("i_love_ponies")
  5463. # And test reversal
  5464. self.assertTrue(operation.reversible)
  5465. with connection.schema_editor() as editor:
  5466. operation.database_backwards(
  5467. "test_separatedatabaseandstate", editor, new_state, project_state
  5468. )
  5469. self.assertTableNotExists("i_love_ponies")
  5470. # And deconstruction
  5471. definition = operation.deconstruct()
  5472. self.assertEqual(definition[0], "SeparateDatabaseAndState")
  5473. self.assertEqual(definition[1], [])
  5474. self.assertEqual(
  5475. sorted(definition[2]), ["database_operations", "state_operations"]
  5476. )
  5477. def test_separate_database_and_state2(self):
  5478. """
  5479. A complex SeparateDatabaseAndState operation: Multiple operations both
  5480. for state and database. Verify the state dependencies within each list
  5481. and that state ops don't affect the database.
  5482. """
  5483. app_label = "test_separatedatabaseandstate2"
  5484. project_state = self.set_up_test_model(app_label)
  5485. # Create the operation
  5486. database_operations = [
  5487. migrations.CreateModel(
  5488. "ILovePonies",
  5489. [("id", models.AutoField(primary_key=True))],
  5490. options={"db_table": "iloveponies"},
  5491. ),
  5492. migrations.CreateModel(
  5493. "ILoveMorePonies",
  5494. # We use IntegerField and not AutoField because
  5495. # the model is going to be deleted immediately
  5496. # and with an AutoField this fails on Oracle
  5497. [("id", models.IntegerField(primary_key=True))],
  5498. options={"db_table": "ilovemoreponies"},
  5499. ),
  5500. migrations.DeleteModel("ILoveMorePonies"),
  5501. migrations.CreateModel(
  5502. "ILoveEvenMorePonies",
  5503. [("id", models.AutoField(primary_key=True))],
  5504. options={"db_table": "iloveevenmoreponies"},
  5505. ),
  5506. ]
  5507. state_operations = [
  5508. migrations.CreateModel(
  5509. "SomethingElse",
  5510. [("id", models.AutoField(primary_key=True))],
  5511. options={"db_table": "somethingelse"},
  5512. ),
  5513. migrations.DeleteModel("SomethingElse"),
  5514. migrations.CreateModel(
  5515. "SomethingCompletelyDifferent",
  5516. [("id", models.AutoField(primary_key=True))],
  5517. options={"db_table": "somethingcompletelydifferent"},
  5518. ),
  5519. ]
  5520. operation = migrations.SeparateDatabaseAndState(
  5521. state_operations=state_operations,
  5522. database_operations=database_operations,
  5523. )
  5524. # Test the state alteration
  5525. new_state = project_state.clone()
  5526. operation.state_forwards(app_label, new_state)
  5527. def assertModelsAndTables(after_db):
  5528. # Tables and models exist, or don't, as they should:
  5529. self.assertNotIn((app_label, "somethingelse"), new_state.models)
  5530. self.assertEqual(
  5531. len(new_state.models[app_label, "somethingcompletelydifferent"].fields),
  5532. 1,
  5533. )
  5534. self.assertNotIn((app_label, "iloveponiesonies"), new_state.models)
  5535. self.assertNotIn((app_label, "ilovemoreponies"), new_state.models)
  5536. self.assertNotIn((app_label, "iloveevenmoreponies"), new_state.models)
  5537. self.assertTableNotExists("somethingelse")
  5538. self.assertTableNotExists("somethingcompletelydifferent")
  5539. self.assertTableNotExists("ilovemoreponies")
  5540. if after_db:
  5541. self.assertTableExists("iloveponies")
  5542. self.assertTableExists("iloveevenmoreponies")
  5543. else:
  5544. self.assertTableNotExists("iloveponies")
  5545. self.assertTableNotExists("iloveevenmoreponies")
  5546. assertModelsAndTables(after_db=False)
  5547. # Test the database alteration
  5548. with connection.schema_editor() as editor:
  5549. operation.database_forwards(app_label, editor, project_state, new_state)
  5550. assertModelsAndTables(after_db=True)
  5551. # And test reversal
  5552. self.assertTrue(operation.reversible)
  5553. with connection.schema_editor() as editor:
  5554. operation.database_backwards(app_label, editor, new_state, project_state)
  5555. assertModelsAndTables(after_db=False)
  5556. def _test_invalid_generated_field_changes(self, db_persist):
  5557. regular = models.IntegerField(default=1)
  5558. generated_1 = models.GeneratedField(
  5559. expression=F("pink") + F("pink"),
  5560. output_field=models.IntegerField(),
  5561. db_persist=db_persist,
  5562. )
  5563. generated_2 = models.GeneratedField(
  5564. expression=F("pink") + F("pink") + F("pink"),
  5565. output_field=models.IntegerField(),
  5566. db_persist=db_persist,
  5567. )
  5568. tests = [
  5569. ("test_igfc_1", regular, generated_1),
  5570. ("test_igfc_2", generated_1, regular),
  5571. ("test_igfc_3", generated_1, generated_2),
  5572. ]
  5573. for app_label, add_field, alter_field in tests:
  5574. project_state = self.set_up_test_model(app_label)
  5575. operations = [
  5576. migrations.AddField("Pony", "modified_pink", add_field),
  5577. migrations.AlterField("Pony", "modified_pink", alter_field),
  5578. ]
  5579. msg = (
  5580. "Modifying GeneratedFields is not supported - the field "
  5581. f"{app_label}.Pony.modified_pink must be removed and re-added with the "
  5582. "new definition."
  5583. )
  5584. with self.assertRaisesMessage(ValueError, msg):
  5585. self.apply_operations(app_label, project_state, operations)
  5586. @skipUnlessDBFeature("supports_stored_generated_columns")
  5587. def test_invalid_generated_field_changes_stored(self):
  5588. self._test_invalid_generated_field_changes(db_persist=True)
  5589. @skipUnlessDBFeature("supports_virtual_generated_columns")
  5590. def test_invalid_generated_field_changes_virtual(self):
  5591. self._test_invalid_generated_field_changes(db_persist=False)
  5592. @skipUnlessDBFeature(
  5593. "supports_stored_generated_columns",
  5594. "supports_virtual_generated_columns",
  5595. )
  5596. def test_invalid_generated_field_persistency_change(self):
  5597. app_label = "test_igfpc"
  5598. project_state = self.set_up_test_model(app_label)
  5599. operations = [
  5600. migrations.AddField(
  5601. "Pony",
  5602. "modified_pink",
  5603. models.GeneratedField(
  5604. expression=F("pink"),
  5605. output_field=models.IntegerField(),
  5606. db_persist=True,
  5607. ),
  5608. ),
  5609. migrations.AlterField(
  5610. "Pony",
  5611. "modified_pink",
  5612. models.GeneratedField(
  5613. expression=F("pink"),
  5614. output_field=models.IntegerField(),
  5615. db_persist=False,
  5616. ),
  5617. ),
  5618. ]
  5619. msg = (
  5620. "Modifying GeneratedFields is not supported - the field "
  5621. f"{app_label}.Pony.modified_pink must be removed and re-added with the "
  5622. "new definition."
  5623. )
  5624. with self.assertRaisesMessage(ValueError, msg):
  5625. self.apply_operations(app_label, project_state, operations)
  5626. def _test_add_generated_field(self, db_persist):
  5627. app_label = "test_agf"
  5628. operation = migrations.AddField(
  5629. "Pony",
  5630. "modified_pink",
  5631. models.GeneratedField(
  5632. expression=F("pink") + F("pink"),
  5633. output_field=models.IntegerField(),
  5634. db_persist=db_persist,
  5635. ),
  5636. )
  5637. project_state, new_state = self.make_test_state(app_label, operation)
  5638. self.assertEqual(len(new_state.models[app_label, "pony"].fields), 6)
  5639. # Add generated column.
  5640. with connection.schema_editor() as editor:
  5641. operation.database_forwards(app_label, editor, project_state, new_state)
  5642. self.assertColumnExists(f"{app_label}_pony", "modified_pink")
  5643. Pony = new_state.apps.get_model(app_label, "Pony")
  5644. obj = Pony.objects.create(pink=5, weight=3.23)
  5645. self.assertEqual(obj.modified_pink, 10)
  5646. # Reversal.
  5647. with connection.schema_editor() as editor:
  5648. operation.database_backwards(app_label, editor, new_state, project_state)
  5649. self.assertColumnNotExists(f"{app_label}_pony", "modified_pink")
  5650. @skipUnlessDBFeature("supports_stored_generated_columns")
  5651. def test_add_generated_field_stored(self):
  5652. self._test_add_generated_field(db_persist=True)
  5653. @skipUnlessDBFeature("supports_virtual_generated_columns")
  5654. def test_add_generated_field_virtual(self):
  5655. self._test_add_generated_field(db_persist=False)
  5656. def _test_remove_generated_field(self, db_persist):
  5657. app_label = "test_rgf"
  5658. operation = migrations.AddField(
  5659. "Pony",
  5660. "modified_pink",
  5661. models.GeneratedField(
  5662. expression=F("pink") + F("pink"),
  5663. output_field=models.IntegerField(),
  5664. db_persist=db_persist,
  5665. ),
  5666. )
  5667. project_state, new_state = self.make_test_state(app_label, operation)
  5668. self.assertEqual(len(new_state.models[app_label, "pony"].fields), 6)
  5669. # Add generated column.
  5670. with connection.schema_editor() as editor:
  5671. operation.database_forwards(app_label, editor, project_state, new_state)
  5672. project_state = new_state
  5673. new_state = project_state.clone()
  5674. operation = migrations.RemoveField("Pony", "modified_pink")
  5675. operation.state_forwards(app_label, new_state)
  5676. # Remove generated column.
  5677. with connection.schema_editor() as editor:
  5678. operation.database_forwards(app_label, editor, project_state, new_state)
  5679. self.assertColumnNotExists(f"{app_label}_pony", "modified_pink")
  5680. @skipUnlessDBFeature("supports_stored_generated_columns")
  5681. def test_remove_generated_field_stored(self):
  5682. self._test_remove_generated_field(db_persist=True)
  5683. @skipUnlessDBFeature("supports_virtual_generated_columns")
  5684. def test_remove_generated_field_virtual(self):
  5685. self._test_remove_generated_field(db_persist=False)
  5686. class SwappableOperationTests(OperationTestBase):
  5687. """
  5688. Key operations ignore swappable models
  5689. (we don't want to replicate all of them here, as the functionality
  5690. is in a common base class anyway)
  5691. """
  5692. available_apps = ["migrations"]
  5693. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  5694. def test_create_ignore_swapped(self):
  5695. """
  5696. The CreateTable operation ignores swapped models.
  5697. """
  5698. operation = migrations.CreateModel(
  5699. "Pony",
  5700. [
  5701. ("id", models.AutoField(primary_key=True)),
  5702. ("pink", models.IntegerField(default=1)),
  5703. ],
  5704. options={
  5705. "swappable": "TEST_SWAP_MODEL",
  5706. },
  5707. )
  5708. # Test the state alteration (it should still be there!)
  5709. project_state = ProjectState()
  5710. new_state = project_state.clone()
  5711. operation.state_forwards("test_crigsw", new_state)
  5712. self.assertEqual(new_state.models["test_crigsw", "pony"].name, "Pony")
  5713. self.assertEqual(len(new_state.models["test_crigsw", "pony"].fields), 2)
  5714. # Test the database alteration
  5715. self.assertTableNotExists("test_crigsw_pony")
  5716. with connection.schema_editor() as editor:
  5717. operation.database_forwards("test_crigsw", editor, project_state, new_state)
  5718. self.assertTableNotExists("test_crigsw_pony")
  5719. # And test reversal
  5720. with connection.schema_editor() as editor:
  5721. operation.database_backwards(
  5722. "test_crigsw", editor, new_state, project_state
  5723. )
  5724. self.assertTableNotExists("test_crigsw_pony")
  5725. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  5726. def test_delete_ignore_swapped(self):
  5727. """
  5728. Tests the DeleteModel operation ignores swapped models.
  5729. """
  5730. operation = migrations.DeleteModel("Pony")
  5731. project_state, new_state = self.make_test_state("test_dligsw", operation)
  5732. # Test the database alteration
  5733. self.assertTableNotExists("test_dligsw_pony")
  5734. with connection.schema_editor() as editor:
  5735. operation.database_forwards("test_dligsw", editor, project_state, new_state)
  5736. self.assertTableNotExists("test_dligsw_pony")
  5737. # And test reversal
  5738. with connection.schema_editor() as editor:
  5739. operation.database_backwards(
  5740. "test_dligsw", editor, new_state, project_state
  5741. )
  5742. self.assertTableNotExists("test_dligsw_pony")
  5743. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  5744. def test_add_field_ignore_swapped(self):
  5745. """
  5746. Tests the AddField operation.
  5747. """
  5748. # Test the state alteration
  5749. operation = migrations.AddField(
  5750. "Pony",
  5751. "height",
  5752. models.FloatField(null=True, default=5),
  5753. )
  5754. project_state, new_state = self.make_test_state("test_adfligsw", operation)
  5755. # Test the database alteration
  5756. self.assertTableNotExists("test_adfligsw_pony")
  5757. with connection.schema_editor() as editor:
  5758. operation.database_forwards(
  5759. "test_adfligsw", editor, project_state, new_state
  5760. )
  5761. self.assertTableNotExists("test_adfligsw_pony")
  5762. # And test reversal
  5763. with connection.schema_editor() as editor:
  5764. operation.database_backwards(
  5765. "test_adfligsw", editor, new_state, project_state
  5766. )
  5767. self.assertTableNotExists("test_adfligsw_pony")
  5768. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  5769. def test_indexes_ignore_swapped(self):
  5770. """
  5771. Add/RemoveIndex operations ignore swapped models.
  5772. """
  5773. operation = migrations.AddIndex(
  5774. "Pony", models.Index(fields=["pink"], name="my_name_idx")
  5775. )
  5776. project_state, new_state = self.make_test_state("test_adinigsw", operation)
  5777. with connection.schema_editor() as editor:
  5778. # No database queries should be run for swapped models
  5779. operation.database_forwards(
  5780. "test_adinigsw", editor, project_state, new_state
  5781. )
  5782. operation.database_backwards(
  5783. "test_adinigsw", editor, new_state, project_state
  5784. )
  5785. operation = migrations.RemoveIndex(
  5786. "Pony", models.Index(fields=["pink"], name="my_name_idx")
  5787. )
  5788. project_state, new_state = self.make_test_state("test_rminigsw", operation)
  5789. with connection.schema_editor() as editor:
  5790. operation.database_forwards(
  5791. "test_rminigsw", editor, project_state, new_state
  5792. )
  5793. operation.database_backwards(
  5794. "test_rminigsw", editor, new_state, project_state
  5795. )
  5796. class TestCreateModel(SimpleTestCase):
  5797. def test_references_model_mixin(self):
  5798. migrations.CreateModel(
  5799. "name",
  5800. fields=[],
  5801. bases=(Mixin, models.Model),
  5802. ).references_model("other_model", "migrations")
  5803. class FieldOperationTests(SimpleTestCase):
  5804. def test_references_model(self):
  5805. operation = FieldOperation(
  5806. "MoDel", "field", models.ForeignKey("Other", models.CASCADE)
  5807. )
  5808. # Model name match.
  5809. self.assertIs(operation.references_model("mOdEl", "migrations"), True)
  5810. # Referenced field.
  5811. self.assertIs(operation.references_model("oTher", "migrations"), True)
  5812. # Doesn't reference.
  5813. self.assertIs(operation.references_model("Whatever", "migrations"), False)
  5814. def test_references_field_by_name(self):
  5815. operation = FieldOperation("MoDel", "field", models.BooleanField(default=False))
  5816. self.assertIs(operation.references_field("model", "field", "migrations"), True)
  5817. def test_references_field_by_remote_field_model(self):
  5818. operation = FieldOperation(
  5819. "Model", "field", models.ForeignKey("Other", models.CASCADE)
  5820. )
  5821. self.assertIs(
  5822. operation.references_field("Other", "whatever", "migrations"), True
  5823. )
  5824. self.assertIs(
  5825. operation.references_field("Missing", "whatever", "migrations"), False
  5826. )
  5827. def test_references_field_by_from_fields(self):
  5828. operation = FieldOperation(
  5829. "Model",
  5830. "field",
  5831. models.fields.related.ForeignObject(
  5832. "Other", models.CASCADE, ["from"], ["to"]
  5833. ),
  5834. )
  5835. self.assertIs(operation.references_field("Model", "from", "migrations"), True)
  5836. self.assertIs(operation.references_field("Model", "to", "migrations"), False)
  5837. self.assertIs(operation.references_field("Other", "from", "migrations"), False)
  5838. self.assertIs(operation.references_field("Model", "to", "migrations"), False)
  5839. def test_references_field_by_to_fields(self):
  5840. operation = FieldOperation(
  5841. "Model",
  5842. "field",
  5843. models.ForeignKey("Other", models.CASCADE, to_field="field"),
  5844. )
  5845. self.assertIs(operation.references_field("Other", "field", "migrations"), True)
  5846. self.assertIs(
  5847. operation.references_field("Other", "whatever", "migrations"), False
  5848. )
  5849. self.assertIs(
  5850. operation.references_field("Missing", "whatever", "migrations"), False
  5851. )
  5852. def test_references_field_by_through(self):
  5853. operation = FieldOperation(
  5854. "Model", "field", models.ManyToManyField("Other", through="Through")
  5855. )
  5856. self.assertIs(
  5857. operation.references_field("Other", "whatever", "migrations"), True
  5858. )
  5859. self.assertIs(
  5860. operation.references_field("Through", "whatever", "migrations"), True
  5861. )
  5862. self.assertIs(
  5863. operation.references_field("Missing", "whatever", "migrations"), False
  5864. )
  5865. def test_reference_field_by_through_fields(self):
  5866. operation = FieldOperation(
  5867. "Model",
  5868. "field",
  5869. models.ManyToManyField(
  5870. "Other", through="Through", through_fields=("first", "second")
  5871. ),
  5872. )
  5873. self.assertIs(
  5874. operation.references_field("Other", "whatever", "migrations"), True
  5875. )
  5876. self.assertIs(
  5877. operation.references_field("Through", "whatever", "migrations"), False
  5878. )
  5879. self.assertIs(
  5880. operation.references_field("Through", "first", "migrations"), True
  5881. )
  5882. self.assertIs(
  5883. operation.references_field("Through", "second", "migrations"), True
  5884. )