test_operations.py 252 KB

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