test_operations.py 247 KB

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