test_operations.py 224 KB

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