test_operations.py 245 KB

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