tests.py 223 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459
  1. import datetime
  2. import itertools
  3. import unittest
  4. from copy import copy
  5. from decimal import Decimal
  6. from unittest import mock
  7. from django.core.exceptions import FieldError
  8. from django.core.management.color import no_style
  9. from django.db import (
  10. DatabaseError,
  11. DataError,
  12. IntegrityError,
  13. OperationalError,
  14. connection,
  15. )
  16. from django.db.backends.utils import truncate_name
  17. from django.db.models import (
  18. CASCADE,
  19. PROTECT,
  20. AutoField,
  21. BigAutoField,
  22. BigIntegerField,
  23. BinaryField,
  24. BooleanField,
  25. CharField,
  26. CheckConstraint,
  27. DateField,
  28. DateTimeField,
  29. DecimalField,
  30. DurationField,
  31. F,
  32. FloatField,
  33. ForeignKey,
  34. ForeignObject,
  35. GeneratedField,
  36. Index,
  37. IntegerField,
  38. JSONField,
  39. ManyToManyField,
  40. Model,
  41. OneToOneField,
  42. OrderBy,
  43. PositiveIntegerField,
  44. Q,
  45. SlugField,
  46. SmallAutoField,
  47. SmallIntegerField,
  48. TextField,
  49. TimeField,
  50. UniqueConstraint,
  51. UUIDField,
  52. Value,
  53. )
  54. from django.db.models.fields.json import KT, KeyTextTransform
  55. from django.db.models.functions import Abs, Cast, Collate, Lower, Random, Round, Upper
  56. from django.db.models.indexes import IndexExpression
  57. from django.db.transaction import TransactionManagementError, atomic
  58. from django.test import TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature
  59. from django.test.utils import CaptureQueriesContext, isolate_apps, register_lookup
  60. from .fields import CustomManyToManyField, InheritedManyToManyField, MediumBlobField
  61. from .models import (
  62. Author,
  63. AuthorCharFieldWithIndex,
  64. AuthorTextFieldWithIndex,
  65. AuthorWithDefaultHeight,
  66. AuthorWithEvenLongerName,
  67. AuthorWithIndexedName,
  68. AuthorWithUniqueName,
  69. AuthorWithUniqueNameAndBirthday,
  70. Book,
  71. BookForeignObj,
  72. BookWeak,
  73. BookWithLongName,
  74. BookWithO2O,
  75. BookWithoutAuthor,
  76. BookWithSlug,
  77. IntegerPK,
  78. Node,
  79. Note,
  80. NoteRename,
  81. Tag,
  82. TagM2MTest,
  83. TagUniqueRename,
  84. Thing,
  85. UniqueTest,
  86. new_apps,
  87. )
  88. class SchemaTests(TransactionTestCase):
  89. """
  90. Tests for the schema-alteration code.
  91. Be aware that these tests are more liable than most to false results,
  92. as sometimes the code to check if a test has worked is almost as complex
  93. as the code it is testing.
  94. """
  95. available_apps = []
  96. models = [
  97. Author,
  98. AuthorCharFieldWithIndex,
  99. AuthorTextFieldWithIndex,
  100. AuthorWithDefaultHeight,
  101. AuthorWithEvenLongerName,
  102. Book,
  103. BookWeak,
  104. BookWithLongName,
  105. BookWithO2O,
  106. BookWithSlug,
  107. IntegerPK,
  108. Node,
  109. Note,
  110. Tag,
  111. TagM2MTest,
  112. TagUniqueRename,
  113. Thing,
  114. UniqueTest,
  115. ]
  116. # Utility functions
  117. def setUp(self):
  118. # local_models should contain test dependent model classes that will be
  119. # automatically removed from the app cache on test tear down.
  120. self.local_models = []
  121. # isolated_local_models contains models that are in test methods
  122. # decorated with @isolate_apps.
  123. self.isolated_local_models = []
  124. def tearDown(self):
  125. # Delete any tables made for our models
  126. self.delete_tables()
  127. new_apps.clear_cache()
  128. for model in new_apps.get_models():
  129. model._meta._expire_cache()
  130. if "schema" in new_apps.all_models:
  131. for model in self.local_models:
  132. for many_to_many in model._meta.many_to_many:
  133. through = many_to_many.remote_field.through
  134. if through and through._meta.auto_created:
  135. del new_apps.all_models["schema"][through._meta.model_name]
  136. del new_apps.all_models["schema"][model._meta.model_name]
  137. if self.isolated_local_models:
  138. with connection.schema_editor() as editor:
  139. for model in self.isolated_local_models:
  140. editor.delete_model(model)
  141. def delete_tables(self):
  142. "Deletes all model tables for our models for a clean test environment"
  143. converter = connection.introspection.identifier_converter
  144. with connection.schema_editor() as editor:
  145. connection.disable_constraint_checking()
  146. table_names = connection.introspection.table_names()
  147. if connection.features.ignores_table_name_case:
  148. table_names = [table_name.lower() for table_name in table_names]
  149. for model in itertools.chain(SchemaTests.models, self.local_models):
  150. tbl = converter(model._meta.db_table)
  151. if connection.features.ignores_table_name_case:
  152. tbl = tbl.lower()
  153. if tbl in table_names:
  154. editor.delete_model(model)
  155. table_names.remove(tbl)
  156. connection.enable_constraint_checking()
  157. def column_classes(self, model):
  158. with connection.cursor() as cursor:
  159. columns = {
  160. d[0]: (connection.introspection.get_field_type(d[1], d), d)
  161. for d in connection.introspection.get_table_description(
  162. cursor,
  163. model._meta.db_table,
  164. )
  165. }
  166. # SQLite has a different format for field_type
  167. for name, (type, desc) in columns.items():
  168. if isinstance(type, tuple):
  169. columns[name] = (type[0], desc)
  170. return columns
  171. def get_primary_key(self, table):
  172. with connection.cursor() as cursor:
  173. return connection.introspection.get_primary_key_column(cursor, table)
  174. def get_indexes(self, table):
  175. """
  176. Get the indexes on the table using a new cursor.
  177. """
  178. with connection.cursor() as cursor:
  179. return [
  180. c["columns"][0]
  181. for c in connection.introspection.get_constraints(
  182. cursor, table
  183. ).values()
  184. if c["index"] and len(c["columns"]) == 1
  185. ]
  186. def get_uniques(self, table):
  187. with connection.cursor() as cursor:
  188. return [
  189. c["columns"][0]
  190. for c in connection.introspection.get_constraints(
  191. cursor, table
  192. ).values()
  193. if c["unique"] and len(c["columns"]) == 1
  194. ]
  195. def get_constraints(self, table):
  196. """
  197. Get the constraints on a table using a new cursor.
  198. """
  199. with connection.cursor() as cursor:
  200. return connection.introspection.get_constraints(cursor, table)
  201. def get_constraints_for_column(self, model, column_name):
  202. constraints = self.get_constraints(model._meta.db_table)
  203. constraints_for_column = []
  204. for name, details in constraints.items():
  205. if details["columns"] == [column_name]:
  206. constraints_for_column.append(name)
  207. return sorted(constraints_for_column)
  208. def get_constraint_opclasses(self, constraint_name):
  209. with connection.cursor() as cursor:
  210. sql = """
  211. SELECT opcname
  212. FROM pg_opclass AS oc
  213. JOIN pg_index as i on oc.oid = ANY(i.indclass)
  214. JOIN pg_class as c on c.oid = i.indexrelid
  215. WHERE c.relname = %s
  216. """
  217. cursor.execute(sql, [constraint_name])
  218. return [row[0] for row in cursor.fetchall()]
  219. def check_added_field_default(
  220. self,
  221. schema_editor,
  222. model,
  223. field,
  224. field_name,
  225. expected_default,
  226. cast_function=None,
  227. ):
  228. with connection.cursor() as cursor:
  229. schema_editor.add_field(model, field)
  230. cursor.execute(
  231. "SELECT {} FROM {};".format(field_name, model._meta.db_table)
  232. )
  233. database_default = cursor.fetchall()[0][0]
  234. if cast_function and type(database_default) is not type(expected_default):
  235. database_default = cast_function(database_default)
  236. self.assertEqual(database_default, expected_default)
  237. def get_constraints_count(self, table, column, fk_to):
  238. """
  239. Return a dict with keys 'fks', 'uniques, and 'indexes' indicating the
  240. number of foreign keys, unique constraints, and indexes on
  241. `table`.`column`. The `fk_to` argument is a 2-tuple specifying the
  242. expected foreign key relationship's (table, column).
  243. """
  244. with connection.cursor() as cursor:
  245. constraints = connection.introspection.get_constraints(cursor, table)
  246. counts = {"fks": 0, "uniques": 0, "indexes": 0}
  247. for c in constraints.values():
  248. if c["columns"] == [column]:
  249. if c["foreign_key"] == fk_to:
  250. counts["fks"] += 1
  251. if c["unique"]:
  252. counts["uniques"] += 1
  253. elif c["index"]:
  254. counts["indexes"] += 1
  255. return counts
  256. def get_column_collation(self, table, column):
  257. with connection.cursor() as cursor:
  258. return next(
  259. f.collation
  260. for f in connection.introspection.get_table_description(cursor, table)
  261. if f.name == column
  262. )
  263. def get_column_comment(self, table, column):
  264. with connection.cursor() as cursor:
  265. return next(
  266. f.comment
  267. for f in connection.introspection.get_table_description(cursor, table)
  268. if f.name == column
  269. )
  270. def get_table_comment(self, table):
  271. with connection.cursor() as cursor:
  272. return next(
  273. t.comment
  274. for t in connection.introspection.get_table_list(cursor)
  275. if t.name == table
  276. )
  277. def assert_column_comment_not_exists(self, table, column):
  278. with connection.cursor() as cursor:
  279. columns = connection.introspection.get_table_description(cursor, table)
  280. self.assertFalse(any([c.name == column and c.comment for c in columns]))
  281. def assertIndexOrder(self, table, index, order):
  282. constraints = self.get_constraints(table)
  283. self.assertIn(index, constraints)
  284. index_orders = constraints[index]["orders"]
  285. self.assertTrue(
  286. all(val == expected for val, expected in zip(index_orders, order))
  287. )
  288. def assertForeignKeyExists(self, model, column, expected_fk_table, field="id"):
  289. """
  290. Fail if the FK constraint on `model.Meta.db_table`.`column` to
  291. `expected_fk_table`.id doesn't exist.
  292. """
  293. if not connection.features.can_introspect_foreign_keys:
  294. return
  295. constraints = self.get_constraints(model._meta.db_table)
  296. constraint_fk = None
  297. for details in constraints.values():
  298. if details["columns"] == [column] and details["foreign_key"]:
  299. constraint_fk = details["foreign_key"]
  300. break
  301. self.assertEqual(constraint_fk, (expected_fk_table, field))
  302. def assertForeignKeyNotExists(self, model, column, expected_fk_table):
  303. if not connection.features.can_introspect_foreign_keys:
  304. return
  305. with self.assertRaises(AssertionError):
  306. self.assertForeignKeyExists(model, column, expected_fk_table)
  307. # Tests
  308. def test_creation_deletion(self):
  309. """
  310. Tries creating a model's table, and then deleting it.
  311. """
  312. with connection.schema_editor() as editor:
  313. # Create the table
  314. editor.create_model(Author)
  315. # The table is there
  316. list(Author.objects.all())
  317. # Clean up that table
  318. editor.delete_model(Author)
  319. # No deferred SQL should be left over.
  320. self.assertEqual(editor.deferred_sql, [])
  321. # The table is gone
  322. with self.assertRaises(DatabaseError):
  323. list(Author.objects.all())
  324. @skipUnlessDBFeature("supports_foreign_keys")
  325. def test_fk(self):
  326. "Creating tables out of FK order, then repointing, works"
  327. # Create the table
  328. with connection.schema_editor() as editor:
  329. editor.create_model(Book)
  330. editor.create_model(Author)
  331. editor.create_model(Tag)
  332. # Initial tables are there
  333. list(Author.objects.all())
  334. list(Book.objects.all())
  335. # Make sure the FK constraint is present
  336. with self.assertRaises(IntegrityError):
  337. Book.objects.create(
  338. author_id=1,
  339. title="Much Ado About Foreign Keys",
  340. pub_date=datetime.datetime.now(),
  341. )
  342. # Repoint the FK constraint
  343. old_field = Book._meta.get_field("author")
  344. new_field = ForeignKey(Tag, CASCADE)
  345. new_field.set_attributes_from_name("author")
  346. with connection.schema_editor() as editor:
  347. editor.alter_field(Book, old_field, new_field, strict=True)
  348. self.assertForeignKeyExists(Book, "author_id", "schema_tag")
  349. @skipUnlessDBFeature("can_create_inline_fk")
  350. def test_inline_fk(self):
  351. # Create some tables.
  352. with connection.schema_editor() as editor:
  353. editor.create_model(Author)
  354. editor.create_model(Book)
  355. editor.create_model(Note)
  356. self.assertForeignKeyNotExists(Note, "book_id", "schema_book")
  357. # Add a foreign key from one to the other.
  358. with connection.schema_editor() as editor:
  359. new_field = ForeignKey(Book, CASCADE)
  360. new_field.set_attributes_from_name("book")
  361. editor.add_field(Note, new_field)
  362. self.assertForeignKeyExists(Note, "book_id", "schema_book")
  363. # Creating a FK field with a constraint uses a single statement without
  364. # a deferred ALTER TABLE.
  365. self.assertFalse(
  366. [
  367. sql
  368. for sql in (str(statement) for statement in editor.deferred_sql)
  369. if sql.startswith("ALTER TABLE") and "ADD CONSTRAINT" in sql
  370. ]
  371. )
  372. @skipUnlessDBFeature("can_create_inline_fk")
  373. def test_add_inline_fk_update_data(self):
  374. with connection.schema_editor() as editor:
  375. editor.create_model(Node)
  376. # Add an inline foreign key and update data in the same transaction.
  377. new_field = ForeignKey(Node, CASCADE, related_name="new_fk", null=True)
  378. new_field.set_attributes_from_name("new_parent_fk")
  379. parent = Node.objects.create()
  380. with connection.schema_editor() as editor:
  381. editor.add_field(Node, new_field)
  382. editor.execute("UPDATE schema_node SET new_parent_fk_id = %s;", [parent.pk])
  383. assertIndex = (
  384. self.assertIn
  385. if connection.features.indexes_foreign_keys
  386. else self.assertNotIn
  387. )
  388. assertIndex("new_parent_fk_id", self.get_indexes(Node._meta.db_table))
  389. @skipUnlessDBFeature(
  390. "can_create_inline_fk",
  391. "allows_multiple_constraints_on_same_fields",
  392. )
  393. @isolate_apps("schema")
  394. def test_add_inline_fk_index_update_data(self):
  395. class Node(Model):
  396. class Meta:
  397. app_label = "schema"
  398. with connection.schema_editor() as editor:
  399. editor.create_model(Node)
  400. # Add an inline foreign key, update data, and an index in the same
  401. # transaction.
  402. new_field = ForeignKey(Node, CASCADE, related_name="new_fk", null=True)
  403. new_field.set_attributes_from_name("new_parent_fk")
  404. parent = Node.objects.create()
  405. with connection.schema_editor() as editor:
  406. editor.add_field(Node, new_field)
  407. Node._meta.add_field(new_field)
  408. editor.execute("UPDATE schema_node SET new_parent_fk_id = %s;", [parent.pk])
  409. editor.add_index(
  410. Node, Index(fields=["new_parent_fk"], name="new_parent_inline_fk_idx")
  411. )
  412. self.assertIn("new_parent_fk_id", self.get_indexes(Node._meta.db_table))
  413. @skipUnlessDBFeature("supports_foreign_keys")
  414. def test_char_field_with_db_index_to_fk(self):
  415. # Create the table
  416. with connection.schema_editor() as editor:
  417. editor.create_model(Author)
  418. editor.create_model(AuthorCharFieldWithIndex)
  419. # Change CharField to FK
  420. old_field = AuthorCharFieldWithIndex._meta.get_field("char_field")
  421. new_field = ForeignKey(Author, CASCADE, blank=True)
  422. new_field.set_attributes_from_name("char_field")
  423. with connection.schema_editor() as editor:
  424. editor.alter_field(
  425. AuthorCharFieldWithIndex, old_field, new_field, strict=True
  426. )
  427. self.assertForeignKeyExists(
  428. AuthorCharFieldWithIndex, "char_field_id", "schema_author"
  429. )
  430. @skipUnlessDBFeature("supports_foreign_keys")
  431. @skipUnlessDBFeature("supports_index_on_text_field")
  432. def test_text_field_with_db_index_to_fk(self):
  433. # Create the table
  434. with connection.schema_editor() as editor:
  435. editor.create_model(Author)
  436. editor.create_model(AuthorTextFieldWithIndex)
  437. # Change TextField to FK
  438. old_field = AuthorTextFieldWithIndex._meta.get_field("text_field")
  439. new_field = ForeignKey(Author, CASCADE, blank=True)
  440. new_field.set_attributes_from_name("text_field")
  441. with connection.schema_editor() as editor:
  442. editor.alter_field(
  443. AuthorTextFieldWithIndex, old_field, new_field, strict=True
  444. )
  445. self.assertForeignKeyExists(
  446. AuthorTextFieldWithIndex, "text_field_id", "schema_author"
  447. )
  448. @isolate_apps("schema")
  449. def test_char_field_pk_to_auto_field(self):
  450. class Foo(Model):
  451. id = CharField(max_length=255, primary_key=True)
  452. class Meta:
  453. app_label = "schema"
  454. with connection.schema_editor() as editor:
  455. editor.create_model(Foo)
  456. self.isolated_local_models = [Foo]
  457. old_field = Foo._meta.get_field("id")
  458. new_field = AutoField(primary_key=True)
  459. new_field.set_attributes_from_name("id")
  460. new_field.model = Foo
  461. with connection.schema_editor() as editor:
  462. editor.alter_field(Foo, old_field, new_field, strict=True)
  463. @skipUnlessDBFeature("supports_foreign_keys")
  464. def test_fk_to_proxy(self):
  465. "Creating a FK to a proxy model creates database constraints."
  466. class AuthorProxy(Author):
  467. class Meta:
  468. app_label = "schema"
  469. apps = new_apps
  470. proxy = True
  471. class AuthorRef(Model):
  472. author = ForeignKey(AuthorProxy, on_delete=CASCADE)
  473. class Meta:
  474. app_label = "schema"
  475. apps = new_apps
  476. self.local_models = [AuthorProxy, AuthorRef]
  477. # Create the table
  478. with connection.schema_editor() as editor:
  479. editor.create_model(Author)
  480. editor.create_model(AuthorRef)
  481. self.assertForeignKeyExists(AuthorRef, "author_id", "schema_author")
  482. @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys")
  483. def test_fk_db_constraint(self):
  484. "The db_constraint parameter is respected"
  485. # Create the table
  486. with connection.schema_editor() as editor:
  487. editor.create_model(Tag)
  488. editor.create_model(Author)
  489. editor.create_model(BookWeak)
  490. # Initial tables are there
  491. list(Author.objects.all())
  492. list(Tag.objects.all())
  493. list(BookWeak.objects.all())
  494. self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author")
  495. # Make a db_constraint=False FK
  496. new_field = ForeignKey(Tag, CASCADE, db_constraint=False)
  497. new_field.set_attributes_from_name("tag")
  498. with connection.schema_editor() as editor:
  499. editor.add_field(Author, new_field)
  500. self.assertForeignKeyNotExists(Author, "tag_id", "schema_tag")
  501. # Alter to one with a constraint
  502. new_field2 = ForeignKey(Tag, CASCADE)
  503. new_field2.set_attributes_from_name("tag")
  504. with connection.schema_editor() as editor:
  505. editor.alter_field(Author, new_field, new_field2, strict=True)
  506. self.assertForeignKeyExists(Author, "tag_id", "schema_tag")
  507. # Alter to one without a constraint again
  508. new_field2 = ForeignKey(Tag, CASCADE)
  509. new_field2.set_attributes_from_name("tag")
  510. with connection.schema_editor() as editor:
  511. editor.alter_field(Author, new_field2, new_field, strict=True)
  512. self.assertForeignKeyNotExists(Author, "tag_id", "schema_tag")
  513. @isolate_apps("schema")
  514. def test_no_db_constraint_added_during_primary_key_change(self):
  515. """
  516. When a primary key that's pointed to by a ForeignKey with
  517. db_constraint=False is altered, a foreign key constraint isn't added.
  518. """
  519. class Author(Model):
  520. class Meta:
  521. app_label = "schema"
  522. class BookWeak(Model):
  523. author = ForeignKey(Author, CASCADE, db_constraint=False)
  524. class Meta:
  525. app_label = "schema"
  526. with connection.schema_editor() as editor:
  527. editor.create_model(Author)
  528. editor.create_model(BookWeak)
  529. self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author")
  530. old_field = Author._meta.get_field("id")
  531. new_field = BigAutoField(primary_key=True)
  532. new_field.model = Author
  533. new_field.set_attributes_from_name("id")
  534. # @isolate_apps() and inner models are needed to have the model
  535. # relations populated, otherwise this doesn't act as a regression test.
  536. self.assertEqual(len(new_field.model._meta.related_objects), 1)
  537. with connection.schema_editor() as editor:
  538. editor.alter_field(Author, old_field, new_field, strict=True)
  539. self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author")
  540. def _test_m2m_db_constraint(self, M2MFieldClass):
  541. class LocalAuthorWithM2M(Model):
  542. name = CharField(max_length=255)
  543. class Meta:
  544. app_label = "schema"
  545. apps = new_apps
  546. self.local_models = [LocalAuthorWithM2M]
  547. # Create the table
  548. with connection.schema_editor() as editor:
  549. editor.create_model(Tag)
  550. editor.create_model(LocalAuthorWithM2M)
  551. # Initial tables are there
  552. list(LocalAuthorWithM2M.objects.all())
  553. list(Tag.objects.all())
  554. # Make a db_constraint=False FK
  555. new_field = M2MFieldClass(Tag, related_name="authors", db_constraint=False)
  556. new_field.contribute_to_class(LocalAuthorWithM2M, "tags")
  557. # Add the field
  558. with connection.schema_editor() as editor:
  559. editor.add_field(LocalAuthorWithM2M, new_field)
  560. self.assertForeignKeyNotExists(
  561. new_field.remote_field.through, "tag_id", "schema_tag"
  562. )
  563. @skipUnlessDBFeature("supports_foreign_keys")
  564. def test_m2m_db_constraint(self):
  565. self._test_m2m_db_constraint(ManyToManyField)
  566. @skipUnlessDBFeature("supports_foreign_keys")
  567. def test_m2m_db_constraint_custom(self):
  568. self._test_m2m_db_constraint(CustomManyToManyField)
  569. @skipUnlessDBFeature("supports_foreign_keys")
  570. def test_m2m_db_constraint_inherited(self):
  571. self._test_m2m_db_constraint(InheritedManyToManyField)
  572. def test_add_field(self):
  573. """
  574. Tests adding fields to models
  575. """
  576. # Create the table
  577. with connection.schema_editor() as editor:
  578. editor.create_model(Author)
  579. # Ensure there's no age field
  580. columns = self.column_classes(Author)
  581. self.assertNotIn("age", columns)
  582. # Add the new field
  583. new_field = IntegerField(null=True)
  584. new_field.set_attributes_from_name("age")
  585. with CaptureQueriesContext(
  586. connection
  587. ) as ctx, connection.schema_editor() as editor:
  588. editor.add_field(Author, new_field)
  589. drop_default_sql = editor.sql_alter_column_no_default % {
  590. "column": editor.quote_name(new_field.name),
  591. }
  592. self.assertFalse(
  593. any(drop_default_sql in query["sql"] for query in ctx.captured_queries)
  594. )
  595. # Table is not rebuilt.
  596. self.assertIs(
  597. any("CREATE TABLE" in query["sql"] for query in ctx.captured_queries), False
  598. )
  599. self.assertIs(
  600. any("DROP TABLE" in query["sql"] for query in ctx.captured_queries), False
  601. )
  602. columns = self.column_classes(Author)
  603. self.assertEqual(
  604. columns["age"][0],
  605. connection.features.introspected_field_types["IntegerField"],
  606. )
  607. self.assertTrue(columns["age"][1][6])
  608. def test_add_field_remove_field(self):
  609. """
  610. Adding a field and removing it removes all deferred sql referring to it.
  611. """
  612. with connection.schema_editor() as editor:
  613. # Create a table with a unique constraint on the slug field.
  614. editor.create_model(Tag)
  615. # Remove the slug column.
  616. editor.remove_field(Tag, Tag._meta.get_field("slug"))
  617. self.assertEqual(editor.deferred_sql, [])
  618. def test_add_field_temp_default(self):
  619. """
  620. Tests adding fields to models with a temporary default
  621. """
  622. # Create the table
  623. with connection.schema_editor() as editor:
  624. editor.create_model(Author)
  625. # Ensure there's no age field
  626. columns = self.column_classes(Author)
  627. self.assertNotIn("age", columns)
  628. # Add some rows of data
  629. Author.objects.create(name="Andrew", height=30)
  630. Author.objects.create(name="Andrea")
  631. # Add a not-null field
  632. new_field = CharField(max_length=30, default="Godwin")
  633. new_field.set_attributes_from_name("surname")
  634. with connection.schema_editor() as editor:
  635. editor.add_field(Author, new_field)
  636. columns = self.column_classes(Author)
  637. self.assertEqual(
  638. columns["surname"][0],
  639. connection.features.introspected_field_types["CharField"],
  640. )
  641. self.assertEqual(
  642. columns["surname"][1][6],
  643. connection.features.interprets_empty_strings_as_nulls,
  644. )
  645. def test_add_field_temp_default_boolean(self):
  646. """
  647. Tests adding fields to models with a temporary default where
  648. the default is False. (#21783)
  649. """
  650. # Create the table
  651. with connection.schema_editor() as editor:
  652. editor.create_model(Author)
  653. # Ensure there's no age field
  654. columns = self.column_classes(Author)
  655. self.assertNotIn("age", columns)
  656. # Add some rows of data
  657. Author.objects.create(name="Andrew", height=30)
  658. Author.objects.create(name="Andrea")
  659. # Add a not-null field
  660. new_field = BooleanField(default=False)
  661. new_field.set_attributes_from_name("awesome")
  662. with connection.schema_editor() as editor:
  663. editor.add_field(Author, new_field)
  664. columns = self.column_classes(Author)
  665. # BooleanField are stored as TINYINT(1) on MySQL.
  666. field_type = columns["awesome"][0]
  667. self.assertEqual(
  668. field_type, connection.features.introspected_field_types["BooleanField"]
  669. )
  670. def test_add_field_default_transform(self):
  671. """
  672. Tests adding fields to models with a default that is not directly
  673. valid in the database (#22581)
  674. """
  675. class TestTransformField(IntegerField):
  676. # Weird field that saves the count of items in its value
  677. def get_default(self):
  678. return self.default
  679. def get_prep_value(self, value):
  680. if value is None:
  681. return 0
  682. return len(value)
  683. # Create the table
  684. with connection.schema_editor() as editor:
  685. editor.create_model(Author)
  686. # Add some rows of data
  687. Author.objects.create(name="Andrew", height=30)
  688. Author.objects.create(name="Andrea")
  689. # Add the field with a default it needs to cast (to string in this case)
  690. new_field = TestTransformField(default={1: 2})
  691. new_field.set_attributes_from_name("thing")
  692. with connection.schema_editor() as editor:
  693. editor.add_field(Author, new_field)
  694. # Ensure the field is there
  695. columns = self.column_classes(Author)
  696. field_type, field_info = columns["thing"]
  697. self.assertEqual(
  698. field_type, connection.features.introspected_field_types["IntegerField"]
  699. )
  700. # Make sure the values were transformed correctly
  701. self.assertEqual(Author.objects.extra(where=["thing = 1"]).count(), 2)
  702. def test_add_field_o2o_nullable(self):
  703. with connection.schema_editor() as editor:
  704. editor.create_model(Author)
  705. editor.create_model(Note)
  706. new_field = OneToOneField(Note, CASCADE, null=True)
  707. new_field.set_attributes_from_name("note")
  708. with connection.schema_editor() as editor:
  709. editor.add_field(Author, new_field)
  710. columns = self.column_classes(Author)
  711. self.assertIn("note_id", columns)
  712. self.assertTrue(columns["note_id"][1][6])
  713. def test_add_field_binary(self):
  714. """
  715. Tests binary fields get a sane default (#22851)
  716. """
  717. # Create the table
  718. with connection.schema_editor() as editor:
  719. editor.create_model(Author)
  720. # Add the new field
  721. new_field = BinaryField(blank=True)
  722. new_field.set_attributes_from_name("bits")
  723. with connection.schema_editor() as editor:
  724. editor.add_field(Author, new_field)
  725. columns = self.column_classes(Author)
  726. # MySQL annoyingly uses the same backend, so it'll come back as one of
  727. # these two types.
  728. self.assertIn(columns["bits"][0], ("BinaryField", "TextField"))
  729. def test_add_field_durationfield_with_default(self):
  730. with connection.schema_editor() as editor:
  731. editor.create_model(Author)
  732. new_field = DurationField(default=datetime.timedelta(minutes=10))
  733. new_field.set_attributes_from_name("duration")
  734. with connection.schema_editor() as editor:
  735. editor.add_field(Author, new_field)
  736. columns = self.column_classes(Author)
  737. self.assertEqual(
  738. columns["duration"][0],
  739. connection.features.introspected_field_types["DurationField"],
  740. )
  741. @unittest.skipUnless(connection.vendor == "mysql", "MySQL specific")
  742. def test_add_binaryfield_mediumblob(self):
  743. """
  744. Test adding a custom-sized binary field on MySQL (#24846).
  745. """
  746. # Create the table
  747. with connection.schema_editor() as editor:
  748. editor.create_model(Author)
  749. # Add the new field with default
  750. new_field = MediumBlobField(blank=True, default=b"123")
  751. new_field.set_attributes_from_name("bits")
  752. with connection.schema_editor() as editor:
  753. editor.add_field(Author, new_field)
  754. columns = self.column_classes(Author)
  755. # Introspection treats BLOBs as TextFields
  756. self.assertEqual(columns["bits"][0], "TextField")
  757. @isolate_apps("schema")
  758. @skipUnlessDBFeature("supports_json_field", "supports_stored_generated_columns")
  759. def test_add_generated_field_with_kt_model(self):
  760. class GeneratedFieldKTModel(Model):
  761. data = JSONField()
  762. status = GeneratedField(
  763. expression=KT("data__status"),
  764. output_field=TextField(),
  765. db_persist=True,
  766. )
  767. class Meta:
  768. app_label = "schema"
  769. with CaptureQueriesContext(connection) as ctx:
  770. with connection.schema_editor() as editor:
  771. editor.create_model(GeneratedFieldKTModel)
  772. self.assertIs(
  773. any("None" in query["sql"] for query in ctx.captured_queries),
  774. False,
  775. )
  776. @isolate_apps("schema")
  777. @skipUnlessDBFeature("supports_stored_generated_columns")
  778. def test_add_generated_field(self):
  779. class GeneratedFieldOutputFieldModel(Model):
  780. price = DecimalField(max_digits=7, decimal_places=2)
  781. vat_price = GeneratedField(
  782. expression=Round(F("price") * Value(Decimal("1.22")), 2),
  783. db_persist=True,
  784. output_field=DecimalField(max_digits=8, decimal_places=2),
  785. )
  786. class Meta:
  787. app_label = "schema"
  788. with connection.schema_editor() as editor:
  789. editor.create_model(GeneratedFieldOutputFieldModel)
  790. @isolate_apps("schema")
  791. def test_add_auto_field(self):
  792. class AddAutoFieldModel(Model):
  793. name = CharField(max_length=255, primary_key=True)
  794. class Meta:
  795. app_label = "schema"
  796. with connection.schema_editor() as editor:
  797. editor.create_model(AddAutoFieldModel)
  798. self.isolated_local_models = [AddAutoFieldModel]
  799. old_field = AddAutoFieldModel._meta.get_field("name")
  800. new_field = CharField(max_length=255)
  801. new_field.set_attributes_from_name("name")
  802. new_field.model = AddAutoFieldModel
  803. with connection.schema_editor() as editor:
  804. editor.alter_field(AddAutoFieldModel, old_field, new_field)
  805. new_auto_field = AutoField(primary_key=True)
  806. new_auto_field.set_attributes_from_name("id")
  807. new_auto_field.model = AddAutoFieldModel()
  808. with connection.schema_editor() as editor:
  809. editor.add_field(AddAutoFieldModel, new_auto_field)
  810. # Crashes on PostgreSQL when the GENERATED BY suffix is missing.
  811. AddAutoFieldModel.objects.create(name="test")
  812. def test_remove_field(self):
  813. with connection.schema_editor() as editor:
  814. editor.create_model(Author)
  815. with CaptureQueriesContext(connection) as ctx:
  816. editor.remove_field(Author, Author._meta.get_field("name"))
  817. columns = self.column_classes(Author)
  818. self.assertNotIn("name", columns)
  819. if getattr(connection.features, "can_alter_table_drop_column", True):
  820. # Table is not rebuilt.
  821. self.assertIs(
  822. any("CREATE TABLE" in query["sql"] for query in ctx.captured_queries),
  823. False,
  824. )
  825. self.assertIs(
  826. any("DROP TABLE" in query["sql"] for query in ctx.captured_queries),
  827. False,
  828. )
  829. def test_remove_indexed_field(self):
  830. with connection.schema_editor() as editor:
  831. editor.create_model(AuthorCharFieldWithIndex)
  832. with connection.schema_editor() as editor:
  833. editor.remove_field(
  834. AuthorCharFieldWithIndex,
  835. AuthorCharFieldWithIndex._meta.get_field("char_field"),
  836. )
  837. columns = self.column_classes(AuthorCharFieldWithIndex)
  838. self.assertNotIn("char_field", columns)
  839. def test_alter(self):
  840. """
  841. Tests simple altering of fields
  842. """
  843. # Create the table
  844. with connection.schema_editor() as editor:
  845. editor.create_model(Author)
  846. # Ensure the field is right to begin with
  847. columns = self.column_classes(Author)
  848. self.assertEqual(
  849. columns["name"][0],
  850. connection.features.introspected_field_types["CharField"],
  851. )
  852. self.assertEqual(
  853. bool(columns["name"][1][6]),
  854. bool(connection.features.interprets_empty_strings_as_nulls),
  855. )
  856. # Alter the name field to a TextField
  857. old_field = Author._meta.get_field("name")
  858. new_field = TextField(null=True)
  859. new_field.set_attributes_from_name("name")
  860. with connection.schema_editor() as editor:
  861. editor.alter_field(Author, old_field, new_field, strict=True)
  862. columns = self.column_classes(Author)
  863. self.assertEqual(columns["name"][0], "TextField")
  864. self.assertTrue(columns["name"][1][6])
  865. # Change nullability again
  866. new_field2 = TextField(null=False)
  867. new_field2.set_attributes_from_name("name")
  868. with connection.schema_editor() as editor:
  869. editor.alter_field(Author, new_field, new_field2, strict=True)
  870. columns = self.column_classes(Author)
  871. self.assertEqual(columns["name"][0], "TextField")
  872. self.assertEqual(
  873. bool(columns["name"][1][6]),
  874. bool(connection.features.interprets_empty_strings_as_nulls),
  875. )
  876. def test_alter_auto_field_to_integer_field(self):
  877. # Create the table
  878. with connection.schema_editor() as editor:
  879. editor.create_model(Author)
  880. # Change AutoField to IntegerField
  881. old_field = Author._meta.get_field("id")
  882. new_field = IntegerField(primary_key=True)
  883. new_field.set_attributes_from_name("id")
  884. new_field.model = Author
  885. with connection.schema_editor() as editor:
  886. editor.alter_field(Author, old_field, new_field, strict=True)
  887. # Now that ID is an IntegerField, the database raises an error if it
  888. # isn't provided.
  889. if not connection.features.supports_unspecified_pk:
  890. with self.assertRaises(DatabaseError):
  891. Author.objects.create()
  892. def test_alter_auto_field_to_char_field(self):
  893. # Create the table
  894. with connection.schema_editor() as editor:
  895. editor.create_model(Author)
  896. # Change AutoField to CharField
  897. old_field = Author._meta.get_field("id")
  898. new_field = CharField(primary_key=True, max_length=50)
  899. new_field.set_attributes_from_name("id")
  900. new_field.model = Author
  901. with connection.schema_editor() as editor:
  902. editor.alter_field(Author, old_field, new_field, strict=True)
  903. @isolate_apps("schema")
  904. def test_alter_auto_field_quoted_db_column(self):
  905. class Foo(Model):
  906. id = AutoField(primary_key=True, db_column='"quoted_id"')
  907. class Meta:
  908. app_label = "schema"
  909. with connection.schema_editor() as editor:
  910. editor.create_model(Foo)
  911. self.isolated_local_models = [Foo]
  912. old_field = Foo._meta.get_field("id")
  913. new_field = BigAutoField(primary_key=True)
  914. new_field.model = Foo
  915. new_field.db_column = '"quoted_id"'
  916. new_field.set_attributes_from_name("id")
  917. with connection.schema_editor() as editor:
  918. editor.alter_field(Foo, old_field, new_field, strict=True)
  919. Foo.objects.create()
  920. def test_alter_not_unique_field_to_primary_key(self):
  921. # Create the table.
  922. with connection.schema_editor() as editor:
  923. editor.create_model(Author)
  924. # Change UUIDField to primary key.
  925. old_field = Author._meta.get_field("uuid")
  926. new_field = UUIDField(primary_key=True)
  927. new_field.set_attributes_from_name("uuid")
  928. new_field.model = Author
  929. with connection.schema_editor() as editor:
  930. editor.remove_field(Author, Author._meta.get_field("id"))
  931. editor.alter_field(Author, old_field, new_field, strict=True)
  932. # Redundant unique constraint is not added.
  933. count = self.get_constraints_count(
  934. Author._meta.db_table,
  935. Author._meta.get_field("uuid").column,
  936. None,
  937. )
  938. self.assertLessEqual(count["uniques"], 1)
  939. @isolate_apps("schema")
  940. def test_alter_primary_key_quoted_db_table(self):
  941. class Foo(Model):
  942. class Meta:
  943. app_label = "schema"
  944. db_table = '"foo"'
  945. with connection.schema_editor() as editor:
  946. editor.create_model(Foo)
  947. self.isolated_local_models = [Foo]
  948. old_field = Foo._meta.get_field("id")
  949. new_field = BigAutoField(primary_key=True)
  950. new_field.model = Foo
  951. new_field.set_attributes_from_name("id")
  952. with connection.schema_editor() as editor:
  953. editor.alter_field(Foo, old_field, new_field, strict=True)
  954. Foo.objects.create()
  955. def test_alter_text_field(self):
  956. # Regression for "BLOB/TEXT column 'info' can't have a default value")
  957. # on MySQL.
  958. # Create the table
  959. with connection.schema_editor() as editor:
  960. editor.create_model(Note)
  961. old_field = Note._meta.get_field("info")
  962. new_field = TextField(blank=True)
  963. new_field.set_attributes_from_name("info")
  964. with connection.schema_editor() as editor:
  965. editor.alter_field(Note, old_field, new_field, strict=True)
  966. def test_alter_text_field_to_not_null_with_default_value(self):
  967. with connection.schema_editor() as editor:
  968. editor.create_model(Note)
  969. old_field = Note._meta.get_field("address")
  970. new_field = TextField(blank=True, default="", null=False)
  971. new_field.set_attributes_from_name("address")
  972. with connection.schema_editor() as editor:
  973. editor.alter_field(Note, old_field, new_field, strict=True)
  974. @skipUnlessDBFeature("can_defer_constraint_checks", "can_rollback_ddl")
  975. def test_alter_fk_checks_deferred_constraints(self):
  976. """
  977. #25492 - Altering a foreign key's structure and data in the same
  978. transaction.
  979. """
  980. with connection.schema_editor() as editor:
  981. editor.create_model(Node)
  982. old_field = Node._meta.get_field("parent")
  983. new_field = ForeignKey(Node, CASCADE)
  984. new_field.set_attributes_from_name("parent")
  985. parent = Node.objects.create()
  986. with connection.schema_editor() as editor:
  987. # Update the parent FK to create a deferred constraint check.
  988. Node.objects.update(parent=parent)
  989. editor.alter_field(Node, old_field, new_field, strict=True)
  990. @isolate_apps("schema")
  991. def test_alter_null_with_default_value_deferred_constraints(self):
  992. class Publisher(Model):
  993. class Meta:
  994. app_label = "schema"
  995. class Article(Model):
  996. publisher = ForeignKey(Publisher, CASCADE)
  997. title = CharField(max_length=50, null=True)
  998. description = CharField(max_length=100, null=True)
  999. class Meta:
  1000. app_label = "schema"
  1001. with connection.schema_editor() as editor:
  1002. editor.create_model(Publisher)
  1003. editor.create_model(Article)
  1004. self.isolated_local_models = [Article, Publisher]
  1005. publisher = Publisher.objects.create()
  1006. Article.objects.create(publisher=publisher)
  1007. old_title = Article._meta.get_field("title")
  1008. new_title = CharField(max_length=50, null=False, default="")
  1009. new_title.set_attributes_from_name("title")
  1010. old_description = Article._meta.get_field("description")
  1011. new_description = CharField(max_length=100, null=False, default="")
  1012. new_description.set_attributes_from_name("description")
  1013. with connection.schema_editor() as editor:
  1014. editor.alter_field(Article, old_title, new_title, strict=True)
  1015. editor.alter_field(Article, old_description, new_description, strict=True)
  1016. def test_alter_text_field_to_date_field(self):
  1017. """
  1018. #25002 - Test conversion of text field to date field.
  1019. """
  1020. with connection.schema_editor() as editor:
  1021. editor.create_model(Note)
  1022. Note.objects.create(info="1988-05-05")
  1023. old_field = Note._meta.get_field("info")
  1024. new_field = DateField(blank=True)
  1025. new_field.set_attributes_from_name("info")
  1026. with connection.schema_editor() as editor:
  1027. editor.alter_field(Note, old_field, new_field, strict=True)
  1028. # Make sure the field isn't nullable
  1029. columns = self.column_classes(Note)
  1030. self.assertFalse(columns["info"][1][6])
  1031. def test_alter_text_field_to_datetime_field(self):
  1032. """
  1033. #25002 - Test conversion of text field to datetime field.
  1034. """
  1035. with connection.schema_editor() as editor:
  1036. editor.create_model(Note)
  1037. Note.objects.create(info="1988-05-05 3:16:17.4567")
  1038. old_field = Note._meta.get_field("info")
  1039. new_field = DateTimeField(blank=True)
  1040. new_field.set_attributes_from_name("info")
  1041. with connection.schema_editor() as editor:
  1042. editor.alter_field(Note, old_field, new_field, strict=True)
  1043. # Make sure the field isn't nullable
  1044. columns = self.column_classes(Note)
  1045. self.assertFalse(columns["info"][1][6])
  1046. def test_alter_text_field_to_time_field(self):
  1047. """
  1048. #25002 - Test conversion of text field to time field.
  1049. """
  1050. with connection.schema_editor() as editor:
  1051. editor.create_model(Note)
  1052. Note.objects.create(info="3:16:17.4567")
  1053. old_field = Note._meta.get_field("info")
  1054. new_field = TimeField(blank=True)
  1055. new_field.set_attributes_from_name("info")
  1056. with connection.schema_editor() as editor:
  1057. editor.alter_field(Note, old_field, new_field, strict=True)
  1058. # Make sure the field isn't nullable
  1059. columns = self.column_classes(Note)
  1060. self.assertFalse(columns["info"][1][6])
  1061. @skipIfDBFeature("interprets_empty_strings_as_nulls")
  1062. def test_alter_textual_field_keep_null_status(self):
  1063. """
  1064. Changing a field type shouldn't affect the not null status.
  1065. """
  1066. with connection.schema_editor() as editor:
  1067. editor.create_model(Note)
  1068. with self.assertRaises(IntegrityError):
  1069. Note.objects.create(info=None)
  1070. old_field = Note._meta.get_field("info")
  1071. new_field = CharField(max_length=50)
  1072. new_field.set_attributes_from_name("info")
  1073. with connection.schema_editor() as editor:
  1074. editor.alter_field(Note, old_field, new_field, strict=True)
  1075. with self.assertRaises(IntegrityError):
  1076. Note.objects.create(info=None)
  1077. @skipUnlessDBFeature("interprets_empty_strings_as_nulls")
  1078. def test_alter_textual_field_not_null_to_null(self):
  1079. """
  1080. Nullability for textual fields is preserved on databases that
  1081. interpret empty strings as NULLs.
  1082. """
  1083. with connection.schema_editor() as editor:
  1084. editor.create_model(Author)
  1085. columns = self.column_classes(Author)
  1086. # Field is nullable.
  1087. self.assertTrue(columns["uuid"][1][6])
  1088. # Change to NOT NULL.
  1089. old_field = Author._meta.get_field("uuid")
  1090. new_field = SlugField(null=False, blank=True)
  1091. new_field.set_attributes_from_name("uuid")
  1092. with connection.schema_editor() as editor:
  1093. editor.alter_field(Author, old_field, new_field, strict=True)
  1094. columns = self.column_classes(Author)
  1095. # Nullability is preserved.
  1096. self.assertTrue(columns["uuid"][1][6])
  1097. def test_alter_numeric_field_keep_null_status(self):
  1098. """
  1099. Changing a field type shouldn't affect the not null status.
  1100. """
  1101. with connection.schema_editor() as editor:
  1102. editor.create_model(UniqueTest)
  1103. with self.assertRaises(IntegrityError):
  1104. UniqueTest.objects.create(year=None, slug="aaa")
  1105. old_field = UniqueTest._meta.get_field("year")
  1106. new_field = BigIntegerField()
  1107. new_field.set_attributes_from_name("year")
  1108. with connection.schema_editor() as editor:
  1109. editor.alter_field(UniqueTest, old_field, new_field, strict=True)
  1110. with self.assertRaises(IntegrityError):
  1111. UniqueTest.objects.create(year=None, slug="bbb")
  1112. def test_alter_null_to_not_null(self):
  1113. """
  1114. #23609 - Tests handling of default values when altering from NULL to NOT NULL.
  1115. """
  1116. # Create the table
  1117. with connection.schema_editor() as editor:
  1118. editor.create_model(Author)
  1119. # Ensure the field is right to begin with
  1120. columns = self.column_classes(Author)
  1121. self.assertTrue(columns["height"][1][6])
  1122. # Create some test data
  1123. Author.objects.create(name="Not null author", height=12)
  1124. Author.objects.create(name="Null author")
  1125. # Verify null value
  1126. self.assertEqual(Author.objects.get(name="Not null author").height, 12)
  1127. self.assertIsNone(Author.objects.get(name="Null author").height)
  1128. # Alter the height field to NOT NULL with default
  1129. old_field = Author._meta.get_field("height")
  1130. new_field = PositiveIntegerField(default=42)
  1131. new_field.set_attributes_from_name("height")
  1132. with connection.schema_editor() as editor:
  1133. editor.alter_field(Author, old_field, new_field, strict=True)
  1134. columns = self.column_classes(Author)
  1135. self.assertFalse(columns["height"][1][6])
  1136. # Verify default value
  1137. self.assertEqual(Author.objects.get(name="Not null author").height, 12)
  1138. self.assertEqual(Author.objects.get(name="Null author").height, 42)
  1139. def test_alter_charfield_to_null(self):
  1140. """
  1141. #24307 - Should skip an alter statement on databases with
  1142. interprets_empty_strings_as_nulls when changing a CharField to null.
  1143. """
  1144. # Create the table
  1145. with connection.schema_editor() as editor:
  1146. editor.create_model(Author)
  1147. # Change the CharField to null
  1148. old_field = Author._meta.get_field("name")
  1149. new_field = copy(old_field)
  1150. new_field.null = True
  1151. with connection.schema_editor() as editor:
  1152. editor.alter_field(Author, old_field, new_field, strict=True)
  1153. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  1154. def test_alter_char_field_decrease_length(self):
  1155. # Create the table.
  1156. with connection.schema_editor() as editor:
  1157. editor.create_model(Author)
  1158. Author.objects.create(name="x" * 255)
  1159. # Change max_length of CharField.
  1160. old_field = Author._meta.get_field("name")
  1161. new_field = CharField(max_length=254)
  1162. new_field.set_attributes_from_name("name")
  1163. with connection.schema_editor() as editor:
  1164. msg = "value too long for type character varying(254)"
  1165. with self.assertRaisesMessage(DataError, msg):
  1166. editor.alter_field(Author, old_field, new_field, strict=True)
  1167. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  1168. def test_alter_field_with_custom_db_type(self):
  1169. from django.contrib.postgres.fields import ArrayField
  1170. class Foo(Model):
  1171. field = ArrayField(CharField(max_length=255))
  1172. class Meta:
  1173. app_label = "schema"
  1174. with connection.schema_editor() as editor:
  1175. editor.create_model(Foo)
  1176. self.isolated_local_models = [Foo]
  1177. old_field = Foo._meta.get_field("field")
  1178. new_field = ArrayField(CharField(max_length=16))
  1179. new_field.set_attributes_from_name("field")
  1180. new_field.model = Foo
  1181. with connection.schema_editor() as editor:
  1182. editor.alter_field(Foo, old_field, new_field, strict=True)
  1183. @isolate_apps("schema")
  1184. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  1185. def test_alter_array_field_decrease_base_field_length(self):
  1186. from django.contrib.postgres.fields import ArrayField
  1187. class ArrayModel(Model):
  1188. field = ArrayField(CharField(max_length=16))
  1189. class Meta:
  1190. app_label = "schema"
  1191. with connection.schema_editor() as editor:
  1192. editor.create_model(ArrayModel)
  1193. self.isolated_local_models = [ArrayModel]
  1194. ArrayModel.objects.create(field=["x" * 16])
  1195. old_field = ArrayModel._meta.get_field("field")
  1196. new_field = ArrayField(CharField(max_length=15))
  1197. new_field.set_attributes_from_name("field")
  1198. new_field.model = ArrayModel
  1199. with connection.schema_editor() as editor:
  1200. msg = "value too long for type character varying(15)"
  1201. with self.assertRaisesMessage(DataError, msg):
  1202. editor.alter_field(ArrayModel, old_field, new_field, strict=True)
  1203. @isolate_apps("schema")
  1204. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  1205. def test_alter_array_field_decrease_nested_base_field_length(self):
  1206. from django.contrib.postgres.fields import ArrayField
  1207. class ArrayModel(Model):
  1208. field = ArrayField(ArrayField(CharField(max_length=16)))
  1209. class Meta:
  1210. app_label = "schema"
  1211. with connection.schema_editor() as editor:
  1212. editor.create_model(ArrayModel)
  1213. self.isolated_local_models = [ArrayModel]
  1214. ArrayModel.objects.create(field=[["x" * 16]])
  1215. old_field = ArrayModel._meta.get_field("field")
  1216. new_field = ArrayField(ArrayField(CharField(max_length=15)))
  1217. new_field.set_attributes_from_name("field")
  1218. new_field.model = ArrayModel
  1219. with connection.schema_editor() as editor:
  1220. msg = "value too long for type character varying(15)"
  1221. with self.assertRaisesMessage(DataError, msg):
  1222. editor.alter_field(ArrayModel, old_field, new_field, strict=True)
  1223. def _add_ci_collation(self):
  1224. ci_collation = "case_insensitive"
  1225. def drop_collation():
  1226. with connection.cursor() as cursor:
  1227. cursor.execute(f"DROP COLLATION IF EXISTS {ci_collation}")
  1228. with connection.cursor() as cursor:
  1229. cursor.execute(
  1230. f"CREATE COLLATION IF NOT EXISTS {ci_collation} (provider=icu, "
  1231. f"locale='und-u-ks-level2', deterministic=false)"
  1232. )
  1233. self.addCleanup(drop_collation)
  1234. return ci_collation
  1235. @isolate_apps("schema")
  1236. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  1237. @skipUnlessDBFeature(
  1238. "supports_collation_on_charfield",
  1239. "supports_non_deterministic_collations",
  1240. )
  1241. def test_db_collation_arrayfield(self):
  1242. from django.contrib.postgres.fields import ArrayField
  1243. ci_collation = self._add_ci_collation()
  1244. cs_collation = "en-x-icu"
  1245. class ArrayModel(Model):
  1246. field = ArrayField(CharField(max_length=16, db_collation=ci_collation))
  1247. class Meta:
  1248. app_label = "schema"
  1249. # Create the table.
  1250. with connection.schema_editor() as editor:
  1251. editor.create_model(ArrayModel)
  1252. self.isolated_local_models = [ArrayModel]
  1253. self.assertEqual(
  1254. self.get_column_collation(ArrayModel._meta.db_table, "field"),
  1255. ci_collation,
  1256. )
  1257. # Alter collation.
  1258. old_field = ArrayModel._meta.get_field("field")
  1259. new_field_cs = ArrayField(CharField(max_length=16, db_collation=cs_collation))
  1260. new_field_cs.set_attributes_from_name("field")
  1261. new_field_cs.model = ArrayField
  1262. with connection.schema_editor() as editor:
  1263. editor.alter_field(ArrayModel, old_field, new_field_cs, strict=True)
  1264. self.assertEqual(
  1265. self.get_column_collation(ArrayModel._meta.db_table, "field"),
  1266. cs_collation,
  1267. )
  1268. @isolate_apps("schema")
  1269. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  1270. @skipUnlessDBFeature(
  1271. "supports_collation_on_charfield",
  1272. "supports_non_deterministic_collations",
  1273. )
  1274. def test_unique_with_collation_charfield(self):
  1275. ci_collation = self._add_ci_collation()
  1276. class CiCharModel(Model):
  1277. field = CharField(max_length=16, db_collation=ci_collation, unique=True)
  1278. class Meta:
  1279. app_label = "schema"
  1280. # Create the table.
  1281. with connection.schema_editor() as editor:
  1282. editor.create_model(CiCharModel)
  1283. self.isolated_local_models = [CiCharModel]
  1284. self.assertEqual(
  1285. self.get_column_collation(CiCharModel._meta.db_table, "field"),
  1286. ci_collation,
  1287. )
  1288. self.assertIn("field", self.get_uniques(CiCharModel._meta.db_table))
  1289. @isolate_apps("schema")
  1290. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  1291. @skipUnlessDBFeature("supports_collation_on_charfield")
  1292. def test_unique_with_deterministic_collation_charfield(self):
  1293. deterministic_collation = connection.features.test_collations.get(
  1294. "deterministic"
  1295. )
  1296. if not deterministic_collation:
  1297. self.skipTest("This backend does not support deterministic collations.")
  1298. class CharModel(Model):
  1299. field = CharField(db_collation=deterministic_collation, unique=True)
  1300. class Meta:
  1301. app_label = "schema"
  1302. # Create the table.
  1303. with connection.schema_editor() as editor:
  1304. editor.create_model(CharModel)
  1305. self.isolated_local_models = [CharModel]
  1306. constraints = self.get_constraints_for_column(
  1307. CharModel, CharModel._meta.get_field("field").column
  1308. )
  1309. self.assertIn("schema_charmodel_field_8b338dea_like", constraints)
  1310. self.assertIn(
  1311. "varchar_pattern_ops",
  1312. self.get_constraint_opclasses("schema_charmodel_field_8b338dea_like"),
  1313. )
  1314. self.assertEqual(
  1315. self.get_column_collation(CharModel._meta.db_table, "field"),
  1316. deterministic_collation,
  1317. )
  1318. self.assertIn("field", self.get_uniques(CharModel._meta.db_table))
  1319. @isolate_apps("schema")
  1320. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  1321. @skipUnlessDBFeature(
  1322. "supports_collation_on_charfield",
  1323. "supports_non_deterministic_collations",
  1324. )
  1325. def test_relation_to_collation_charfield(self):
  1326. ci_collation = self._add_ci_collation()
  1327. class CiCharModel(Model):
  1328. field = CharField(max_length=16, db_collation=ci_collation, unique=True)
  1329. class Meta:
  1330. app_label = "schema"
  1331. class RelationModel(Model):
  1332. field = OneToOneField(CiCharModel, CASCADE, to_field="field")
  1333. class Meta:
  1334. app_label = "schema"
  1335. # Create the table.
  1336. with connection.schema_editor() as editor:
  1337. editor.create_model(CiCharModel)
  1338. editor.create_model(RelationModel)
  1339. self.isolated_local_models = [CiCharModel, RelationModel]
  1340. self.assertEqual(
  1341. self.get_column_collation(RelationModel._meta.db_table, "field_id"),
  1342. ci_collation,
  1343. )
  1344. self.assertEqual(
  1345. self.get_column_collation(CiCharModel._meta.db_table, "field"),
  1346. ci_collation,
  1347. )
  1348. self.assertIn("field_id", self.get_uniques(RelationModel._meta.db_table))
  1349. @isolate_apps("schema")
  1350. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  1351. @skipUnlessDBFeature("supports_collation_on_charfield")
  1352. def test_relation_to_deterministic_collation_charfield(self):
  1353. deterministic_collation = connection.features.test_collations.get(
  1354. "deterministic"
  1355. )
  1356. if not deterministic_collation:
  1357. self.skipTest("This backend does not support deterministic collations.")
  1358. class CharModel(Model):
  1359. field = CharField(db_collation=deterministic_collation, unique=True)
  1360. class Meta:
  1361. app_label = "schema"
  1362. class RelationModel(Model):
  1363. field = OneToOneField(CharModel, CASCADE, to_field="field")
  1364. class Meta:
  1365. app_label = "schema"
  1366. # Create the table.
  1367. with connection.schema_editor() as editor:
  1368. editor.create_model(CharModel)
  1369. editor.create_model(RelationModel)
  1370. self.isolated_local_models = [CharModel, RelationModel]
  1371. constraints = self.get_constraints_for_column(
  1372. CharModel, CharModel._meta.get_field("field").column
  1373. )
  1374. self.assertIn("schema_charmodel_field_8b338dea_like", constraints)
  1375. self.assertIn(
  1376. "varchar_pattern_ops",
  1377. self.get_constraint_opclasses("schema_charmodel_field_8b338dea_like"),
  1378. )
  1379. rel_constraints = self.get_constraints_for_column(
  1380. RelationModel, RelationModel._meta.get_field("field").column
  1381. )
  1382. self.assertIn("schema_relationmodel_field_id_395fbb08_like", rel_constraints)
  1383. self.assertIn(
  1384. "varchar_pattern_ops",
  1385. self.get_constraint_opclasses(
  1386. "schema_relationmodel_field_id_395fbb08_like"
  1387. ),
  1388. )
  1389. self.assertEqual(
  1390. self.get_column_collation(RelationModel._meta.db_table, "field_id"),
  1391. deterministic_collation,
  1392. )
  1393. self.assertEqual(
  1394. self.get_column_collation(CharModel._meta.db_table, "field"),
  1395. deterministic_collation,
  1396. )
  1397. self.assertIn("field_id", self.get_uniques(RelationModel._meta.db_table))
  1398. def test_alter_textfield_to_null(self):
  1399. """
  1400. #24307 - Should skip an alter statement on databases with
  1401. interprets_empty_strings_as_nulls when changing a TextField to null.
  1402. """
  1403. # Create the table
  1404. with connection.schema_editor() as editor:
  1405. editor.create_model(Note)
  1406. # Change the TextField to null
  1407. old_field = Note._meta.get_field("info")
  1408. new_field = copy(old_field)
  1409. new_field.null = True
  1410. with connection.schema_editor() as editor:
  1411. editor.alter_field(Note, old_field, new_field, strict=True)
  1412. def test_alter_null_to_not_null_keeping_default(self):
  1413. """
  1414. #23738 - Can change a nullable field with default to non-nullable
  1415. with the same default.
  1416. """
  1417. # Create the table
  1418. with connection.schema_editor() as editor:
  1419. editor.create_model(AuthorWithDefaultHeight)
  1420. # Ensure the field is right to begin with
  1421. columns = self.column_classes(AuthorWithDefaultHeight)
  1422. self.assertTrue(columns["height"][1][6])
  1423. # Alter the height field to NOT NULL keeping the previous default
  1424. old_field = AuthorWithDefaultHeight._meta.get_field("height")
  1425. new_field = PositiveIntegerField(default=42)
  1426. new_field.set_attributes_from_name("height")
  1427. with connection.schema_editor() as editor:
  1428. editor.alter_field(
  1429. AuthorWithDefaultHeight, old_field, new_field, strict=True
  1430. )
  1431. columns = self.column_classes(AuthorWithDefaultHeight)
  1432. self.assertFalse(columns["height"][1][6])
  1433. @skipUnlessDBFeature("supports_foreign_keys")
  1434. def test_alter_fk(self):
  1435. """
  1436. Tests altering of FKs
  1437. """
  1438. # Create the table
  1439. with connection.schema_editor() as editor:
  1440. editor.create_model(Author)
  1441. editor.create_model(Book)
  1442. # Ensure the field is right to begin with
  1443. columns = self.column_classes(Book)
  1444. self.assertEqual(
  1445. columns["author_id"][0],
  1446. connection.features.introspected_field_types["IntegerField"],
  1447. )
  1448. self.assertForeignKeyExists(Book, "author_id", "schema_author")
  1449. # Alter the FK
  1450. old_field = Book._meta.get_field("author")
  1451. new_field = ForeignKey(Author, CASCADE, editable=False)
  1452. new_field.set_attributes_from_name("author")
  1453. with connection.schema_editor() as editor:
  1454. editor.alter_field(Book, old_field, new_field, strict=True)
  1455. columns = self.column_classes(Book)
  1456. self.assertEqual(
  1457. columns["author_id"][0],
  1458. connection.features.introspected_field_types["IntegerField"],
  1459. )
  1460. self.assertForeignKeyExists(Book, "author_id", "schema_author")
  1461. @skipUnlessDBFeature("supports_foreign_keys")
  1462. def test_alter_to_fk(self):
  1463. """
  1464. #24447 - Tests adding a FK constraint for an existing column
  1465. """
  1466. class LocalBook(Model):
  1467. author = IntegerField()
  1468. title = CharField(max_length=100, db_index=True)
  1469. pub_date = DateTimeField()
  1470. class Meta:
  1471. app_label = "schema"
  1472. apps = new_apps
  1473. self.local_models = [LocalBook]
  1474. # Create the tables
  1475. with connection.schema_editor() as editor:
  1476. editor.create_model(Author)
  1477. editor.create_model(LocalBook)
  1478. # Ensure no FK constraint exists
  1479. constraints = self.get_constraints(LocalBook._meta.db_table)
  1480. for details in constraints.values():
  1481. if details["foreign_key"]:
  1482. self.fail(
  1483. "Found an unexpected FK constraint to %s" % details["columns"]
  1484. )
  1485. old_field = LocalBook._meta.get_field("author")
  1486. new_field = ForeignKey(Author, CASCADE)
  1487. new_field.set_attributes_from_name("author")
  1488. with connection.schema_editor() as editor:
  1489. editor.alter_field(LocalBook, old_field, new_field, strict=True)
  1490. self.assertForeignKeyExists(LocalBook, "author_id", "schema_author")
  1491. @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys")
  1492. def test_alter_o2o_to_fk(self):
  1493. """
  1494. #24163 - Tests altering of OneToOneField to ForeignKey
  1495. """
  1496. # Create the table
  1497. with connection.schema_editor() as editor:
  1498. editor.create_model(Author)
  1499. editor.create_model(BookWithO2O)
  1500. # Ensure the field is right to begin with
  1501. columns = self.column_classes(BookWithO2O)
  1502. self.assertEqual(
  1503. columns["author_id"][0],
  1504. connection.features.introspected_field_types["IntegerField"],
  1505. )
  1506. # Ensure the field is unique
  1507. author = Author.objects.create(name="Joe")
  1508. BookWithO2O.objects.create(
  1509. author=author, title="Django 1", pub_date=datetime.datetime.now()
  1510. )
  1511. with self.assertRaises(IntegrityError):
  1512. BookWithO2O.objects.create(
  1513. author=author, title="Django 2", pub_date=datetime.datetime.now()
  1514. )
  1515. BookWithO2O.objects.all().delete()
  1516. self.assertForeignKeyExists(BookWithO2O, "author_id", "schema_author")
  1517. # Alter the OneToOneField to ForeignKey
  1518. old_field = BookWithO2O._meta.get_field("author")
  1519. new_field = ForeignKey(Author, CASCADE)
  1520. new_field.set_attributes_from_name("author")
  1521. with connection.schema_editor() as editor:
  1522. editor.alter_field(BookWithO2O, old_field, new_field, strict=True)
  1523. columns = self.column_classes(Book)
  1524. self.assertEqual(
  1525. columns["author_id"][0],
  1526. connection.features.introspected_field_types["IntegerField"],
  1527. )
  1528. # Ensure the field is not unique anymore
  1529. Book.objects.create(
  1530. author=author, title="Django 1", pub_date=datetime.datetime.now()
  1531. )
  1532. Book.objects.create(
  1533. author=author, title="Django 2", pub_date=datetime.datetime.now()
  1534. )
  1535. self.assertForeignKeyExists(Book, "author_id", "schema_author")
  1536. @skipUnlessDBFeature("supports_foreign_keys", "can_introspect_foreign_keys")
  1537. def test_alter_fk_to_o2o(self):
  1538. """
  1539. #24163 - Tests altering of ForeignKey to OneToOneField
  1540. """
  1541. # Create the table
  1542. with connection.schema_editor() as editor:
  1543. editor.create_model(Author)
  1544. editor.create_model(Book)
  1545. # Ensure the field is right to begin with
  1546. columns = self.column_classes(Book)
  1547. self.assertEqual(
  1548. columns["author_id"][0],
  1549. connection.features.introspected_field_types["IntegerField"],
  1550. )
  1551. # Ensure the field is not unique
  1552. author = Author.objects.create(name="Joe")
  1553. Book.objects.create(
  1554. author=author, title="Django 1", pub_date=datetime.datetime.now()
  1555. )
  1556. Book.objects.create(
  1557. author=author, title="Django 2", pub_date=datetime.datetime.now()
  1558. )
  1559. Book.objects.all().delete()
  1560. self.assertForeignKeyExists(Book, "author_id", "schema_author")
  1561. # Alter the ForeignKey to OneToOneField
  1562. old_field = Book._meta.get_field("author")
  1563. new_field = OneToOneField(Author, CASCADE)
  1564. new_field.set_attributes_from_name("author")
  1565. with connection.schema_editor() as editor:
  1566. editor.alter_field(Book, old_field, new_field, strict=True)
  1567. columns = self.column_classes(BookWithO2O)
  1568. self.assertEqual(
  1569. columns["author_id"][0],
  1570. connection.features.introspected_field_types["IntegerField"],
  1571. )
  1572. # Ensure the field is unique now
  1573. BookWithO2O.objects.create(
  1574. author=author, title="Django 1", pub_date=datetime.datetime.now()
  1575. )
  1576. with self.assertRaises(IntegrityError):
  1577. BookWithO2O.objects.create(
  1578. author=author, title="Django 2", pub_date=datetime.datetime.now()
  1579. )
  1580. self.assertForeignKeyExists(BookWithO2O, "author_id", "schema_author")
  1581. def test_alter_field_fk_to_o2o(self):
  1582. with connection.schema_editor() as editor:
  1583. editor.create_model(Author)
  1584. editor.create_model(Book)
  1585. expected_fks = (
  1586. 1
  1587. if connection.features.supports_foreign_keys
  1588. and connection.features.can_introspect_foreign_keys
  1589. else 0
  1590. )
  1591. expected_indexes = 1 if connection.features.indexes_foreign_keys else 0
  1592. # Check the index is right to begin with.
  1593. counts = self.get_constraints_count(
  1594. Book._meta.db_table,
  1595. Book._meta.get_field("author").column,
  1596. (Author._meta.db_table, Author._meta.pk.column),
  1597. )
  1598. self.assertEqual(
  1599. counts,
  1600. {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes},
  1601. )
  1602. old_field = Book._meta.get_field("author")
  1603. new_field = OneToOneField(Author, CASCADE)
  1604. new_field.set_attributes_from_name("author")
  1605. with connection.schema_editor() as editor:
  1606. editor.alter_field(Book, old_field, new_field)
  1607. counts = self.get_constraints_count(
  1608. Book._meta.db_table,
  1609. Book._meta.get_field("author").column,
  1610. (Author._meta.db_table, Author._meta.pk.column),
  1611. )
  1612. # The index on ForeignKey is replaced with a unique constraint for
  1613. # OneToOneField.
  1614. self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0})
  1615. def test_autofield_to_o2o(self):
  1616. with connection.schema_editor() as editor:
  1617. editor.create_model(Author)
  1618. editor.create_model(Note)
  1619. # Rename the field.
  1620. old_field = Author._meta.get_field("id")
  1621. new_field = AutoField(primary_key=True)
  1622. new_field.set_attributes_from_name("note_ptr")
  1623. new_field.model = Author
  1624. with connection.schema_editor() as editor:
  1625. editor.alter_field(Author, old_field, new_field, strict=True)
  1626. # Alter AutoField to OneToOneField.
  1627. new_field_o2o = OneToOneField(Note, CASCADE)
  1628. new_field_o2o.set_attributes_from_name("note_ptr")
  1629. new_field_o2o.model = Author
  1630. with connection.schema_editor() as editor:
  1631. editor.alter_field(Author, new_field, new_field_o2o, strict=True)
  1632. columns = self.column_classes(Author)
  1633. field_type, _ = columns["note_ptr_id"]
  1634. self.assertEqual(
  1635. field_type, connection.features.introspected_field_types["IntegerField"]
  1636. )
  1637. def test_alter_field_fk_keeps_index(self):
  1638. with connection.schema_editor() as editor:
  1639. editor.create_model(Author)
  1640. editor.create_model(Book)
  1641. expected_fks = (
  1642. 1
  1643. if connection.features.supports_foreign_keys
  1644. and connection.features.can_introspect_foreign_keys
  1645. else 0
  1646. )
  1647. expected_indexes = 1 if connection.features.indexes_foreign_keys else 0
  1648. # Check the index is right to begin with.
  1649. counts = self.get_constraints_count(
  1650. Book._meta.db_table,
  1651. Book._meta.get_field("author").column,
  1652. (Author._meta.db_table, Author._meta.pk.column),
  1653. )
  1654. self.assertEqual(
  1655. counts,
  1656. {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes},
  1657. )
  1658. old_field = Book._meta.get_field("author")
  1659. # on_delete changed from CASCADE.
  1660. new_field = ForeignKey(Author, PROTECT)
  1661. new_field.set_attributes_from_name("author")
  1662. with connection.schema_editor() as editor:
  1663. editor.alter_field(Book, old_field, new_field, strict=True)
  1664. counts = self.get_constraints_count(
  1665. Book._meta.db_table,
  1666. Book._meta.get_field("author").column,
  1667. (Author._meta.db_table, Author._meta.pk.column),
  1668. )
  1669. # The index remains.
  1670. self.assertEqual(
  1671. counts,
  1672. {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes},
  1673. )
  1674. def test_alter_field_o2o_to_fk(self):
  1675. with connection.schema_editor() as editor:
  1676. editor.create_model(Author)
  1677. editor.create_model(BookWithO2O)
  1678. expected_fks = (
  1679. 1
  1680. if connection.features.supports_foreign_keys
  1681. and connection.features.can_introspect_foreign_keys
  1682. else 0
  1683. )
  1684. # Check the unique constraint is right to begin with.
  1685. counts = self.get_constraints_count(
  1686. BookWithO2O._meta.db_table,
  1687. BookWithO2O._meta.get_field("author").column,
  1688. (Author._meta.db_table, Author._meta.pk.column),
  1689. )
  1690. self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0})
  1691. old_field = BookWithO2O._meta.get_field("author")
  1692. new_field = ForeignKey(Author, CASCADE)
  1693. new_field.set_attributes_from_name("author")
  1694. with connection.schema_editor() as editor:
  1695. editor.alter_field(BookWithO2O, old_field, new_field)
  1696. counts = self.get_constraints_count(
  1697. BookWithO2O._meta.db_table,
  1698. BookWithO2O._meta.get_field("author").column,
  1699. (Author._meta.db_table, Author._meta.pk.column),
  1700. )
  1701. # The unique constraint on OneToOneField is replaced with an index for
  1702. # ForeignKey.
  1703. self.assertEqual(counts, {"fks": expected_fks, "uniques": 0, "indexes": 1})
  1704. def test_alter_field_o2o_keeps_unique(self):
  1705. with connection.schema_editor() as editor:
  1706. editor.create_model(Author)
  1707. editor.create_model(BookWithO2O)
  1708. expected_fks = (
  1709. 1
  1710. if connection.features.supports_foreign_keys
  1711. and connection.features.can_introspect_foreign_keys
  1712. else 0
  1713. )
  1714. # Check the unique constraint is right to begin with.
  1715. counts = self.get_constraints_count(
  1716. BookWithO2O._meta.db_table,
  1717. BookWithO2O._meta.get_field("author").column,
  1718. (Author._meta.db_table, Author._meta.pk.column),
  1719. )
  1720. self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0})
  1721. old_field = BookWithO2O._meta.get_field("author")
  1722. # on_delete changed from CASCADE.
  1723. new_field = OneToOneField(Author, PROTECT)
  1724. new_field.set_attributes_from_name("author")
  1725. with connection.schema_editor() as editor:
  1726. editor.alter_field(BookWithO2O, old_field, new_field, strict=True)
  1727. counts = self.get_constraints_count(
  1728. BookWithO2O._meta.db_table,
  1729. BookWithO2O._meta.get_field("author").column,
  1730. (Author._meta.db_table, Author._meta.pk.column),
  1731. )
  1732. # The unique constraint remains.
  1733. self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0})
  1734. @skipUnlessDBFeature("ignores_table_name_case")
  1735. def test_alter_db_table_case(self):
  1736. # Create the table
  1737. with connection.schema_editor() as editor:
  1738. editor.create_model(Author)
  1739. # Alter the case of the table
  1740. old_table_name = Author._meta.db_table
  1741. with connection.schema_editor() as editor:
  1742. editor.alter_db_table(Author, old_table_name, old_table_name.upper())
  1743. def test_alter_implicit_id_to_explicit(self):
  1744. """
  1745. Should be able to convert an implicit "id" field to an explicit "id"
  1746. primary key field.
  1747. """
  1748. with connection.schema_editor() as editor:
  1749. editor.create_model(Author)
  1750. old_field = Author._meta.get_field("id")
  1751. new_field = AutoField(primary_key=True)
  1752. new_field.set_attributes_from_name("id")
  1753. new_field.model = Author
  1754. with connection.schema_editor() as editor:
  1755. editor.alter_field(Author, old_field, new_field, strict=True)
  1756. # This will fail if DROP DEFAULT is inadvertently executed on this
  1757. # field which drops the id sequence, at least on PostgreSQL.
  1758. Author.objects.create(name="Foo")
  1759. Author.objects.create(name="Bar")
  1760. def test_alter_autofield_pk_to_bigautofield_pk(self):
  1761. with connection.schema_editor() as editor:
  1762. editor.create_model(Author)
  1763. old_field = Author._meta.get_field("id")
  1764. new_field = BigAutoField(primary_key=True)
  1765. new_field.set_attributes_from_name("id")
  1766. new_field.model = Author
  1767. with connection.schema_editor() as editor:
  1768. editor.alter_field(Author, old_field, new_field, strict=True)
  1769. Author.objects.create(name="Foo", pk=1)
  1770. with connection.cursor() as cursor:
  1771. sequence_reset_sqls = connection.ops.sequence_reset_sql(
  1772. no_style(), [Author]
  1773. )
  1774. if sequence_reset_sqls:
  1775. cursor.execute(sequence_reset_sqls[0])
  1776. self.assertIsNotNone(Author.objects.create(name="Bar"))
  1777. def test_alter_autofield_pk_to_smallautofield_pk(self):
  1778. with connection.schema_editor() as editor:
  1779. editor.create_model(Author)
  1780. old_field = Author._meta.get_field("id")
  1781. new_field = SmallAutoField(primary_key=True)
  1782. new_field.set_attributes_from_name("id")
  1783. new_field.model = Author
  1784. with connection.schema_editor() as editor:
  1785. editor.alter_field(Author, old_field, new_field, strict=True)
  1786. Author.objects.create(name="Foo", pk=1)
  1787. with connection.cursor() as cursor:
  1788. sequence_reset_sqls = connection.ops.sequence_reset_sql(
  1789. no_style(), [Author]
  1790. )
  1791. if sequence_reset_sqls:
  1792. cursor.execute(sequence_reset_sqls[0])
  1793. self.assertIsNotNone(Author.objects.create(name="Bar"))
  1794. def test_alter_int_pk_to_autofield_pk(self):
  1795. """
  1796. Should be able to rename an IntegerField(primary_key=True) to
  1797. AutoField(primary_key=True).
  1798. """
  1799. with connection.schema_editor() as editor:
  1800. editor.create_model(IntegerPK)
  1801. old_field = IntegerPK._meta.get_field("i")
  1802. new_field = AutoField(primary_key=True)
  1803. new_field.model = IntegerPK
  1804. new_field.set_attributes_from_name("i")
  1805. with connection.schema_editor() as editor:
  1806. editor.alter_field(IntegerPK, old_field, new_field, strict=True)
  1807. # A model representing the updated model.
  1808. class IntegerPKToAutoField(Model):
  1809. i = AutoField(primary_key=True)
  1810. j = IntegerField(unique=True)
  1811. class Meta:
  1812. app_label = "schema"
  1813. apps = new_apps
  1814. db_table = IntegerPK._meta.db_table
  1815. # An id (i) is generated by the database.
  1816. obj = IntegerPKToAutoField.objects.create(j=1)
  1817. self.assertIsNotNone(obj.i)
  1818. def test_alter_int_pk_to_bigautofield_pk(self):
  1819. """
  1820. Should be able to rename an IntegerField(primary_key=True) to
  1821. BigAutoField(primary_key=True).
  1822. """
  1823. with connection.schema_editor() as editor:
  1824. editor.create_model(IntegerPK)
  1825. old_field = IntegerPK._meta.get_field("i")
  1826. new_field = BigAutoField(primary_key=True)
  1827. new_field.model = IntegerPK
  1828. new_field.set_attributes_from_name("i")
  1829. with connection.schema_editor() as editor:
  1830. editor.alter_field(IntegerPK, old_field, new_field, strict=True)
  1831. # A model representing the updated model.
  1832. class IntegerPKToBigAutoField(Model):
  1833. i = BigAutoField(primary_key=True)
  1834. j = IntegerField(unique=True)
  1835. class Meta:
  1836. app_label = "schema"
  1837. apps = new_apps
  1838. db_table = IntegerPK._meta.db_table
  1839. # An id (i) is generated by the database.
  1840. obj = IntegerPKToBigAutoField.objects.create(j=1)
  1841. self.assertIsNotNone(obj.i)
  1842. @isolate_apps("schema")
  1843. def test_alter_smallint_pk_to_smallautofield_pk(self):
  1844. """
  1845. Should be able to rename an SmallIntegerField(primary_key=True) to
  1846. SmallAutoField(primary_key=True).
  1847. """
  1848. class SmallIntegerPK(Model):
  1849. i = SmallIntegerField(primary_key=True)
  1850. class Meta:
  1851. app_label = "schema"
  1852. with connection.schema_editor() as editor:
  1853. editor.create_model(SmallIntegerPK)
  1854. self.isolated_local_models = [SmallIntegerPK]
  1855. old_field = SmallIntegerPK._meta.get_field("i")
  1856. new_field = SmallAutoField(primary_key=True)
  1857. new_field.model = SmallIntegerPK
  1858. new_field.set_attributes_from_name("i")
  1859. with connection.schema_editor() as editor:
  1860. editor.alter_field(SmallIntegerPK, old_field, new_field, strict=True)
  1861. @isolate_apps("schema")
  1862. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  1863. def test_alter_serial_auto_field_to_bigautofield(self):
  1864. class SerialAutoField(Model):
  1865. id = SmallAutoField(primary_key=True)
  1866. class Meta:
  1867. app_label = "schema"
  1868. table = SerialAutoField._meta.db_table
  1869. column = SerialAutoField._meta.get_field("id").column
  1870. with connection.cursor() as cursor:
  1871. cursor.execute(
  1872. f'CREATE TABLE "{table}" '
  1873. f'("{column}" smallserial NOT NULL PRIMARY KEY)'
  1874. )
  1875. try:
  1876. old_field = SerialAutoField._meta.get_field("id")
  1877. new_field = BigAutoField(primary_key=True)
  1878. new_field.model = SerialAutoField
  1879. new_field.set_attributes_from_name("id")
  1880. with connection.schema_editor() as editor:
  1881. editor.alter_field(SerialAutoField, old_field, new_field, strict=True)
  1882. sequence_name = f"{table}_{column}_seq"
  1883. with connection.cursor() as cursor:
  1884. cursor.execute(
  1885. "SELECT data_type FROM pg_sequences WHERE sequencename = %s",
  1886. [sequence_name],
  1887. )
  1888. row = cursor.fetchone()
  1889. sequence_data_type = row[0] if row and row[0] else None
  1890. self.assertEqual(sequence_data_type, "bigint")
  1891. # Rename the column.
  1892. old_field = new_field
  1893. new_field = AutoField(primary_key=True)
  1894. new_field.model = SerialAutoField
  1895. new_field.set_attributes_from_name("renamed_id")
  1896. with connection.schema_editor() as editor:
  1897. editor.alter_field(SerialAutoField, old_field, new_field, strict=True)
  1898. with connection.cursor() as cursor:
  1899. cursor.execute(
  1900. "SELECT data_type FROM pg_sequences WHERE sequencename = %s",
  1901. [sequence_name],
  1902. )
  1903. row = cursor.fetchone()
  1904. sequence_data_type = row[0] if row and row[0] else None
  1905. self.assertEqual(sequence_data_type, "integer")
  1906. finally:
  1907. with connection.cursor() as cursor:
  1908. cursor.execute(f'DROP TABLE "{table}"')
  1909. def test_alter_int_pk_to_int_unique(self):
  1910. """
  1911. Should be able to rename an IntegerField(primary_key=True) to
  1912. IntegerField(unique=True).
  1913. """
  1914. with connection.schema_editor() as editor:
  1915. editor.create_model(IntegerPK)
  1916. # Delete the old PK
  1917. old_field = IntegerPK._meta.get_field("i")
  1918. new_field = IntegerField(unique=True)
  1919. new_field.model = IntegerPK
  1920. new_field.set_attributes_from_name("i")
  1921. with connection.schema_editor() as editor:
  1922. editor.alter_field(IntegerPK, old_field, new_field, strict=True)
  1923. # The primary key constraint is gone. Result depends on database:
  1924. # 'id' for SQLite, None for others (must not be 'i').
  1925. self.assertIn(self.get_primary_key(IntegerPK._meta.db_table), ("id", None))
  1926. # Set up a model class as it currently stands. The original IntegerPK
  1927. # class is now out of date and some backends make use of the whole
  1928. # model class when modifying a field (such as sqlite3 when remaking a
  1929. # table) so an outdated model class leads to incorrect results.
  1930. class Transitional(Model):
  1931. i = IntegerField(unique=True)
  1932. j = IntegerField(unique=True)
  1933. class Meta:
  1934. app_label = "schema"
  1935. apps = new_apps
  1936. db_table = "INTEGERPK"
  1937. # model requires a new PK
  1938. old_field = Transitional._meta.get_field("j")
  1939. new_field = IntegerField(primary_key=True)
  1940. new_field.model = Transitional
  1941. new_field.set_attributes_from_name("j")
  1942. with connection.schema_editor() as editor:
  1943. editor.alter_field(Transitional, old_field, new_field, strict=True)
  1944. # Create a model class representing the updated model.
  1945. class IntegerUnique(Model):
  1946. i = IntegerField(unique=True)
  1947. j = IntegerField(primary_key=True)
  1948. class Meta:
  1949. app_label = "schema"
  1950. apps = new_apps
  1951. db_table = "INTEGERPK"
  1952. # Ensure unique constraint works.
  1953. IntegerUnique.objects.create(i=1, j=1)
  1954. with self.assertRaises(IntegrityError):
  1955. IntegerUnique.objects.create(i=1, j=2)
  1956. def test_rename(self):
  1957. """
  1958. Tests simple altering of fields
  1959. """
  1960. # Create the table
  1961. with connection.schema_editor() as editor:
  1962. editor.create_model(Author)
  1963. # Ensure the field is right to begin with
  1964. columns = self.column_classes(Author)
  1965. self.assertEqual(
  1966. columns["name"][0],
  1967. connection.features.introspected_field_types["CharField"],
  1968. )
  1969. self.assertNotIn("display_name", columns)
  1970. # Alter the name field's name
  1971. old_field = Author._meta.get_field("name")
  1972. new_field = CharField(max_length=254)
  1973. new_field.set_attributes_from_name("display_name")
  1974. with connection.schema_editor() as editor:
  1975. editor.alter_field(Author, old_field, new_field, strict=True)
  1976. columns = self.column_classes(Author)
  1977. self.assertEqual(
  1978. columns["display_name"][0],
  1979. connection.features.introspected_field_types["CharField"],
  1980. )
  1981. self.assertNotIn("name", columns)
  1982. @isolate_apps("schema")
  1983. def test_rename_referenced_field(self):
  1984. class Author(Model):
  1985. name = CharField(max_length=255, unique=True)
  1986. class Meta:
  1987. app_label = "schema"
  1988. class Book(Model):
  1989. author = ForeignKey(Author, CASCADE, to_field="name")
  1990. class Meta:
  1991. app_label = "schema"
  1992. with connection.schema_editor() as editor:
  1993. editor.create_model(Author)
  1994. editor.create_model(Book)
  1995. new_field = CharField(max_length=255, unique=True)
  1996. new_field.set_attributes_from_name("renamed")
  1997. with connection.schema_editor() as editor:
  1998. editor.alter_field(Author, Author._meta.get_field("name"), new_field)
  1999. # Ensure the foreign key reference was updated.
  2000. self.assertForeignKeyExists(Book, "author_id", "schema_author", "renamed")
  2001. @skipIfDBFeature("interprets_empty_strings_as_nulls")
  2002. def test_rename_keep_null_status(self):
  2003. """
  2004. Renaming a field shouldn't affect the not null status.
  2005. """
  2006. with connection.schema_editor() as editor:
  2007. editor.create_model(Note)
  2008. with self.assertRaises(IntegrityError):
  2009. Note.objects.create(info=None)
  2010. old_field = Note._meta.get_field("info")
  2011. new_field = TextField()
  2012. new_field.set_attributes_from_name("detail_info")
  2013. with connection.schema_editor() as editor:
  2014. editor.alter_field(Note, old_field, new_field, strict=True)
  2015. columns = self.column_classes(Note)
  2016. self.assertEqual(columns["detail_info"][0], "TextField")
  2017. self.assertNotIn("info", columns)
  2018. with self.assertRaises(IntegrityError):
  2019. NoteRename.objects.create(detail_info=None)
  2020. @isolate_apps("schema")
  2021. def test_rename_keep_db_default(self):
  2022. """Renaming a field shouldn't affect a database default."""
  2023. class AuthorDbDefault(Model):
  2024. birth_year = IntegerField(db_default=1985)
  2025. class Meta:
  2026. app_label = "schema"
  2027. self.isolated_local_models = [AuthorDbDefault]
  2028. with connection.schema_editor() as editor:
  2029. editor.create_model(AuthorDbDefault)
  2030. columns = self.column_classes(AuthorDbDefault)
  2031. self.assertEqual(columns["birth_year"][1].default, "1985")
  2032. old_field = AuthorDbDefault._meta.get_field("birth_year")
  2033. new_field = IntegerField(db_default=1985)
  2034. new_field.set_attributes_from_name("renamed_year")
  2035. new_field.model = AuthorDbDefault
  2036. with connection.schema_editor() as editor:
  2037. editor.alter_field(AuthorDbDefault, old_field, new_field, strict=True)
  2038. columns = self.column_classes(AuthorDbDefault)
  2039. self.assertEqual(columns["renamed_year"][1].default, "1985")
  2040. @isolate_apps("schema")
  2041. def test_add_field_both_defaults_preserves_db_default(self):
  2042. class Author(Model):
  2043. class Meta:
  2044. app_label = "schema"
  2045. with connection.schema_editor() as editor:
  2046. editor.create_model(Author)
  2047. field = IntegerField(default=1985, db_default=1988)
  2048. field.set_attributes_from_name("birth_year")
  2049. field.model = Author
  2050. with connection.schema_editor() as editor:
  2051. editor.add_field(Author, field)
  2052. columns = self.column_classes(Author)
  2053. self.assertEqual(columns["birth_year"][1].default, "1988")
  2054. @skipUnlessDBFeature(
  2055. "supports_column_check_constraints", "can_introspect_check_constraints"
  2056. )
  2057. @isolate_apps("schema")
  2058. def test_rename_field_with_check_to_truncated_name(self):
  2059. class AuthorWithLongColumn(Model):
  2060. field_with_very_looooooong_name = PositiveIntegerField(null=True)
  2061. class Meta:
  2062. app_label = "schema"
  2063. self.isolated_local_models = [AuthorWithLongColumn]
  2064. with connection.schema_editor() as editor:
  2065. editor.create_model(AuthorWithLongColumn)
  2066. old_field = AuthorWithLongColumn._meta.get_field(
  2067. "field_with_very_looooooong_name"
  2068. )
  2069. new_field = PositiveIntegerField(null=True)
  2070. new_field.set_attributes_from_name("renamed_field_with_very_long_name")
  2071. with connection.schema_editor() as editor:
  2072. editor.alter_field(AuthorWithLongColumn, old_field, new_field, strict=True)
  2073. new_field_name = truncate_name(
  2074. new_field.column, connection.ops.max_name_length()
  2075. )
  2076. constraints = self.get_constraints(AuthorWithLongColumn._meta.db_table)
  2077. check_constraints = [
  2078. name
  2079. for name, details in constraints.items()
  2080. if details["columns"] == [new_field_name] and details["check"]
  2081. ]
  2082. self.assertEqual(len(check_constraints), 1)
  2083. def _test_m2m_create(self, M2MFieldClass):
  2084. """
  2085. Tests M2M fields on models during creation
  2086. """
  2087. class LocalBookWithM2M(Model):
  2088. author = ForeignKey(Author, CASCADE)
  2089. title = CharField(max_length=100, db_index=True)
  2090. pub_date = DateTimeField()
  2091. tags = M2MFieldClass("TagM2MTest", related_name="books")
  2092. class Meta:
  2093. app_label = "schema"
  2094. apps = new_apps
  2095. self.local_models = [LocalBookWithM2M]
  2096. # Create the tables
  2097. with connection.schema_editor() as editor:
  2098. editor.create_model(Author)
  2099. editor.create_model(TagM2MTest)
  2100. editor.create_model(LocalBookWithM2M)
  2101. # Ensure there is now an m2m table there
  2102. columns = self.column_classes(
  2103. LocalBookWithM2M._meta.get_field("tags").remote_field.through
  2104. )
  2105. self.assertEqual(
  2106. columns["tagm2mtest_id"][0],
  2107. connection.features.introspected_field_types["IntegerField"],
  2108. )
  2109. def test_m2m_create(self):
  2110. self._test_m2m_create(ManyToManyField)
  2111. def test_m2m_create_custom(self):
  2112. self._test_m2m_create(CustomManyToManyField)
  2113. def test_m2m_create_inherited(self):
  2114. self._test_m2m_create(InheritedManyToManyField)
  2115. def _test_m2m_create_through(self, M2MFieldClass):
  2116. """
  2117. Tests M2M fields on models during creation with through models
  2118. """
  2119. class LocalTagThrough(Model):
  2120. book = ForeignKey("schema.LocalBookWithM2MThrough", CASCADE)
  2121. tag = ForeignKey("schema.TagM2MTest", CASCADE)
  2122. class Meta:
  2123. app_label = "schema"
  2124. apps = new_apps
  2125. class LocalBookWithM2MThrough(Model):
  2126. tags = M2MFieldClass(
  2127. "TagM2MTest", related_name="books", through=LocalTagThrough
  2128. )
  2129. class Meta:
  2130. app_label = "schema"
  2131. apps = new_apps
  2132. self.local_models = [LocalTagThrough, LocalBookWithM2MThrough]
  2133. # Create the tables
  2134. with connection.schema_editor() as editor:
  2135. editor.create_model(LocalTagThrough)
  2136. editor.create_model(TagM2MTest)
  2137. editor.create_model(LocalBookWithM2MThrough)
  2138. # Ensure there is now an m2m table there
  2139. columns = self.column_classes(LocalTagThrough)
  2140. self.assertEqual(
  2141. columns["book_id"][0],
  2142. connection.features.introspected_field_types["IntegerField"],
  2143. )
  2144. self.assertEqual(
  2145. columns["tag_id"][0],
  2146. connection.features.introspected_field_types["IntegerField"],
  2147. )
  2148. def test_m2m_create_through(self):
  2149. self._test_m2m_create_through(ManyToManyField)
  2150. def test_m2m_create_through_custom(self):
  2151. self._test_m2m_create_through(CustomManyToManyField)
  2152. def test_m2m_create_through_inherited(self):
  2153. self._test_m2m_create_through(InheritedManyToManyField)
  2154. def test_m2m_through_remove(self):
  2155. class LocalAuthorNoteThrough(Model):
  2156. book = ForeignKey("schema.Author", CASCADE)
  2157. tag = ForeignKey("self", CASCADE)
  2158. class Meta:
  2159. app_label = "schema"
  2160. apps = new_apps
  2161. class LocalNoteWithM2MThrough(Model):
  2162. authors = ManyToManyField("schema.Author", through=LocalAuthorNoteThrough)
  2163. class Meta:
  2164. app_label = "schema"
  2165. apps = new_apps
  2166. self.local_models = [LocalAuthorNoteThrough, LocalNoteWithM2MThrough]
  2167. # Create the tables.
  2168. with connection.schema_editor() as editor:
  2169. editor.create_model(Author)
  2170. editor.create_model(LocalAuthorNoteThrough)
  2171. editor.create_model(LocalNoteWithM2MThrough)
  2172. # Remove the through parameter.
  2173. old_field = LocalNoteWithM2MThrough._meta.get_field("authors")
  2174. new_field = ManyToManyField("Author")
  2175. new_field.set_attributes_from_name("authors")
  2176. msg = (
  2177. f"Cannot alter field {old_field} into {new_field} - they are not "
  2178. f"compatible types (you cannot alter to or from M2M fields, or add or "
  2179. f"remove through= on M2M fields)"
  2180. )
  2181. with connection.schema_editor() as editor:
  2182. with self.assertRaisesMessage(ValueError, msg):
  2183. editor.alter_field(LocalNoteWithM2MThrough, old_field, new_field)
  2184. def _test_m2m(self, M2MFieldClass):
  2185. """
  2186. Tests adding/removing M2M fields on models
  2187. """
  2188. class LocalAuthorWithM2M(Model):
  2189. name = CharField(max_length=255)
  2190. class Meta:
  2191. app_label = "schema"
  2192. apps = new_apps
  2193. self.local_models = [LocalAuthorWithM2M]
  2194. # Create the tables
  2195. with connection.schema_editor() as editor:
  2196. editor.create_model(LocalAuthorWithM2M)
  2197. editor.create_model(TagM2MTest)
  2198. # Create an M2M field
  2199. new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors")
  2200. new_field.contribute_to_class(LocalAuthorWithM2M, "tags")
  2201. # Ensure there's no m2m table there
  2202. with self.assertRaises(DatabaseError):
  2203. self.column_classes(new_field.remote_field.through)
  2204. # Add the field
  2205. with CaptureQueriesContext(
  2206. connection
  2207. ) as ctx, connection.schema_editor() as editor:
  2208. editor.add_field(LocalAuthorWithM2M, new_field)
  2209. # Table is not rebuilt.
  2210. self.assertEqual(
  2211. len(
  2212. [
  2213. query["sql"]
  2214. for query in ctx.captured_queries
  2215. if "CREATE TABLE" in query["sql"]
  2216. ]
  2217. ),
  2218. 1,
  2219. )
  2220. self.assertIs(
  2221. any("DROP TABLE" in query["sql"] for query in ctx.captured_queries),
  2222. False,
  2223. )
  2224. # Ensure there is now an m2m table there
  2225. columns = self.column_classes(new_field.remote_field.through)
  2226. self.assertEqual(
  2227. columns["tagm2mtest_id"][0],
  2228. connection.features.introspected_field_types["IntegerField"],
  2229. )
  2230. # "Alter" the field. This should not rename the DB table to itself.
  2231. with connection.schema_editor() as editor:
  2232. editor.alter_field(LocalAuthorWithM2M, new_field, new_field, strict=True)
  2233. # Remove the M2M table again
  2234. with connection.schema_editor() as editor:
  2235. editor.remove_field(LocalAuthorWithM2M, new_field)
  2236. # Ensure there's no m2m table there
  2237. with self.assertRaises(DatabaseError):
  2238. self.column_classes(new_field.remote_field.through)
  2239. # Make sure the model state is coherent with the table one now that
  2240. # we've removed the tags field.
  2241. opts = LocalAuthorWithM2M._meta
  2242. opts.local_many_to_many.remove(new_field)
  2243. del new_apps.all_models["schema"][
  2244. new_field.remote_field.through._meta.model_name
  2245. ]
  2246. opts._expire_cache()
  2247. def test_m2m(self):
  2248. self._test_m2m(ManyToManyField)
  2249. def test_m2m_custom(self):
  2250. self._test_m2m(CustomManyToManyField)
  2251. def test_m2m_inherited(self):
  2252. self._test_m2m(InheritedManyToManyField)
  2253. def _test_m2m_through_alter(self, M2MFieldClass):
  2254. """
  2255. Tests altering M2Ms with explicit through models (should no-op)
  2256. """
  2257. class LocalAuthorTag(Model):
  2258. author = ForeignKey("schema.LocalAuthorWithM2MThrough", CASCADE)
  2259. tag = ForeignKey("schema.TagM2MTest", CASCADE)
  2260. class Meta:
  2261. app_label = "schema"
  2262. apps = new_apps
  2263. class LocalAuthorWithM2MThrough(Model):
  2264. name = CharField(max_length=255)
  2265. tags = M2MFieldClass(
  2266. "schema.TagM2MTest", related_name="authors", through=LocalAuthorTag
  2267. )
  2268. class Meta:
  2269. app_label = "schema"
  2270. apps = new_apps
  2271. self.local_models = [LocalAuthorTag, LocalAuthorWithM2MThrough]
  2272. # Create the tables
  2273. with connection.schema_editor() as editor:
  2274. editor.create_model(LocalAuthorTag)
  2275. editor.create_model(LocalAuthorWithM2MThrough)
  2276. editor.create_model(TagM2MTest)
  2277. # Ensure the m2m table is there
  2278. self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3)
  2279. # "Alter" the field's blankness. This should not actually do anything.
  2280. old_field = LocalAuthorWithM2MThrough._meta.get_field("tags")
  2281. new_field = M2MFieldClass(
  2282. "schema.TagM2MTest", related_name="authors", through=LocalAuthorTag
  2283. )
  2284. new_field.contribute_to_class(LocalAuthorWithM2MThrough, "tags")
  2285. with connection.schema_editor() as editor:
  2286. editor.alter_field(
  2287. LocalAuthorWithM2MThrough, old_field, new_field, strict=True
  2288. )
  2289. # Ensure the m2m table is still there
  2290. self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3)
  2291. def test_m2m_through_alter(self):
  2292. self._test_m2m_through_alter(ManyToManyField)
  2293. def test_m2m_through_alter_custom(self):
  2294. self._test_m2m_through_alter(CustomManyToManyField)
  2295. def test_m2m_through_alter_inherited(self):
  2296. self._test_m2m_through_alter(InheritedManyToManyField)
  2297. def _test_m2m_repoint(self, M2MFieldClass):
  2298. """
  2299. Tests repointing M2M fields
  2300. """
  2301. class LocalBookWithM2M(Model):
  2302. author = ForeignKey(Author, CASCADE)
  2303. title = CharField(max_length=100, db_index=True)
  2304. pub_date = DateTimeField()
  2305. tags = M2MFieldClass("TagM2MTest", related_name="books")
  2306. class Meta:
  2307. app_label = "schema"
  2308. apps = new_apps
  2309. self.local_models = [LocalBookWithM2M]
  2310. # Create the tables
  2311. with connection.schema_editor() as editor:
  2312. editor.create_model(Author)
  2313. editor.create_model(LocalBookWithM2M)
  2314. editor.create_model(TagM2MTest)
  2315. editor.create_model(UniqueTest)
  2316. # Ensure the M2M exists and points to TagM2MTest
  2317. if connection.features.supports_foreign_keys:
  2318. self.assertForeignKeyExists(
  2319. LocalBookWithM2M._meta.get_field("tags").remote_field.through,
  2320. "tagm2mtest_id",
  2321. "schema_tagm2mtest",
  2322. )
  2323. # Repoint the M2M
  2324. old_field = LocalBookWithM2M._meta.get_field("tags")
  2325. new_field = M2MFieldClass(UniqueTest)
  2326. new_field.contribute_to_class(LocalBookWithM2M, "uniques")
  2327. with connection.schema_editor() as editor:
  2328. editor.alter_field(LocalBookWithM2M, old_field, new_field, strict=True)
  2329. # Ensure old M2M is gone
  2330. with self.assertRaises(DatabaseError):
  2331. self.column_classes(
  2332. LocalBookWithM2M._meta.get_field("tags").remote_field.through
  2333. )
  2334. # This model looks like the new model and is used for teardown.
  2335. opts = LocalBookWithM2M._meta
  2336. opts.local_many_to_many.remove(old_field)
  2337. # Ensure the new M2M exists and points to UniqueTest
  2338. if connection.features.supports_foreign_keys:
  2339. self.assertForeignKeyExists(
  2340. new_field.remote_field.through, "uniquetest_id", "schema_uniquetest"
  2341. )
  2342. def test_m2m_repoint(self):
  2343. self._test_m2m_repoint(ManyToManyField)
  2344. def test_m2m_repoint_custom(self):
  2345. self._test_m2m_repoint(CustomManyToManyField)
  2346. def test_m2m_repoint_inherited(self):
  2347. self._test_m2m_repoint(InheritedManyToManyField)
  2348. @isolate_apps("schema")
  2349. def test_m2m_rename_field_in_target_model(self):
  2350. class LocalTagM2MTest(Model):
  2351. title = CharField(max_length=255)
  2352. class Meta:
  2353. app_label = "schema"
  2354. class LocalM2M(Model):
  2355. tags = ManyToManyField(LocalTagM2MTest)
  2356. class Meta:
  2357. app_label = "schema"
  2358. # Create the tables.
  2359. with connection.schema_editor() as editor:
  2360. editor.create_model(LocalM2M)
  2361. editor.create_model(LocalTagM2MTest)
  2362. self.isolated_local_models = [LocalM2M, LocalTagM2MTest]
  2363. # Ensure the m2m table is there.
  2364. self.assertEqual(len(self.column_classes(LocalM2M)), 1)
  2365. # Alter a field in LocalTagM2MTest.
  2366. old_field = LocalTagM2MTest._meta.get_field("title")
  2367. new_field = CharField(max_length=254)
  2368. new_field.contribute_to_class(LocalTagM2MTest, "title1")
  2369. # @isolate_apps() and inner models are needed to have the model
  2370. # relations populated, otherwise this doesn't act as a regression test.
  2371. self.assertEqual(len(new_field.model._meta.related_objects), 1)
  2372. with connection.schema_editor() as editor:
  2373. editor.alter_field(LocalTagM2MTest, old_field, new_field, strict=True)
  2374. # Ensure the m2m table is still there.
  2375. self.assertEqual(len(self.column_classes(LocalM2M)), 1)
  2376. @skipUnlessDBFeature(
  2377. "supports_column_check_constraints", "can_introspect_check_constraints"
  2378. )
  2379. def test_check_constraints(self):
  2380. """
  2381. Tests creating/deleting CHECK constraints
  2382. """
  2383. # Create the tables
  2384. with connection.schema_editor() as editor:
  2385. editor.create_model(Author)
  2386. # Ensure the constraint exists
  2387. constraints = self.get_constraints(Author._meta.db_table)
  2388. if not any(
  2389. details["columns"] == ["height"] and details["check"]
  2390. for details in constraints.values()
  2391. ):
  2392. self.fail("No check constraint for height found")
  2393. # Alter the column to remove it
  2394. old_field = Author._meta.get_field("height")
  2395. new_field = IntegerField(null=True, blank=True)
  2396. new_field.set_attributes_from_name("height")
  2397. with connection.schema_editor() as editor:
  2398. editor.alter_field(Author, old_field, new_field, strict=True)
  2399. constraints = self.get_constraints(Author._meta.db_table)
  2400. for details in constraints.values():
  2401. if details["columns"] == ["height"] and details["check"]:
  2402. self.fail("Check constraint for height found")
  2403. # Alter the column to re-add it
  2404. new_field2 = Author._meta.get_field("height")
  2405. with connection.schema_editor() as editor:
  2406. editor.alter_field(Author, new_field, new_field2, strict=True)
  2407. constraints = self.get_constraints(Author._meta.db_table)
  2408. if not any(
  2409. details["columns"] == ["height"] and details["check"]
  2410. for details in constraints.values()
  2411. ):
  2412. self.fail("No check constraint for height found")
  2413. @skipUnlessDBFeature(
  2414. "supports_column_check_constraints", "can_introspect_check_constraints"
  2415. )
  2416. @isolate_apps("schema")
  2417. def test_check_constraint_timedelta_param(self):
  2418. class DurationModel(Model):
  2419. duration = DurationField()
  2420. class Meta:
  2421. app_label = "schema"
  2422. with connection.schema_editor() as editor:
  2423. editor.create_model(DurationModel)
  2424. self.isolated_local_models = [DurationModel]
  2425. constraint_name = "duration_gte_5_minutes"
  2426. constraint = CheckConstraint(
  2427. check=Q(duration__gt=datetime.timedelta(minutes=5)),
  2428. name=constraint_name,
  2429. )
  2430. DurationModel._meta.constraints = [constraint]
  2431. with connection.schema_editor() as editor:
  2432. editor.add_constraint(DurationModel, constraint)
  2433. constraints = self.get_constraints(DurationModel._meta.db_table)
  2434. self.assertIn(constraint_name, constraints)
  2435. with self.assertRaises(IntegrityError), atomic():
  2436. DurationModel.objects.create(duration=datetime.timedelta(minutes=4))
  2437. DurationModel.objects.create(duration=datetime.timedelta(minutes=10))
  2438. @skipUnlessDBFeature(
  2439. "supports_column_check_constraints", "can_introspect_check_constraints"
  2440. )
  2441. def test_remove_field_check_does_not_remove_meta_constraints(self):
  2442. with connection.schema_editor() as editor:
  2443. editor.create_model(Author)
  2444. # Add the custom check constraint
  2445. constraint = CheckConstraint(
  2446. check=Q(height__gte=0), name="author_height_gte_0_check"
  2447. )
  2448. custom_constraint_name = constraint.name
  2449. Author._meta.constraints = [constraint]
  2450. with connection.schema_editor() as editor:
  2451. editor.add_constraint(Author, constraint)
  2452. # Ensure the constraints exist
  2453. constraints = self.get_constraints(Author._meta.db_table)
  2454. self.assertIn(custom_constraint_name, constraints)
  2455. other_constraints = [
  2456. name
  2457. for name, details in constraints.items()
  2458. if details["columns"] == ["height"]
  2459. and details["check"]
  2460. and name != custom_constraint_name
  2461. ]
  2462. self.assertEqual(len(other_constraints), 1)
  2463. # Alter the column to remove field check
  2464. old_field = Author._meta.get_field("height")
  2465. new_field = IntegerField(null=True, blank=True)
  2466. new_field.set_attributes_from_name("height")
  2467. with connection.schema_editor() as editor:
  2468. editor.alter_field(Author, old_field, new_field, strict=True)
  2469. constraints = self.get_constraints(Author._meta.db_table)
  2470. self.assertIn(custom_constraint_name, constraints)
  2471. other_constraints = [
  2472. name
  2473. for name, details in constraints.items()
  2474. if details["columns"] == ["height"]
  2475. and details["check"]
  2476. and name != custom_constraint_name
  2477. ]
  2478. self.assertEqual(len(other_constraints), 0)
  2479. # Alter the column to re-add field check
  2480. new_field2 = Author._meta.get_field("height")
  2481. with connection.schema_editor() as editor:
  2482. editor.alter_field(Author, new_field, new_field2, strict=True)
  2483. constraints = self.get_constraints(Author._meta.db_table)
  2484. self.assertIn(custom_constraint_name, constraints)
  2485. other_constraints = [
  2486. name
  2487. for name, details in constraints.items()
  2488. if details["columns"] == ["height"]
  2489. and details["check"]
  2490. and name != custom_constraint_name
  2491. ]
  2492. self.assertEqual(len(other_constraints), 1)
  2493. # Drop the check constraint
  2494. with connection.schema_editor() as editor:
  2495. Author._meta.constraints = []
  2496. editor.remove_constraint(Author, constraint)
  2497. def test_unique(self):
  2498. """
  2499. Tests removing and adding unique constraints to a single column.
  2500. """
  2501. # Create the table
  2502. with connection.schema_editor() as editor:
  2503. editor.create_model(Tag)
  2504. # Ensure the field is unique to begin with
  2505. Tag.objects.create(title="foo", slug="foo")
  2506. with self.assertRaises(IntegrityError):
  2507. Tag.objects.create(title="bar", slug="foo")
  2508. Tag.objects.all().delete()
  2509. # Alter the slug field to be non-unique
  2510. old_field = Tag._meta.get_field("slug")
  2511. new_field = SlugField(unique=False)
  2512. new_field.set_attributes_from_name("slug")
  2513. with connection.schema_editor() as editor:
  2514. editor.alter_field(Tag, old_field, new_field, strict=True)
  2515. # Ensure the field is no longer unique
  2516. Tag.objects.create(title="foo", slug="foo")
  2517. Tag.objects.create(title="bar", slug="foo")
  2518. Tag.objects.all().delete()
  2519. # Alter the slug field to be unique
  2520. new_field2 = SlugField(unique=True)
  2521. new_field2.set_attributes_from_name("slug")
  2522. with connection.schema_editor() as editor:
  2523. editor.alter_field(Tag, new_field, new_field2, strict=True)
  2524. # Ensure the field is unique again
  2525. Tag.objects.create(title="foo", slug="foo")
  2526. with self.assertRaises(IntegrityError):
  2527. Tag.objects.create(title="bar", slug="foo")
  2528. Tag.objects.all().delete()
  2529. # Rename the field
  2530. new_field3 = SlugField(unique=True)
  2531. new_field3.set_attributes_from_name("slug2")
  2532. with connection.schema_editor() as editor:
  2533. editor.alter_field(Tag, new_field2, new_field3, strict=True)
  2534. # Ensure the field is still unique
  2535. TagUniqueRename.objects.create(title="foo", slug2="foo")
  2536. with self.assertRaises(IntegrityError):
  2537. TagUniqueRename.objects.create(title="bar", slug2="foo")
  2538. Tag.objects.all().delete()
  2539. def test_unique_name_quoting(self):
  2540. old_table_name = TagUniqueRename._meta.db_table
  2541. try:
  2542. with connection.schema_editor() as editor:
  2543. editor.create_model(TagUniqueRename)
  2544. editor.alter_db_table(TagUniqueRename, old_table_name, "unique-table")
  2545. TagUniqueRename._meta.db_table = "unique-table"
  2546. # This fails if the unique index name isn't quoted.
  2547. editor.alter_unique_together(TagUniqueRename, [], (("title", "slug2"),))
  2548. finally:
  2549. with connection.schema_editor() as editor:
  2550. editor.delete_model(TagUniqueRename)
  2551. TagUniqueRename._meta.db_table = old_table_name
  2552. @isolate_apps("schema")
  2553. @skipUnlessDBFeature("supports_foreign_keys")
  2554. def test_unique_no_unnecessary_fk_drops(self):
  2555. """
  2556. If AlterField isn't selective about dropping foreign key constraints
  2557. when modifying a field with a unique constraint, the AlterField
  2558. incorrectly drops and recreates the Book.author foreign key even though
  2559. it doesn't restrict the field being changed (#29193).
  2560. """
  2561. class Author(Model):
  2562. name = CharField(max_length=254, unique=True)
  2563. class Meta:
  2564. app_label = "schema"
  2565. class Book(Model):
  2566. author = ForeignKey(Author, CASCADE)
  2567. class Meta:
  2568. app_label = "schema"
  2569. with connection.schema_editor() as editor:
  2570. editor.create_model(Author)
  2571. editor.create_model(Book)
  2572. new_field = CharField(max_length=255, unique=True)
  2573. new_field.model = Author
  2574. new_field.set_attributes_from_name("name")
  2575. with self.assertLogs("django.db.backends.schema", "DEBUG") as cm:
  2576. with connection.schema_editor() as editor:
  2577. editor.alter_field(Author, Author._meta.get_field("name"), new_field)
  2578. # One SQL statement is executed to alter the field.
  2579. self.assertEqual(len(cm.records), 1)
  2580. @isolate_apps("schema")
  2581. def test_unique_and_reverse_m2m(self):
  2582. """
  2583. AlterField can modify a unique field when there's a reverse M2M
  2584. relation on the model.
  2585. """
  2586. class Tag(Model):
  2587. title = CharField(max_length=255)
  2588. slug = SlugField(unique=True)
  2589. class Meta:
  2590. app_label = "schema"
  2591. class Book(Model):
  2592. tags = ManyToManyField(Tag, related_name="books")
  2593. class Meta:
  2594. app_label = "schema"
  2595. self.isolated_local_models = [Book._meta.get_field("tags").remote_field.through]
  2596. with connection.schema_editor() as editor:
  2597. editor.create_model(Tag)
  2598. editor.create_model(Book)
  2599. new_field = SlugField(max_length=75, unique=True)
  2600. new_field.model = Tag
  2601. new_field.set_attributes_from_name("slug")
  2602. with self.assertLogs("django.db.backends.schema", "DEBUG") as cm:
  2603. with connection.schema_editor() as editor:
  2604. editor.alter_field(Tag, Tag._meta.get_field("slug"), new_field)
  2605. # One SQL statement is executed to alter the field.
  2606. self.assertEqual(len(cm.records), 1)
  2607. # Ensure that the field is still unique.
  2608. Tag.objects.create(title="foo", slug="foo")
  2609. with self.assertRaises(IntegrityError):
  2610. Tag.objects.create(title="bar", slug="foo")
  2611. def test_remove_ignored_unique_constraint_not_create_fk_index(self):
  2612. with connection.schema_editor() as editor:
  2613. editor.create_model(Author)
  2614. editor.create_model(Book)
  2615. constraint = UniqueConstraint(
  2616. "author",
  2617. condition=Q(title__in=["tHGttG", "tRatEotU"]),
  2618. name="book_author_condition_uniq",
  2619. )
  2620. # Add unique constraint.
  2621. with connection.schema_editor() as editor:
  2622. editor.add_constraint(Book, constraint)
  2623. old_constraints = self.get_constraints_for_column(
  2624. Book,
  2625. Book._meta.get_field("author").column,
  2626. )
  2627. # Remove unique constraint.
  2628. with connection.schema_editor() as editor:
  2629. editor.remove_constraint(Book, constraint)
  2630. new_constraints = self.get_constraints_for_column(
  2631. Book,
  2632. Book._meta.get_field("author").column,
  2633. )
  2634. # Redundant foreign key index is not added.
  2635. self.assertEqual(
  2636. len(old_constraints) - 1
  2637. if connection.features.supports_partial_indexes
  2638. else len(old_constraints),
  2639. len(new_constraints),
  2640. )
  2641. @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields")
  2642. def test_remove_field_unique_does_not_remove_meta_constraints(self):
  2643. with connection.schema_editor() as editor:
  2644. editor.create_model(AuthorWithUniqueName)
  2645. self.local_models = [AuthorWithUniqueName]
  2646. # Add the custom unique constraint
  2647. constraint = UniqueConstraint(fields=["name"], name="author_name_uniq")
  2648. custom_constraint_name = constraint.name
  2649. AuthorWithUniqueName._meta.constraints = [constraint]
  2650. with connection.schema_editor() as editor:
  2651. editor.add_constraint(AuthorWithUniqueName, constraint)
  2652. # Ensure the constraints exist
  2653. constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table)
  2654. self.assertIn(custom_constraint_name, constraints)
  2655. other_constraints = [
  2656. name
  2657. for name, details in constraints.items()
  2658. if details["columns"] == ["name"]
  2659. and details["unique"]
  2660. and name != custom_constraint_name
  2661. ]
  2662. self.assertEqual(len(other_constraints), 1)
  2663. # Alter the column to remove field uniqueness
  2664. old_field = AuthorWithUniqueName._meta.get_field("name")
  2665. new_field = CharField(max_length=255)
  2666. new_field.set_attributes_from_name("name")
  2667. with connection.schema_editor() as editor:
  2668. editor.alter_field(AuthorWithUniqueName, old_field, new_field, strict=True)
  2669. constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table)
  2670. self.assertIn(custom_constraint_name, constraints)
  2671. other_constraints = [
  2672. name
  2673. for name, details in constraints.items()
  2674. if details["columns"] == ["name"]
  2675. and details["unique"]
  2676. and name != custom_constraint_name
  2677. ]
  2678. self.assertEqual(len(other_constraints), 0)
  2679. # Alter the column to re-add field uniqueness
  2680. new_field2 = AuthorWithUniqueName._meta.get_field("name")
  2681. with connection.schema_editor() as editor:
  2682. editor.alter_field(AuthorWithUniqueName, new_field, new_field2, strict=True)
  2683. constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table)
  2684. self.assertIn(custom_constraint_name, constraints)
  2685. other_constraints = [
  2686. name
  2687. for name, details in constraints.items()
  2688. if details["columns"] == ["name"]
  2689. and details["unique"]
  2690. and name != custom_constraint_name
  2691. ]
  2692. self.assertEqual(len(other_constraints), 1)
  2693. # Drop the unique constraint
  2694. with connection.schema_editor() as editor:
  2695. AuthorWithUniqueName._meta.constraints = []
  2696. editor.remove_constraint(AuthorWithUniqueName, constraint)
  2697. def test_unique_together(self):
  2698. """
  2699. Tests removing and adding unique_together constraints on a model.
  2700. """
  2701. # Create the table
  2702. with connection.schema_editor() as editor:
  2703. editor.create_model(UniqueTest)
  2704. # Ensure the fields are unique to begin with
  2705. UniqueTest.objects.create(year=2012, slug="foo")
  2706. UniqueTest.objects.create(year=2011, slug="foo")
  2707. UniqueTest.objects.create(year=2011, slug="bar")
  2708. with self.assertRaises(IntegrityError):
  2709. UniqueTest.objects.create(year=2012, slug="foo")
  2710. UniqueTest.objects.all().delete()
  2711. # Alter the model to its non-unique-together companion
  2712. with connection.schema_editor() as editor:
  2713. editor.alter_unique_together(
  2714. UniqueTest, UniqueTest._meta.unique_together, []
  2715. )
  2716. # Ensure the fields are no longer unique
  2717. UniqueTest.objects.create(year=2012, slug="foo")
  2718. UniqueTest.objects.create(year=2012, slug="foo")
  2719. UniqueTest.objects.all().delete()
  2720. # Alter it back
  2721. new_field2 = SlugField(unique=True)
  2722. new_field2.set_attributes_from_name("slug")
  2723. with connection.schema_editor() as editor:
  2724. editor.alter_unique_together(
  2725. UniqueTest, [], UniqueTest._meta.unique_together
  2726. )
  2727. # Ensure the fields are unique again
  2728. UniqueTest.objects.create(year=2012, slug="foo")
  2729. with self.assertRaises(IntegrityError):
  2730. UniqueTest.objects.create(year=2012, slug="foo")
  2731. UniqueTest.objects.all().delete()
  2732. def test_unique_together_with_fk(self):
  2733. """
  2734. Tests removing and adding unique_together constraints that include
  2735. a foreign key.
  2736. """
  2737. # Create the table
  2738. with connection.schema_editor() as editor:
  2739. editor.create_model(Author)
  2740. editor.create_model(Book)
  2741. # Ensure the fields are unique to begin with
  2742. self.assertEqual(Book._meta.unique_together, ())
  2743. # Add the unique_together constraint
  2744. with connection.schema_editor() as editor:
  2745. editor.alter_unique_together(Book, [], [["author", "title"]])
  2746. # Alter it back
  2747. with connection.schema_editor() as editor:
  2748. editor.alter_unique_together(Book, [["author", "title"]], [])
  2749. def test_unique_together_with_fk_with_existing_index(self):
  2750. """
  2751. Tests removing and adding unique_together constraints that include
  2752. a foreign key, where the foreign key is added after the model is
  2753. created.
  2754. """
  2755. # Create the tables
  2756. with connection.schema_editor() as editor:
  2757. editor.create_model(Author)
  2758. editor.create_model(BookWithoutAuthor)
  2759. new_field = ForeignKey(Author, CASCADE)
  2760. new_field.set_attributes_from_name("author")
  2761. editor.add_field(BookWithoutAuthor, new_field)
  2762. # Ensure the fields aren't unique to begin with
  2763. self.assertEqual(Book._meta.unique_together, ())
  2764. # Add the unique_together constraint
  2765. with connection.schema_editor() as editor:
  2766. editor.alter_unique_together(Book, [], [["author", "title"]])
  2767. # Alter it back
  2768. with connection.schema_editor() as editor:
  2769. editor.alter_unique_together(Book, [["author", "title"]], [])
  2770. def _test_composed_index_with_fk(self, index):
  2771. with connection.schema_editor() as editor:
  2772. editor.create_model(Author)
  2773. editor.create_model(Book)
  2774. table = Book._meta.db_table
  2775. self.assertEqual(Book._meta.indexes, [])
  2776. Book._meta.indexes = [index]
  2777. with connection.schema_editor() as editor:
  2778. editor.add_index(Book, index)
  2779. self.assertIn(index.name, self.get_constraints(table))
  2780. Book._meta.indexes = []
  2781. with connection.schema_editor() as editor:
  2782. editor.remove_index(Book, index)
  2783. self.assertNotIn(index.name, self.get_constraints(table))
  2784. def test_composed_index_with_fk(self):
  2785. index = Index(fields=["author", "title"], name="book_author_title_idx")
  2786. self._test_composed_index_with_fk(index)
  2787. def test_composed_desc_index_with_fk(self):
  2788. index = Index(fields=["-author", "title"], name="book_author_title_idx")
  2789. self._test_composed_index_with_fk(index)
  2790. @skipUnlessDBFeature("supports_expression_indexes")
  2791. def test_composed_func_index_with_fk(self):
  2792. index = Index(F("author"), F("title"), name="book_author_title_idx")
  2793. self._test_composed_index_with_fk(index)
  2794. @skipUnlessDBFeature("supports_expression_indexes")
  2795. def test_composed_desc_func_index_with_fk(self):
  2796. index = Index(F("author").desc(), F("title"), name="book_author_title_idx")
  2797. self._test_composed_index_with_fk(index)
  2798. @skipUnlessDBFeature("supports_expression_indexes")
  2799. def test_composed_func_transform_index_with_fk(self):
  2800. index = Index(F("title__lower"), name="book_title_lower_idx")
  2801. with register_lookup(CharField, Lower):
  2802. self._test_composed_index_with_fk(index)
  2803. def _test_composed_constraint_with_fk(self, constraint):
  2804. with connection.schema_editor() as editor:
  2805. editor.create_model(Author)
  2806. editor.create_model(Book)
  2807. table = Book._meta.db_table
  2808. self.assertEqual(Book._meta.constraints, [])
  2809. Book._meta.constraints = [constraint]
  2810. with connection.schema_editor() as editor:
  2811. editor.add_constraint(Book, constraint)
  2812. self.assertIn(constraint.name, self.get_constraints(table))
  2813. Book._meta.constraints = []
  2814. with connection.schema_editor() as editor:
  2815. editor.remove_constraint(Book, constraint)
  2816. self.assertNotIn(constraint.name, self.get_constraints(table))
  2817. def test_composed_constraint_with_fk(self):
  2818. constraint = UniqueConstraint(
  2819. fields=["author", "title"],
  2820. name="book_author_title_uniq",
  2821. )
  2822. self._test_composed_constraint_with_fk(constraint)
  2823. @skipUnlessDBFeature(
  2824. "supports_column_check_constraints", "can_introspect_check_constraints"
  2825. )
  2826. def test_composed_check_constraint_with_fk(self):
  2827. constraint = CheckConstraint(check=Q(author__gt=0), name="book_author_check")
  2828. self._test_composed_constraint_with_fk(constraint)
  2829. @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields")
  2830. def test_remove_unique_together_does_not_remove_meta_constraints(self):
  2831. with connection.schema_editor() as editor:
  2832. editor.create_model(AuthorWithUniqueNameAndBirthday)
  2833. self.local_models = [AuthorWithUniqueNameAndBirthday]
  2834. # Add the custom unique constraint
  2835. constraint = UniqueConstraint(
  2836. fields=["name", "birthday"], name="author_name_birthday_uniq"
  2837. )
  2838. custom_constraint_name = constraint.name
  2839. AuthorWithUniqueNameAndBirthday._meta.constraints = [constraint]
  2840. with connection.schema_editor() as editor:
  2841. editor.add_constraint(AuthorWithUniqueNameAndBirthday, constraint)
  2842. # Ensure the constraints exist
  2843. constraints = self.get_constraints(
  2844. AuthorWithUniqueNameAndBirthday._meta.db_table
  2845. )
  2846. self.assertIn(custom_constraint_name, constraints)
  2847. other_constraints = [
  2848. name
  2849. for name, details in constraints.items()
  2850. if details["columns"] == ["name", "birthday"]
  2851. and details["unique"]
  2852. and name != custom_constraint_name
  2853. ]
  2854. self.assertEqual(len(other_constraints), 1)
  2855. # Remove unique together
  2856. unique_together = AuthorWithUniqueNameAndBirthday._meta.unique_together
  2857. with connection.schema_editor() as editor:
  2858. editor.alter_unique_together(
  2859. AuthorWithUniqueNameAndBirthday, unique_together, []
  2860. )
  2861. constraints = self.get_constraints(
  2862. AuthorWithUniqueNameAndBirthday._meta.db_table
  2863. )
  2864. self.assertIn(custom_constraint_name, constraints)
  2865. other_constraints = [
  2866. name
  2867. for name, details in constraints.items()
  2868. if details["columns"] == ["name", "birthday"]
  2869. and details["unique"]
  2870. and name != custom_constraint_name
  2871. ]
  2872. self.assertEqual(len(other_constraints), 0)
  2873. # Re-add unique together
  2874. with connection.schema_editor() as editor:
  2875. editor.alter_unique_together(
  2876. AuthorWithUniqueNameAndBirthday, [], unique_together
  2877. )
  2878. constraints = self.get_constraints(
  2879. AuthorWithUniqueNameAndBirthday._meta.db_table
  2880. )
  2881. self.assertIn(custom_constraint_name, constraints)
  2882. other_constraints = [
  2883. name
  2884. for name, details in constraints.items()
  2885. if details["columns"] == ["name", "birthday"]
  2886. and details["unique"]
  2887. and name != custom_constraint_name
  2888. ]
  2889. self.assertEqual(len(other_constraints), 1)
  2890. # Drop the unique constraint
  2891. with connection.schema_editor() as editor:
  2892. AuthorWithUniqueNameAndBirthday._meta.constraints = []
  2893. editor.remove_constraint(AuthorWithUniqueNameAndBirthday, constraint)
  2894. def test_unique_constraint(self):
  2895. with connection.schema_editor() as editor:
  2896. editor.create_model(Author)
  2897. constraint = UniqueConstraint(fields=["name"], name="name_uq")
  2898. # Add constraint.
  2899. with connection.schema_editor() as editor:
  2900. editor.add_constraint(Author, constraint)
  2901. sql = constraint.create_sql(Author, editor)
  2902. table = Author._meta.db_table
  2903. self.assertIs(sql.references_table(table), True)
  2904. self.assertIs(sql.references_column(table, "name"), True)
  2905. # Remove constraint.
  2906. with connection.schema_editor() as editor:
  2907. editor.remove_constraint(Author, constraint)
  2908. self.assertNotIn(constraint.name, self.get_constraints(table))
  2909. @skipUnlessDBFeature("supports_expression_indexes")
  2910. def test_func_unique_constraint(self):
  2911. with connection.schema_editor() as editor:
  2912. editor.create_model(Author)
  2913. constraint = UniqueConstraint(Upper("name").desc(), name="func_upper_uq")
  2914. # Add constraint.
  2915. with connection.schema_editor() as editor:
  2916. editor.add_constraint(Author, constraint)
  2917. sql = constraint.create_sql(Author, editor)
  2918. table = Author._meta.db_table
  2919. constraints = self.get_constraints(table)
  2920. if connection.features.supports_index_column_ordering:
  2921. self.assertIndexOrder(table, constraint.name, ["DESC"])
  2922. self.assertIn(constraint.name, constraints)
  2923. self.assertIs(constraints[constraint.name]["unique"], True)
  2924. # SQL contains a database function.
  2925. self.assertIs(sql.references_column(table, "name"), True)
  2926. self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql))
  2927. # Remove constraint.
  2928. with connection.schema_editor() as editor:
  2929. editor.remove_constraint(Author, constraint)
  2930. self.assertNotIn(constraint.name, self.get_constraints(table))
  2931. @skipUnlessDBFeature("supports_expression_indexes")
  2932. def test_composite_func_unique_constraint(self):
  2933. with connection.schema_editor() as editor:
  2934. editor.create_model(Author)
  2935. editor.create_model(BookWithSlug)
  2936. constraint = UniqueConstraint(
  2937. Upper("title"),
  2938. Lower("slug"),
  2939. name="func_upper_lower_unq",
  2940. )
  2941. # Add constraint.
  2942. with connection.schema_editor() as editor:
  2943. editor.add_constraint(BookWithSlug, constraint)
  2944. sql = constraint.create_sql(BookWithSlug, editor)
  2945. table = BookWithSlug._meta.db_table
  2946. constraints = self.get_constraints(table)
  2947. self.assertIn(constraint.name, constraints)
  2948. self.assertIs(constraints[constraint.name]["unique"], True)
  2949. # SQL contains database functions.
  2950. self.assertIs(sql.references_column(table, "title"), True)
  2951. self.assertIs(sql.references_column(table, "slug"), True)
  2952. sql = str(sql)
  2953. self.assertIn("UPPER(%s)" % editor.quote_name("title"), sql)
  2954. self.assertIn("LOWER(%s)" % editor.quote_name("slug"), sql)
  2955. self.assertLess(sql.index("UPPER"), sql.index("LOWER"))
  2956. # Remove constraint.
  2957. with connection.schema_editor() as editor:
  2958. editor.remove_constraint(BookWithSlug, constraint)
  2959. self.assertNotIn(constraint.name, self.get_constraints(table))
  2960. @skipUnlessDBFeature("supports_expression_indexes")
  2961. def test_unique_constraint_field_and_expression(self):
  2962. with connection.schema_editor() as editor:
  2963. editor.create_model(Author)
  2964. constraint = UniqueConstraint(
  2965. F("height").desc(),
  2966. "uuid",
  2967. Lower("name").asc(),
  2968. name="func_f_lower_field_unq",
  2969. )
  2970. # Add constraint.
  2971. with connection.schema_editor() as editor:
  2972. editor.add_constraint(Author, constraint)
  2973. sql = constraint.create_sql(Author, editor)
  2974. table = Author._meta.db_table
  2975. if connection.features.supports_index_column_ordering:
  2976. self.assertIndexOrder(table, constraint.name, ["DESC", "ASC", "ASC"])
  2977. constraints = self.get_constraints(table)
  2978. self.assertIs(constraints[constraint.name]["unique"], True)
  2979. self.assertEqual(len(constraints[constraint.name]["columns"]), 3)
  2980. self.assertEqual(constraints[constraint.name]["columns"][1], "uuid")
  2981. # SQL contains database functions and columns.
  2982. self.assertIs(sql.references_column(table, "height"), True)
  2983. self.assertIs(sql.references_column(table, "name"), True)
  2984. self.assertIs(sql.references_column(table, "uuid"), True)
  2985. self.assertIn("LOWER(%s)" % editor.quote_name("name"), str(sql))
  2986. # Remove constraint.
  2987. with connection.schema_editor() as editor:
  2988. editor.remove_constraint(Author, constraint)
  2989. self.assertNotIn(constraint.name, self.get_constraints(table))
  2990. @skipUnlessDBFeature("supports_expression_indexes", "supports_partial_indexes")
  2991. def test_func_unique_constraint_partial(self):
  2992. with connection.schema_editor() as editor:
  2993. editor.create_model(Author)
  2994. constraint = UniqueConstraint(
  2995. Upper("name"),
  2996. name="func_upper_cond_weight_uq",
  2997. condition=Q(weight__isnull=False),
  2998. )
  2999. # Add constraint.
  3000. with connection.schema_editor() as editor:
  3001. editor.add_constraint(Author, constraint)
  3002. sql = constraint.create_sql(Author, editor)
  3003. table = Author._meta.db_table
  3004. constraints = self.get_constraints(table)
  3005. self.assertIn(constraint.name, constraints)
  3006. self.assertIs(constraints[constraint.name]["unique"], True)
  3007. self.assertIs(sql.references_column(table, "name"), True)
  3008. self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql))
  3009. self.assertIn(
  3010. "WHERE %s IS NOT NULL" % editor.quote_name("weight"),
  3011. str(sql),
  3012. )
  3013. # Remove constraint.
  3014. with connection.schema_editor() as editor:
  3015. editor.remove_constraint(Author, constraint)
  3016. self.assertNotIn(constraint.name, self.get_constraints(table))
  3017. @skipUnlessDBFeature("supports_expression_indexes", "supports_covering_indexes")
  3018. def test_func_unique_constraint_covering(self):
  3019. with connection.schema_editor() as editor:
  3020. editor.create_model(Author)
  3021. constraint = UniqueConstraint(
  3022. Upper("name"),
  3023. name="func_upper_covering_uq",
  3024. include=["weight", "height"],
  3025. )
  3026. # Add constraint.
  3027. with connection.schema_editor() as editor:
  3028. editor.add_constraint(Author, constraint)
  3029. sql = constraint.create_sql(Author, editor)
  3030. table = Author._meta.db_table
  3031. constraints = self.get_constraints(table)
  3032. self.assertIn(constraint.name, constraints)
  3033. self.assertIs(constraints[constraint.name]["unique"], True)
  3034. self.assertEqual(
  3035. constraints[constraint.name]["columns"],
  3036. [None, "weight", "height"],
  3037. )
  3038. self.assertIs(sql.references_column(table, "name"), True)
  3039. self.assertIs(sql.references_column(table, "weight"), True)
  3040. self.assertIs(sql.references_column(table, "height"), True)
  3041. self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql))
  3042. self.assertIn(
  3043. "INCLUDE (%s, %s)"
  3044. % (
  3045. editor.quote_name("weight"),
  3046. editor.quote_name("height"),
  3047. ),
  3048. str(sql),
  3049. )
  3050. # Remove constraint.
  3051. with connection.schema_editor() as editor:
  3052. editor.remove_constraint(Author, constraint)
  3053. self.assertNotIn(constraint.name, self.get_constraints(table))
  3054. @skipUnlessDBFeature("supports_expression_indexes")
  3055. def test_func_unique_constraint_lookups(self):
  3056. with connection.schema_editor() as editor:
  3057. editor.create_model(Author)
  3058. with register_lookup(CharField, Lower), register_lookup(IntegerField, Abs):
  3059. constraint = UniqueConstraint(
  3060. F("name__lower"),
  3061. F("weight__abs"),
  3062. name="func_lower_abs_lookup_uq",
  3063. )
  3064. # Add constraint.
  3065. with connection.schema_editor() as editor:
  3066. editor.add_constraint(Author, constraint)
  3067. sql = constraint.create_sql(Author, editor)
  3068. table = Author._meta.db_table
  3069. constraints = self.get_constraints(table)
  3070. self.assertIn(constraint.name, constraints)
  3071. self.assertIs(constraints[constraint.name]["unique"], True)
  3072. # SQL contains columns.
  3073. self.assertIs(sql.references_column(table, "name"), True)
  3074. self.assertIs(sql.references_column(table, "weight"), True)
  3075. # Remove constraint.
  3076. with connection.schema_editor() as editor:
  3077. editor.remove_constraint(Author, constraint)
  3078. self.assertNotIn(constraint.name, self.get_constraints(table))
  3079. @skipUnlessDBFeature("supports_expression_indexes")
  3080. def test_func_unique_constraint_collate(self):
  3081. collation = connection.features.test_collations.get("non_default")
  3082. if not collation:
  3083. self.skipTest("This backend does not support case-insensitive collations.")
  3084. with connection.schema_editor() as editor:
  3085. editor.create_model(Author)
  3086. editor.create_model(BookWithSlug)
  3087. constraint = UniqueConstraint(
  3088. Collate(F("title"), collation=collation).desc(),
  3089. Collate("slug", collation=collation),
  3090. name="func_collate_uq",
  3091. )
  3092. # Add constraint.
  3093. with connection.schema_editor() as editor:
  3094. editor.add_constraint(BookWithSlug, constraint)
  3095. sql = constraint.create_sql(BookWithSlug, editor)
  3096. table = BookWithSlug._meta.db_table
  3097. constraints = self.get_constraints(table)
  3098. self.assertIn(constraint.name, constraints)
  3099. self.assertIs(constraints[constraint.name]["unique"], True)
  3100. if connection.features.supports_index_column_ordering:
  3101. self.assertIndexOrder(table, constraint.name, ["DESC", "ASC"])
  3102. # SQL contains columns and a collation.
  3103. self.assertIs(sql.references_column(table, "title"), True)
  3104. self.assertIs(sql.references_column(table, "slug"), True)
  3105. self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql))
  3106. # Remove constraint.
  3107. with connection.schema_editor() as editor:
  3108. editor.remove_constraint(BookWithSlug, constraint)
  3109. self.assertNotIn(constraint.name, self.get_constraints(table))
  3110. @skipIfDBFeature("supports_expression_indexes")
  3111. def test_func_unique_constraint_unsupported(self):
  3112. # UniqueConstraint is ignored on databases that don't support indexes on
  3113. # expressions.
  3114. with connection.schema_editor() as editor:
  3115. editor.create_model(Author)
  3116. constraint = UniqueConstraint(F("name"), name="func_name_uq")
  3117. with connection.schema_editor() as editor, self.assertNumQueries(0):
  3118. self.assertIsNone(editor.add_constraint(Author, constraint))
  3119. self.assertIsNone(editor.remove_constraint(Author, constraint))
  3120. @skipUnlessDBFeature("supports_expression_indexes")
  3121. def test_func_unique_constraint_nonexistent_field(self):
  3122. constraint = UniqueConstraint(Lower("nonexistent"), name="func_nonexistent_uq")
  3123. msg = (
  3124. "Cannot resolve keyword 'nonexistent' into field. Choices are: "
  3125. "height, id, name, uuid, weight"
  3126. )
  3127. with self.assertRaisesMessage(FieldError, msg):
  3128. with connection.schema_editor() as editor:
  3129. editor.add_constraint(Author, constraint)
  3130. @skipUnlessDBFeature("supports_expression_indexes")
  3131. def test_func_unique_constraint_nondeterministic(self):
  3132. with connection.schema_editor() as editor:
  3133. editor.create_model(Author)
  3134. constraint = UniqueConstraint(Random(), name="func_random_uq")
  3135. with connection.schema_editor() as editor:
  3136. with self.assertRaises(DatabaseError):
  3137. editor.add_constraint(Author, constraint)
  3138. @skipUnlessDBFeature("supports_nulls_distinct_unique_constraints")
  3139. def test_unique_constraint_nulls_distinct(self):
  3140. with connection.schema_editor() as editor:
  3141. editor.create_model(Author)
  3142. nulls_distinct = UniqueConstraint(
  3143. F("height"), name="distinct_height", nulls_distinct=True
  3144. )
  3145. nulls_not_distinct = UniqueConstraint(
  3146. F("weight"), name="not_distinct_weight", nulls_distinct=False
  3147. )
  3148. with connection.schema_editor() as editor:
  3149. editor.add_constraint(Author, nulls_distinct)
  3150. editor.add_constraint(Author, nulls_not_distinct)
  3151. Author.objects.create(name="", height=None, weight=None)
  3152. Author.objects.create(name="", height=None, weight=1)
  3153. with self.assertRaises(IntegrityError):
  3154. Author.objects.create(name="", height=1, weight=None)
  3155. with connection.schema_editor() as editor:
  3156. editor.remove_constraint(Author, nulls_distinct)
  3157. editor.remove_constraint(Author, nulls_not_distinct)
  3158. constraints = self.get_constraints(Author._meta.db_table)
  3159. self.assertNotIn(nulls_distinct.name, constraints)
  3160. self.assertNotIn(nulls_not_distinct.name, constraints)
  3161. @skipIfDBFeature("supports_nulls_distinct_unique_constraints")
  3162. def test_unique_constraint_nulls_distinct_unsupported(self):
  3163. # UniqueConstraint is ignored on databases that don't support
  3164. # NULLS [NOT] DISTINCT.
  3165. with connection.schema_editor() as editor:
  3166. editor.create_model(Author)
  3167. constraint = UniqueConstraint(
  3168. F("name"), name="func_name_uq", nulls_distinct=True
  3169. )
  3170. with connection.schema_editor() as editor, self.assertNumQueries(0):
  3171. self.assertIsNone(editor.add_constraint(Author, constraint))
  3172. self.assertIsNone(editor.remove_constraint(Author, constraint))
  3173. def test_index_together(self):
  3174. """
  3175. Tests removing and adding index_together constraints on a model.
  3176. """
  3177. # Create the table
  3178. with connection.schema_editor() as editor:
  3179. editor.create_model(Tag)
  3180. # Ensure there's no index on the year/slug columns first
  3181. self.assertIs(
  3182. any(
  3183. c["index"]
  3184. for c in self.get_constraints("schema_tag").values()
  3185. if c["columns"] == ["slug", "title"]
  3186. ),
  3187. False,
  3188. )
  3189. # Alter the model to add an index
  3190. with connection.schema_editor() as editor:
  3191. editor.alter_index_together(Tag, [], [("slug", "title")])
  3192. # Ensure there is now an index
  3193. self.assertIs(
  3194. any(
  3195. c["index"]
  3196. for c in self.get_constraints("schema_tag").values()
  3197. if c["columns"] == ["slug", "title"]
  3198. ),
  3199. True,
  3200. )
  3201. # Alter it back
  3202. new_field2 = SlugField(unique=True)
  3203. new_field2.set_attributes_from_name("slug")
  3204. with connection.schema_editor() as editor:
  3205. editor.alter_index_together(Tag, [("slug", "title")], [])
  3206. # Ensure there's no index
  3207. self.assertIs(
  3208. any(
  3209. c["index"]
  3210. for c in self.get_constraints("schema_tag").values()
  3211. if c["columns"] == ["slug", "title"]
  3212. ),
  3213. False,
  3214. )
  3215. @isolate_apps("schema")
  3216. def test_db_table(self):
  3217. """
  3218. Tests renaming of the table
  3219. """
  3220. class Author(Model):
  3221. name = CharField(max_length=255)
  3222. class Meta:
  3223. app_label = "schema"
  3224. class Book(Model):
  3225. author = ForeignKey(Author, CASCADE)
  3226. class Meta:
  3227. app_label = "schema"
  3228. # Create the table and one referring it.
  3229. with connection.schema_editor() as editor:
  3230. editor.create_model(Author)
  3231. editor.create_model(Book)
  3232. # Ensure the table is there to begin with
  3233. columns = self.column_classes(Author)
  3234. self.assertEqual(
  3235. columns["name"][0],
  3236. connection.features.introspected_field_types["CharField"],
  3237. )
  3238. # Alter the table
  3239. with connection.schema_editor() as editor:
  3240. editor.alter_db_table(Author, "schema_author", "schema_otherauthor")
  3241. Author._meta.db_table = "schema_otherauthor"
  3242. columns = self.column_classes(Author)
  3243. self.assertEqual(
  3244. columns["name"][0],
  3245. connection.features.introspected_field_types["CharField"],
  3246. )
  3247. # Ensure the foreign key reference was updated
  3248. self.assertForeignKeyExists(Book, "author_id", "schema_otherauthor")
  3249. # Alter the table again
  3250. with connection.schema_editor() as editor:
  3251. editor.alter_db_table(Author, "schema_otherauthor", "schema_author")
  3252. # Ensure the table is still there
  3253. Author._meta.db_table = "schema_author"
  3254. columns = self.column_classes(Author)
  3255. self.assertEqual(
  3256. columns["name"][0],
  3257. connection.features.introspected_field_types["CharField"],
  3258. )
  3259. def test_add_remove_index(self):
  3260. """
  3261. Tests index addition and removal
  3262. """
  3263. # Create the table
  3264. with connection.schema_editor() as editor:
  3265. editor.create_model(Author)
  3266. # Ensure the table is there and has no index
  3267. self.assertNotIn("title", self.get_indexes(Author._meta.db_table))
  3268. # Add the index
  3269. index = Index(fields=["name"], name="author_title_idx")
  3270. with connection.schema_editor() as editor:
  3271. editor.add_index(Author, index)
  3272. self.assertIn("name", self.get_indexes(Author._meta.db_table))
  3273. # Drop the index
  3274. with connection.schema_editor() as editor:
  3275. editor.remove_index(Author, index)
  3276. self.assertNotIn("name", self.get_indexes(Author._meta.db_table))
  3277. def test_remove_db_index_doesnt_remove_custom_indexes(self):
  3278. """
  3279. Changing db_index to False doesn't remove indexes from Meta.indexes.
  3280. """
  3281. with connection.schema_editor() as editor:
  3282. editor.create_model(AuthorWithIndexedName)
  3283. self.local_models = [AuthorWithIndexedName]
  3284. # Ensure the table has its index
  3285. self.assertIn("name", self.get_indexes(AuthorWithIndexedName._meta.db_table))
  3286. # Add the custom index
  3287. index = Index(fields=["-name"], name="author_name_idx")
  3288. author_index_name = index.name
  3289. with connection.schema_editor() as editor:
  3290. db_index_name = editor._create_index_name(
  3291. table_name=AuthorWithIndexedName._meta.db_table,
  3292. column_names=("name",),
  3293. )
  3294. try:
  3295. AuthorWithIndexedName._meta.indexes = [index]
  3296. with connection.schema_editor() as editor:
  3297. editor.add_index(AuthorWithIndexedName, index)
  3298. old_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table)
  3299. self.assertIn(author_index_name, old_constraints)
  3300. self.assertIn(db_index_name, old_constraints)
  3301. # Change name field to db_index=False
  3302. old_field = AuthorWithIndexedName._meta.get_field("name")
  3303. new_field = CharField(max_length=255)
  3304. new_field.set_attributes_from_name("name")
  3305. with connection.schema_editor() as editor:
  3306. editor.alter_field(
  3307. AuthorWithIndexedName, old_field, new_field, strict=True
  3308. )
  3309. new_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table)
  3310. self.assertNotIn(db_index_name, new_constraints)
  3311. # The index from Meta.indexes is still in the database.
  3312. self.assertIn(author_index_name, new_constraints)
  3313. # Drop the index
  3314. with connection.schema_editor() as editor:
  3315. editor.remove_index(AuthorWithIndexedName, index)
  3316. finally:
  3317. AuthorWithIndexedName._meta.indexes = []
  3318. def test_order_index(self):
  3319. """
  3320. Indexes defined with ordering (ASC/DESC) defined on column
  3321. """
  3322. with connection.schema_editor() as editor:
  3323. editor.create_model(Author)
  3324. # The table doesn't have an index
  3325. self.assertNotIn("title", self.get_indexes(Author._meta.db_table))
  3326. index_name = "author_name_idx"
  3327. # Add the index
  3328. index = Index(fields=["name", "-weight"], name=index_name)
  3329. with connection.schema_editor() as editor:
  3330. editor.add_index(Author, index)
  3331. if connection.features.supports_index_column_ordering:
  3332. self.assertIndexOrder(Author._meta.db_table, index_name, ["ASC", "DESC"])
  3333. # Drop the index
  3334. with connection.schema_editor() as editor:
  3335. editor.remove_index(Author, index)
  3336. def test_indexes(self):
  3337. """
  3338. Tests creation/altering of indexes
  3339. """
  3340. # Create the table
  3341. with connection.schema_editor() as editor:
  3342. editor.create_model(Author)
  3343. editor.create_model(Book)
  3344. # Ensure the table is there and has the right index
  3345. self.assertIn(
  3346. "title",
  3347. self.get_indexes(Book._meta.db_table),
  3348. )
  3349. # Alter to remove the index
  3350. old_field = Book._meta.get_field("title")
  3351. new_field = CharField(max_length=100, db_index=False)
  3352. new_field.set_attributes_from_name("title")
  3353. with connection.schema_editor() as editor:
  3354. editor.alter_field(Book, old_field, new_field, strict=True)
  3355. # Ensure the table is there and has no index
  3356. self.assertNotIn(
  3357. "title",
  3358. self.get_indexes(Book._meta.db_table),
  3359. )
  3360. # Alter to re-add the index
  3361. new_field2 = Book._meta.get_field("title")
  3362. with connection.schema_editor() as editor:
  3363. editor.alter_field(Book, new_field, new_field2, strict=True)
  3364. # Ensure the table is there and has the index again
  3365. self.assertIn(
  3366. "title",
  3367. self.get_indexes(Book._meta.db_table),
  3368. )
  3369. # Add a unique column, verify that creates an implicit index
  3370. new_field3 = BookWithSlug._meta.get_field("slug")
  3371. with connection.schema_editor() as editor:
  3372. editor.add_field(Book, new_field3)
  3373. self.assertIn(
  3374. "slug",
  3375. self.get_uniques(Book._meta.db_table),
  3376. )
  3377. # Remove the unique, check the index goes with it
  3378. new_field4 = CharField(max_length=20, unique=False)
  3379. new_field4.set_attributes_from_name("slug")
  3380. with connection.schema_editor() as editor:
  3381. editor.alter_field(BookWithSlug, new_field3, new_field4, strict=True)
  3382. self.assertNotIn(
  3383. "slug",
  3384. self.get_uniques(Book._meta.db_table),
  3385. )
  3386. def test_text_field_with_db_index(self):
  3387. with connection.schema_editor() as editor:
  3388. editor.create_model(AuthorTextFieldWithIndex)
  3389. # The text_field index is present if the database supports it.
  3390. assertion = (
  3391. self.assertIn
  3392. if connection.features.supports_index_on_text_field
  3393. else self.assertNotIn
  3394. )
  3395. assertion(
  3396. "text_field", self.get_indexes(AuthorTextFieldWithIndex._meta.db_table)
  3397. )
  3398. def _index_expressions_wrappers(self):
  3399. index_expression = IndexExpression()
  3400. index_expression.set_wrapper_classes(connection)
  3401. return ", ".join(
  3402. [
  3403. wrapper_cls.__qualname__
  3404. for wrapper_cls in index_expression.wrapper_classes
  3405. ]
  3406. )
  3407. @skipUnlessDBFeature("supports_expression_indexes")
  3408. def test_func_index_multiple_wrapper_references(self):
  3409. index = Index(OrderBy(F("name").desc(), descending=True), name="name")
  3410. msg = (
  3411. "Multiple references to %s can't be used in an indexed expression."
  3412. % self._index_expressions_wrappers()
  3413. )
  3414. with connection.schema_editor() as editor:
  3415. with self.assertRaisesMessage(ValueError, msg):
  3416. editor.add_index(Author, index)
  3417. @skipUnlessDBFeature("supports_expression_indexes")
  3418. def test_func_index_invalid_topmost_expressions(self):
  3419. index = Index(Upper(F("name").desc()), name="name")
  3420. msg = (
  3421. "%s must be topmost expressions in an indexed expression."
  3422. % self._index_expressions_wrappers()
  3423. )
  3424. with connection.schema_editor() as editor:
  3425. with self.assertRaisesMessage(ValueError, msg):
  3426. editor.add_index(Author, index)
  3427. @skipUnlessDBFeature("supports_expression_indexes")
  3428. def test_func_index(self):
  3429. with connection.schema_editor() as editor:
  3430. editor.create_model(Author)
  3431. index = Index(Lower("name").desc(), name="func_lower_idx")
  3432. # Add index.
  3433. with connection.schema_editor() as editor:
  3434. editor.add_index(Author, index)
  3435. sql = index.create_sql(Author, editor)
  3436. table = Author._meta.db_table
  3437. if connection.features.supports_index_column_ordering:
  3438. self.assertIndexOrder(table, index.name, ["DESC"])
  3439. # SQL contains a database function.
  3440. self.assertIs(sql.references_column(table, "name"), True)
  3441. self.assertIn("LOWER(%s)" % editor.quote_name("name"), str(sql))
  3442. # Remove index.
  3443. with connection.schema_editor() as editor:
  3444. editor.remove_index(Author, index)
  3445. self.assertNotIn(index.name, self.get_constraints(table))
  3446. @skipUnlessDBFeature("supports_expression_indexes")
  3447. def test_func_index_f(self):
  3448. with connection.schema_editor() as editor:
  3449. editor.create_model(Tag)
  3450. index = Index("slug", F("title").desc(), name="func_f_idx")
  3451. # Add index.
  3452. with connection.schema_editor() as editor:
  3453. editor.add_index(Tag, index)
  3454. sql = index.create_sql(Tag, editor)
  3455. table = Tag._meta.db_table
  3456. self.assertIn(index.name, self.get_constraints(table))
  3457. if connection.features.supports_index_column_ordering:
  3458. self.assertIndexOrder(Tag._meta.db_table, index.name, ["ASC", "DESC"])
  3459. # SQL contains columns.
  3460. self.assertIs(sql.references_column(table, "slug"), True)
  3461. self.assertIs(sql.references_column(table, "title"), True)
  3462. # Remove index.
  3463. with connection.schema_editor() as editor:
  3464. editor.remove_index(Tag, index)
  3465. self.assertNotIn(index.name, self.get_constraints(table))
  3466. @skipUnlessDBFeature("supports_expression_indexes")
  3467. def test_func_index_lookups(self):
  3468. with connection.schema_editor() as editor:
  3469. editor.create_model(Author)
  3470. with register_lookup(CharField, Lower), register_lookup(IntegerField, Abs):
  3471. index = Index(
  3472. F("name__lower"),
  3473. F("weight__abs"),
  3474. name="func_lower_abs_lookup_idx",
  3475. )
  3476. # Add index.
  3477. with connection.schema_editor() as editor:
  3478. editor.add_index(Author, index)
  3479. sql = index.create_sql(Author, editor)
  3480. table = Author._meta.db_table
  3481. self.assertIn(index.name, self.get_constraints(table))
  3482. # SQL contains columns.
  3483. self.assertIs(sql.references_column(table, "name"), True)
  3484. self.assertIs(sql.references_column(table, "weight"), True)
  3485. # Remove index.
  3486. with connection.schema_editor() as editor:
  3487. editor.remove_index(Author, index)
  3488. self.assertNotIn(index.name, self.get_constraints(table))
  3489. @skipUnlessDBFeature("supports_expression_indexes")
  3490. def test_composite_func_index(self):
  3491. with connection.schema_editor() as editor:
  3492. editor.create_model(Author)
  3493. index = Index(Lower("name"), Upper("name"), name="func_lower_upper_idx")
  3494. # Add index.
  3495. with connection.schema_editor() as editor:
  3496. editor.add_index(Author, index)
  3497. sql = index.create_sql(Author, editor)
  3498. table = Author._meta.db_table
  3499. self.assertIn(index.name, self.get_constraints(table))
  3500. # SQL contains database functions.
  3501. self.assertIs(sql.references_column(table, "name"), True)
  3502. sql = str(sql)
  3503. self.assertIn("LOWER(%s)" % editor.quote_name("name"), sql)
  3504. self.assertIn("UPPER(%s)" % editor.quote_name("name"), sql)
  3505. self.assertLess(sql.index("LOWER"), sql.index("UPPER"))
  3506. # Remove index.
  3507. with connection.schema_editor() as editor:
  3508. editor.remove_index(Author, index)
  3509. self.assertNotIn(index.name, self.get_constraints(table))
  3510. @skipUnlessDBFeature("supports_expression_indexes")
  3511. def test_composite_func_index_field_and_expression(self):
  3512. with connection.schema_editor() as editor:
  3513. editor.create_model(Author)
  3514. editor.create_model(Book)
  3515. index = Index(
  3516. F("author").desc(),
  3517. Lower("title").asc(),
  3518. "pub_date",
  3519. name="func_f_lower_field_idx",
  3520. )
  3521. # Add index.
  3522. with connection.schema_editor() as editor:
  3523. editor.add_index(Book, index)
  3524. sql = index.create_sql(Book, editor)
  3525. table = Book._meta.db_table
  3526. constraints = self.get_constraints(table)
  3527. if connection.features.supports_index_column_ordering:
  3528. self.assertIndexOrder(table, index.name, ["DESC", "ASC", "ASC"])
  3529. self.assertEqual(len(constraints[index.name]["columns"]), 3)
  3530. self.assertEqual(constraints[index.name]["columns"][2], "pub_date")
  3531. # SQL contains database functions and columns.
  3532. self.assertIs(sql.references_column(table, "author_id"), True)
  3533. self.assertIs(sql.references_column(table, "title"), True)
  3534. self.assertIs(sql.references_column(table, "pub_date"), True)
  3535. self.assertIn("LOWER(%s)" % editor.quote_name("title"), str(sql))
  3536. # Remove index.
  3537. with connection.schema_editor() as editor:
  3538. editor.remove_index(Book, index)
  3539. self.assertNotIn(index.name, self.get_constraints(table))
  3540. @skipUnlessDBFeature("supports_expression_indexes")
  3541. @isolate_apps("schema")
  3542. def test_func_index_f_decimalfield(self):
  3543. class Node(Model):
  3544. value = DecimalField(max_digits=5, decimal_places=2)
  3545. class Meta:
  3546. app_label = "schema"
  3547. with connection.schema_editor() as editor:
  3548. editor.create_model(Node)
  3549. index = Index(F("value"), name="func_f_decimalfield_idx")
  3550. # Add index.
  3551. with connection.schema_editor() as editor:
  3552. editor.add_index(Node, index)
  3553. sql = index.create_sql(Node, editor)
  3554. table = Node._meta.db_table
  3555. self.assertIn(index.name, self.get_constraints(table))
  3556. self.assertIs(sql.references_column(table, "value"), True)
  3557. # SQL doesn't contain casting.
  3558. self.assertNotIn("CAST", str(sql))
  3559. # Remove index.
  3560. with connection.schema_editor() as editor:
  3561. editor.remove_index(Node, index)
  3562. self.assertNotIn(index.name, self.get_constraints(table))
  3563. @skipUnlessDBFeature("supports_expression_indexes")
  3564. def test_func_index_cast(self):
  3565. with connection.schema_editor() as editor:
  3566. editor.create_model(Author)
  3567. index = Index(Cast("weight", FloatField()), name="func_cast_idx")
  3568. # Add index.
  3569. with connection.schema_editor() as editor:
  3570. editor.add_index(Author, index)
  3571. sql = index.create_sql(Author, editor)
  3572. table = Author._meta.db_table
  3573. self.assertIn(index.name, self.get_constraints(table))
  3574. self.assertIs(sql.references_column(table, "weight"), True)
  3575. # Remove index.
  3576. with connection.schema_editor() as editor:
  3577. editor.remove_index(Author, index)
  3578. self.assertNotIn(index.name, self.get_constraints(table))
  3579. @skipUnlessDBFeature("supports_expression_indexes")
  3580. def test_func_index_collate(self):
  3581. collation = connection.features.test_collations.get("non_default")
  3582. if not collation:
  3583. self.skipTest("This backend does not support case-insensitive collations.")
  3584. with connection.schema_editor() as editor:
  3585. editor.create_model(Author)
  3586. editor.create_model(BookWithSlug)
  3587. index = Index(
  3588. Collate(F("title"), collation=collation).desc(),
  3589. Collate("slug", collation=collation),
  3590. name="func_collate_idx",
  3591. )
  3592. # Add index.
  3593. with connection.schema_editor() as editor:
  3594. editor.add_index(BookWithSlug, index)
  3595. sql = index.create_sql(BookWithSlug, editor)
  3596. table = Book._meta.db_table
  3597. self.assertIn(index.name, self.get_constraints(table))
  3598. if connection.features.supports_index_column_ordering:
  3599. self.assertIndexOrder(table, index.name, ["DESC", "ASC"])
  3600. # SQL contains columns and a collation.
  3601. self.assertIs(sql.references_column(table, "title"), True)
  3602. self.assertIs(sql.references_column(table, "slug"), True)
  3603. self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql))
  3604. # Remove index.
  3605. with connection.schema_editor() as editor:
  3606. editor.remove_index(Book, index)
  3607. self.assertNotIn(index.name, self.get_constraints(table))
  3608. @skipUnlessDBFeature("supports_expression_indexes")
  3609. @skipIfDBFeature("collate_as_index_expression")
  3610. def test_func_index_collate_f_ordered(self):
  3611. collation = connection.features.test_collations.get("non_default")
  3612. if not collation:
  3613. self.skipTest("This backend does not support case-insensitive collations.")
  3614. with connection.schema_editor() as editor:
  3615. editor.create_model(Author)
  3616. index = Index(
  3617. Collate(F("name").desc(), collation=collation),
  3618. name="func_collate_f_desc_idx",
  3619. )
  3620. # Add index.
  3621. with connection.schema_editor() as editor:
  3622. editor.add_index(Author, index)
  3623. sql = index.create_sql(Author, editor)
  3624. table = Author._meta.db_table
  3625. self.assertIn(index.name, self.get_constraints(table))
  3626. if connection.features.supports_index_column_ordering:
  3627. self.assertIndexOrder(table, index.name, ["DESC"])
  3628. # SQL contains columns and a collation.
  3629. self.assertIs(sql.references_column(table, "name"), True)
  3630. self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql))
  3631. # Remove index.
  3632. with connection.schema_editor() as editor:
  3633. editor.remove_index(Author, index)
  3634. self.assertNotIn(index.name, self.get_constraints(table))
  3635. @skipUnlessDBFeature("supports_expression_indexes")
  3636. def test_func_index_calc(self):
  3637. with connection.schema_editor() as editor:
  3638. editor.create_model(Author)
  3639. index = Index(F("height") / (F("weight") + Value(5)), name="func_calc_idx")
  3640. # Add index.
  3641. with connection.schema_editor() as editor:
  3642. editor.add_index(Author, index)
  3643. sql = index.create_sql(Author, editor)
  3644. table = Author._meta.db_table
  3645. self.assertIn(index.name, self.get_constraints(table))
  3646. # SQL contains columns and expressions.
  3647. self.assertIs(sql.references_column(table, "height"), True)
  3648. self.assertIs(sql.references_column(table, "weight"), True)
  3649. sql = str(sql)
  3650. self.assertIs(
  3651. sql.index(editor.quote_name("height"))
  3652. < sql.index("/")
  3653. < sql.index(editor.quote_name("weight"))
  3654. < sql.index("+")
  3655. < sql.index("5"),
  3656. True,
  3657. )
  3658. # Remove index.
  3659. with connection.schema_editor() as editor:
  3660. editor.remove_index(Author, index)
  3661. self.assertNotIn(index.name, self.get_constraints(table))
  3662. @skipUnlessDBFeature("supports_expression_indexes", "supports_json_field")
  3663. @isolate_apps("schema")
  3664. def test_func_index_json_key_transform(self):
  3665. class JSONModel(Model):
  3666. field = JSONField()
  3667. class Meta:
  3668. app_label = "schema"
  3669. with connection.schema_editor() as editor:
  3670. editor.create_model(JSONModel)
  3671. self.isolated_local_models = [JSONModel]
  3672. index = Index("field__some_key", name="func_json_key_idx")
  3673. with connection.schema_editor() as editor:
  3674. editor.add_index(JSONModel, index)
  3675. sql = index.create_sql(JSONModel, editor)
  3676. table = JSONModel._meta.db_table
  3677. self.assertIn(index.name, self.get_constraints(table))
  3678. self.assertIs(sql.references_column(table, "field"), True)
  3679. with connection.schema_editor() as editor:
  3680. editor.remove_index(JSONModel, index)
  3681. self.assertNotIn(index.name, self.get_constraints(table))
  3682. @skipUnlessDBFeature("supports_expression_indexes", "supports_json_field")
  3683. @isolate_apps("schema")
  3684. def test_func_index_json_key_transform_cast(self):
  3685. class JSONModel(Model):
  3686. field = JSONField()
  3687. class Meta:
  3688. app_label = "schema"
  3689. with connection.schema_editor() as editor:
  3690. editor.create_model(JSONModel)
  3691. self.isolated_local_models = [JSONModel]
  3692. index = Index(
  3693. Cast(KeyTextTransform("some_key", "field"), IntegerField()),
  3694. name="func_json_key_cast_idx",
  3695. )
  3696. with connection.schema_editor() as editor:
  3697. editor.add_index(JSONModel, index)
  3698. sql = index.create_sql(JSONModel, editor)
  3699. table = JSONModel._meta.db_table
  3700. self.assertIn(index.name, self.get_constraints(table))
  3701. self.assertIs(sql.references_column(table, "field"), True)
  3702. with connection.schema_editor() as editor:
  3703. editor.remove_index(JSONModel, index)
  3704. self.assertNotIn(index.name, self.get_constraints(table))
  3705. @skipIfDBFeature("supports_expression_indexes")
  3706. def test_func_index_unsupported(self):
  3707. # Index is ignored on databases that don't support indexes on
  3708. # expressions.
  3709. with connection.schema_editor() as editor:
  3710. editor.create_model(Author)
  3711. index = Index(F("name"), name="random_idx")
  3712. with connection.schema_editor() as editor, self.assertNumQueries(0):
  3713. self.assertIsNone(editor.add_index(Author, index))
  3714. self.assertIsNone(editor.remove_index(Author, index))
  3715. @skipUnlessDBFeature("supports_expression_indexes")
  3716. def test_func_index_nonexistent_field(self):
  3717. index = Index(Lower("nonexistent"), name="func_nonexistent_idx")
  3718. msg = (
  3719. "Cannot resolve keyword 'nonexistent' into field. Choices are: "
  3720. "height, id, name, uuid, weight"
  3721. )
  3722. with self.assertRaisesMessage(FieldError, msg):
  3723. with connection.schema_editor() as editor:
  3724. editor.add_index(Author, index)
  3725. @skipUnlessDBFeature("supports_expression_indexes")
  3726. def test_func_index_nondeterministic(self):
  3727. with connection.schema_editor() as editor:
  3728. editor.create_model(Author)
  3729. index = Index(Random(), name="func_random_idx")
  3730. with connection.schema_editor() as editor:
  3731. with self.assertRaises(DatabaseError):
  3732. editor.add_index(Author, index)
  3733. def test_primary_key(self):
  3734. """
  3735. Tests altering of the primary key
  3736. """
  3737. # Create the table
  3738. with connection.schema_editor() as editor:
  3739. editor.create_model(Tag)
  3740. # Ensure the table is there and has the right PK
  3741. self.assertEqual(self.get_primary_key(Tag._meta.db_table), "id")
  3742. # Alter to change the PK
  3743. id_field = Tag._meta.get_field("id")
  3744. old_field = Tag._meta.get_field("slug")
  3745. new_field = SlugField(primary_key=True)
  3746. new_field.set_attributes_from_name("slug")
  3747. new_field.model = Tag
  3748. with connection.schema_editor() as editor:
  3749. editor.remove_field(Tag, id_field)
  3750. editor.alter_field(Tag, old_field, new_field)
  3751. # Ensure the PK changed
  3752. self.assertNotIn(
  3753. "id",
  3754. self.get_indexes(Tag._meta.db_table),
  3755. )
  3756. self.assertEqual(self.get_primary_key(Tag._meta.db_table), "slug")
  3757. def test_alter_primary_key_the_same_name(self):
  3758. with connection.schema_editor() as editor:
  3759. editor.create_model(Thing)
  3760. old_field = Thing._meta.get_field("when")
  3761. new_field = CharField(max_length=2, primary_key=True)
  3762. new_field.set_attributes_from_name("when")
  3763. new_field.model = Thing
  3764. with connection.schema_editor() as editor:
  3765. editor.alter_field(Thing, old_field, new_field, strict=True)
  3766. self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when")
  3767. with connection.schema_editor() as editor:
  3768. editor.alter_field(Thing, new_field, old_field, strict=True)
  3769. self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when")
  3770. def test_context_manager_exit(self):
  3771. """
  3772. Ensures transaction is correctly closed when an error occurs
  3773. inside a SchemaEditor context.
  3774. """
  3775. class SomeError(Exception):
  3776. pass
  3777. try:
  3778. with connection.schema_editor():
  3779. raise SomeError
  3780. except SomeError:
  3781. self.assertFalse(connection.in_atomic_block)
  3782. @skipIfDBFeature("can_rollback_ddl")
  3783. def test_unsupported_transactional_ddl_disallowed(self):
  3784. message = (
  3785. "Executing DDL statements while in a transaction on databases "
  3786. "that can't perform a rollback is prohibited."
  3787. )
  3788. with atomic(), connection.schema_editor() as editor:
  3789. with self.assertRaisesMessage(TransactionManagementError, message):
  3790. editor.execute(
  3791. editor.sql_create_table % {"table": "foo", "definition": ""}
  3792. )
  3793. @skipUnlessDBFeature("supports_foreign_keys", "indexes_foreign_keys")
  3794. def test_foreign_key_index_long_names_regression(self):
  3795. """
  3796. Regression test for #21497.
  3797. Only affects databases that supports foreign keys.
  3798. """
  3799. # Create the table
  3800. with connection.schema_editor() as editor:
  3801. editor.create_model(AuthorWithEvenLongerName)
  3802. editor.create_model(BookWithLongName)
  3803. # Find the properly shortened column name
  3804. column_name = connection.ops.quote_name(
  3805. "author_foreign_key_with_really_long_field_name_id"
  3806. )
  3807. column_name = column_name[1:-1].lower() # unquote, and, for Oracle, un-upcase
  3808. # Ensure the table is there and has an index on the column
  3809. self.assertIn(
  3810. column_name,
  3811. self.get_indexes(BookWithLongName._meta.db_table),
  3812. )
  3813. @skipUnlessDBFeature("supports_foreign_keys")
  3814. def test_add_foreign_key_long_names(self):
  3815. """
  3816. Regression test for #23009.
  3817. Only affects databases that supports foreign keys.
  3818. """
  3819. # Create the initial tables
  3820. with connection.schema_editor() as editor:
  3821. editor.create_model(AuthorWithEvenLongerName)
  3822. editor.create_model(BookWithLongName)
  3823. # Add a second FK, this would fail due to long ref name before the fix
  3824. new_field = ForeignKey(
  3825. AuthorWithEvenLongerName, CASCADE, related_name="something"
  3826. )
  3827. new_field.set_attributes_from_name(
  3828. "author_other_really_long_named_i_mean_so_long_fk"
  3829. )
  3830. with connection.schema_editor() as editor:
  3831. editor.add_field(BookWithLongName, new_field)
  3832. @isolate_apps("schema")
  3833. @skipUnlessDBFeature("supports_foreign_keys")
  3834. def test_add_foreign_key_quoted_db_table(self):
  3835. class Author(Model):
  3836. class Meta:
  3837. db_table = '"table_author_double_quoted"'
  3838. app_label = "schema"
  3839. class Book(Model):
  3840. author = ForeignKey(Author, CASCADE)
  3841. class Meta:
  3842. app_label = "schema"
  3843. with connection.schema_editor() as editor:
  3844. editor.create_model(Author)
  3845. editor.create_model(Book)
  3846. self.isolated_local_models = [Author]
  3847. if connection.vendor == "mysql":
  3848. self.assertForeignKeyExists(
  3849. Book, "author_id", '"table_author_double_quoted"'
  3850. )
  3851. else:
  3852. self.assertForeignKeyExists(Book, "author_id", "table_author_double_quoted")
  3853. def test_add_foreign_object(self):
  3854. with connection.schema_editor() as editor:
  3855. editor.create_model(BookForeignObj)
  3856. self.local_models = [BookForeignObj]
  3857. new_field = ForeignObject(
  3858. Author, on_delete=CASCADE, from_fields=["author_id"], to_fields=["id"]
  3859. )
  3860. new_field.set_attributes_from_name("author")
  3861. with connection.schema_editor() as editor:
  3862. editor.add_field(BookForeignObj, new_field)
  3863. def test_creation_deletion_reserved_names(self):
  3864. """
  3865. Tries creating a model's table, and then deleting it when it has a
  3866. SQL reserved name.
  3867. """
  3868. # Create the table
  3869. with connection.schema_editor() as editor:
  3870. try:
  3871. editor.create_model(Thing)
  3872. except OperationalError as e:
  3873. self.fail(
  3874. "Errors when applying initial migration for a model "
  3875. "with a table named after an SQL reserved word: %s" % e
  3876. )
  3877. # The table is there
  3878. list(Thing.objects.all())
  3879. # Clean up that table
  3880. with connection.schema_editor() as editor:
  3881. editor.delete_model(Thing)
  3882. # The table is gone
  3883. with self.assertRaises(DatabaseError):
  3884. list(Thing.objects.all())
  3885. def test_remove_constraints_capital_letters(self):
  3886. """
  3887. #23065 - Constraint names must be quoted if they contain capital letters.
  3888. """
  3889. def get_field(*args, field_class=IntegerField, **kwargs):
  3890. kwargs["db_column"] = "CamelCase"
  3891. field = field_class(*args, **kwargs)
  3892. field.set_attributes_from_name("CamelCase")
  3893. return field
  3894. model = Author
  3895. field = get_field()
  3896. table = model._meta.db_table
  3897. column = field.column
  3898. identifier_converter = connection.introspection.identifier_converter
  3899. with connection.schema_editor() as editor:
  3900. editor.create_model(model)
  3901. editor.add_field(model, field)
  3902. constraint_name = "CamelCaseIndex"
  3903. expected_constraint_name = identifier_converter(constraint_name)
  3904. editor.execute(
  3905. editor.sql_create_index
  3906. % {
  3907. "table": editor.quote_name(table),
  3908. "name": editor.quote_name(constraint_name),
  3909. "using": "",
  3910. "columns": editor.quote_name(column),
  3911. "extra": "",
  3912. "condition": "",
  3913. "include": "",
  3914. }
  3915. )
  3916. self.assertIn(
  3917. expected_constraint_name, self.get_constraints(model._meta.db_table)
  3918. )
  3919. editor.alter_field(model, get_field(db_index=True), field, strict=True)
  3920. self.assertNotIn(
  3921. expected_constraint_name, self.get_constraints(model._meta.db_table)
  3922. )
  3923. constraint_name = "CamelCaseUniqConstraint"
  3924. expected_constraint_name = identifier_converter(constraint_name)
  3925. editor.execute(editor._create_unique_sql(model, [field], constraint_name))
  3926. self.assertIn(
  3927. expected_constraint_name, self.get_constraints(model._meta.db_table)
  3928. )
  3929. editor.alter_field(model, get_field(unique=True), field, strict=True)
  3930. self.assertNotIn(
  3931. expected_constraint_name, self.get_constraints(model._meta.db_table)
  3932. )
  3933. if editor.sql_create_fk and connection.features.can_introspect_foreign_keys:
  3934. constraint_name = "CamelCaseFKConstraint"
  3935. expected_constraint_name = identifier_converter(constraint_name)
  3936. editor.execute(
  3937. editor.sql_create_fk
  3938. % {
  3939. "table": editor.quote_name(table),
  3940. "name": editor.quote_name(constraint_name),
  3941. "column": editor.quote_name(column),
  3942. "to_table": editor.quote_name(table),
  3943. "to_column": editor.quote_name(model._meta.auto_field.column),
  3944. "deferrable": connection.ops.deferrable_sql(),
  3945. }
  3946. )
  3947. self.assertIn(
  3948. expected_constraint_name, self.get_constraints(model._meta.db_table)
  3949. )
  3950. editor.alter_field(
  3951. model,
  3952. get_field(Author, CASCADE, field_class=ForeignKey),
  3953. field,
  3954. strict=True,
  3955. )
  3956. self.assertNotIn(
  3957. expected_constraint_name, self.get_constraints(model._meta.db_table)
  3958. )
  3959. def test_add_field_use_effective_default(self):
  3960. """
  3961. #23987 - effective_default() should be used as the field default when
  3962. adding a new field.
  3963. """
  3964. # Create the table
  3965. with connection.schema_editor() as editor:
  3966. editor.create_model(Author)
  3967. # Ensure there's no surname field
  3968. columns = self.column_classes(Author)
  3969. self.assertNotIn("surname", columns)
  3970. # Create a row
  3971. Author.objects.create(name="Anonymous1")
  3972. # Add new CharField to ensure default will be used from effective_default
  3973. new_field = CharField(max_length=15, blank=True)
  3974. new_field.set_attributes_from_name("surname")
  3975. with connection.schema_editor() as editor:
  3976. editor.add_field(Author, new_field)
  3977. # Ensure field was added with the right default
  3978. with connection.cursor() as cursor:
  3979. cursor.execute("SELECT surname FROM schema_author;")
  3980. item = cursor.fetchall()[0]
  3981. self.assertEqual(
  3982. item[0],
  3983. None if connection.features.interprets_empty_strings_as_nulls else "",
  3984. )
  3985. def test_add_field_default_dropped(self):
  3986. # Create the table
  3987. with connection.schema_editor() as editor:
  3988. editor.create_model(Author)
  3989. # Ensure there's no surname field
  3990. columns = self.column_classes(Author)
  3991. self.assertNotIn("surname", columns)
  3992. # Create a row
  3993. Author.objects.create(name="Anonymous1")
  3994. # Add new CharField with a default
  3995. new_field = CharField(max_length=15, blank=True, default="surname default")
  3996. new_field.set_attributes_from_name("surname")
  3997. with connection.schema_editor() as editor:
  3998. editor.add_field(Author, new_field)
  3999. # Ensure field was added with the right default
  4000. with connection.cursor() as cursor:
  4001. cursor.execute("SELECT surname FROM schema_author;")
  4002. item = cursor.fetchall()[0]
  4003. self.assertEqual(item[0], "surname default")
  4004. # And that the default is no longer set in the database.
  4005. field = next(
  4006. f
  4007. for f in connection.introspection.get_table_description(
  4008. cursor, "schema_author"
  4009. )
  4010. if f.name == "surname"
  4011. )
  4012. if connection.features.can_introspect_default:
  4013. self.assertIsNone(field.default)
  4014. def test_add_field_default_nullable(self):
  4015. with connection.schema_editor() as editor:
  4016. editor.create_model(Author)
  4017. # Add new nullable CharField with a default.
  4018. new_field = CharField(max_length=15, blank=True, null=True, default="surname")
  4019. new_field.set_attributes_from_name("surname")
  4020. with connection.schema_editor() as editor:
  4021. editor.add_field(Author, new_field)
  4022. Author.objects.create(name="Anonymous1")
  4023. with connection.cursor() as cursor:
  4024. cursor.execute("SELECT surname FROM schema_author;")
  4025. item = cursor.fetchall()[0]
  4026. self.assertIsNone(item[0])
  4027. field = next(
  4028. f
  4029. for f in connection.introspection.get_table_description(
  4030. cursor,
  4031. "schema_author",
  4032. )
  4033. if f.name == "surname"
  4034. )
  4035. # Field is still nullable.
  4036. self.assertTrue(field.null_ok)
  4037. # The database default is no longer set.
  4038. if connection.features.can_introspect_default:
  4039. self.assertIn(field.default, ["NULL", None])
  4040. def test_add_textfield_default_nullable(self):
  4041. with connection.schema_editor() as editor:
  4042. editor.create_model(Author)
  4043. # Add new nullable TextField with a default.
  4044. new_field = TextField(blank=True, null=True, default="text")
  4045. new_field.set_attributes_from_name("description")
  4046. with connection.schema_editor() as editor:
  4047. editor.add_field(Author, new_field)
  4048. Author.objects.create(name="Anonymous1")
  4049. with connection.cursor() as cursor:
  4050. cursor.execute("SELECT description FROM schema_author;")
  4051. item = cursor.fetchall()[0]
  4052. self.assertIsNone(item[0])
  4053. field = next(
  4054. f
  4055. for f in connection.introspection.get_table_description(
  4056. cursor,
  4057. "schema_author",
  4058. )
  4059. if f.name == "description"
  4060. )
  4061. # Field is still nullable.
  4062. self.assertTrue(field.null_ok)
  4063. # The database default is no longer set.
  4064. if connection.features.can_introspect_default:
  4065. self.assertIn(field.default, ["NULL", None])
  4066. def test_alter_field_default_dropped(self):
  4067. # Create the table
  4068. with connection.schema_editor() as editor:
  4069. editor.create_model(Author)
  4070. # Create a row
  4071. Author.objects.create(name="Anonymous1")
  4072. self.assertIsNone(Author.objects.get().height)
  4073. old_field = Author._meta.get_field("height")
  4074. # The default from the new field is used in updating existing rows.
  4075. new_field = IntegerField(blank=True, default=42)
  4076. new_field.set_attributes_from_name("height")
  4077. with connection.schema_editor() as editor:
  4078. editor.alter_field(Author, old_field, new_field, strict=True)
  4079. self.assertEqual(Author.objects.get().height, 42)
  4080. # The database default should be removed.
  4081. with connection.cursor() as cursor:
  4082. field = next(
  4083. f
  4084. for f in connection.introspection.get_table_description(
  4085. cursor, "schema_author"
  4086. )
  4087. if f.name == "height"
  4088. )
  4089. if connection.features.can_introspect_default:
  4090. self.assertIsNone(field.default)
  4091. def test_alter_field_default_doesnt_perform_queries(self):
  4092. """
  4093. No queries are performed if a field default changes and the field's
  4094. not changing from null to non-null.
  4095. """
  4096. with connection.schema_editor() as editor:
  4097. editor.create_model(AuthorWithDefaultHeight)
  4098. old_field = AuthorWithDefaultHeight._meta.get_field("height")
  4099. new_default = old_field.default * 2
  4100. new_field = PositiveIntegerField(null=True, blank=True, default=new_default)
  4101. new_field.set_attributes_from_name("height")
  4102. with connection.schema_editor() as editor, self.assertNumQueries(0):
  4103. editor.alter_field(
  4104. AuthorWithDefaultHeight, old_field, new_field, strict=True
  4105. )
  4106. @skipUnlessDBFeature("supports_foreign_keys")
  4107. def test_alter_field_fk_attributes_noop(self):
  4108. """
  4109. No queries are performed when changing field attributes that don't
  4110. affect the schema.
  4111. """
  4112. with connection.schema_editor() as editor:
  4113. editor.create_model(Author)
  4114. editor.create_model(Book)
  4115. old_field = Book._meta.get_field("author")
  4116. new_field = ForeignKey(
  4117. Author,
  4118. blank=True,
  4119. editable=False,
  4120. error_messages={"invalid": "error message"},
  4121. help_text="help text",
  4122. limit_choices_to={"limit": "choice"},
  4123. on_delete=PROTECT,
  4124. related_name="related_name",
  4125. related_query_name="related_query_name",
  4126. validators=[lambda x: x],
  4127. verbose_name="verbose name",
  4128. )
  4129. new_field.set_attributes_from_name("author")
  4130. with connection.schema_editor() as editor, self.assertNumQueries(0):
  4131. editor.alter_field(Book, old_field, new_field, strict=True)
  4132. with connection.schema_editor() as editor, self.assertNumQueries(0):
  4133. editor.alter_field(Book, new_field, old_field, strict=True)
  4134. def test_alter_field_choices_noop(self):
  4135. with connection.schema_editor() as editor:
  4136. editor.create_model(Author)
  4137. old_field = Author._meta.get_field("name")
  4138. new_field = CharField(
  4139. choices=(("Jane", "Jane"), ("Joe", "Joe")),
  4140. max_length=255,
  4141. )
  4142. new_field.set_attributes_from_name("name")
  4143. with connection.schema_editor() as editor, self.assertNumQueries(0):
  4144. editor.alter_field(Author, old_field, new_field, strict=True)
  4145. with connection.schema_editor() as editor, self.assertNumQueries(0):
  4146. editor.alter_field(Author, new_field, old_field, strict=True)
  4147. def test_add_textfield_unhashable_default(self):
  4148. # Create the table
  4149. with connection.schema_editor() as editor:
  4150. editor.create_model(Author)
  4151. # Create a row
  4152. Author.objects.create(name="Anonymous1")
  4153. # Create a field that has an unhashable default
  4154. new_field = TextField(default={})
  4155. new_field.set_attributes_from_name("info")
  4156. with connection.schema_editor() as editor:
  4157. editor.add_field(Author, new_field)
  4158. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  4159. def test_add_indexed_charfield(self):
  4160. field = CharField(max_length=255, db_index=True)
  4161. field.set_attributes_from_name("nom_de_plume")
  4162. with connection.schema_editor() as editor:
  4163. editor.create_model(Author)
  4164. editor.add_field(Author, field)
  4165. # Should create two indexes; one for like operator.
  4166. self.assertEqual(
  4167. self.get_constraints_for_column(Author, "nom_de_plume"),
  4168. [
  4169. "schema_author_nom_de_plume_7570a851",
  4170. "schema_author_nom_de_plume_7570a851_like",
  4171. ],
  4172. )
  4173. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  4174. def test_add_unique_charfield(self):
  4175. field = CharField(max_length=255, unique=True)
  4176. field.set_attributes_from_name("nom_de_plume")
  4177. with connection.schema_editor() as editor:
  4178. editor.create_model(Author)
  4179. editor.add_field(Author, field)
  4180. # Should create two indexes; one for like operator.
  4181. self.assertEqual(
  4182. self.get_constraints_for_column(Author, "nom_de_plume"),
  4183. [
  4184. "schema_author_nom_de_plume_7570a851_like",
  4185. "schema_author_nom_de_plume_key",
  4186. ],
  4187. )
  4188. @skipUnlessDBFeature("supports_comments")
  4189. def test_add_db_comment_charfield(self):
  4190. comment = "Custom comment"
  4191. field = CharField(max_length=255, db_comment=comment)
  4192. field.set_attributes_from_name("name_with_comment")
  4193. with connection.schema_editor() as editor:
  4194. editor.create_model(Author)
  4195. editor.add_field(Author, field)
  4196. self.assertEqual(
  4197. self.get_column_comment(Author._meta.db_table, "name_with_comment"),
  4198. comment,
  4199. )
  4200. @skipUnlessDBFeature("supports_comments")
  4201. def test_add_db_comment_and_default_charfield(self):
  4202. comment = "Custom comment with default"
  4203. field = CharField(max_length=255, default="Joe Doe", db_comment=comment)
  4204. field.set_attributes_from_name("name_with_comment_default")
  4205. with connection.schema_editor() as editor:
  4206. editor.create_model(Author)
  4207. Author.objects.create(name="Before adding a new field")
  4208. editor.add_field(Author, field)
  4209. self.assertEqual(
  4210. self.get_column_comment(Author._meta.db_table, "name_with_comment_default"),
  4211. comment,
  4212. )
  4213. with connection.cursor() as cursor:
  4214. cursor.execute(
  4215. f"SELECT name_with_comment_default FROM {Author._meta.db_table};"
  4216. )
  4217. for row in cursor.fetchall():
  4218. self.assertEqual(row[0], "Joe Doe")
  4219. @skipUnlessDBFeature("supports_comments")
  4220. def test_alter_db_comment(self):
  4221. with connection.schema_editor() as editor:
  4222. editor.create_model(Author)
  4223. # Add comment.
  4224. old_field = Author._meta.get_field("name")
  4225. new_field = CharField(max_length=255, db_comment="Custom comment")
  4226. new_field.set_attributes_from_name("name")
  4227. with connection.schema_editor() as editor:
  4228. editor.alter_field(Author, old_field, new_field, strict=True)
  4229. self.assertEqual(
  4230. self.get_column_comment(Author._meta.db_table, "name"),
  4231. "Custom comment",
  4232. )
  4233. # Alter comment.
  4234. old_field = new_field
  4235. new_field = CharField(max_length=255, db_comment="New custom comment")
  4236. new_field.set_attributes_from_name("name")
  4237. with connection.schema_editor() as editor:
  4238. editor.alter_field(Author, old_field, new_field, strict=True)
  4239. self.assertEqual(
  4240. self.get_column_comment(Author._meta.db_table, "name"),
  4241. "New custom comment",
  4242. )
  4243. # Remove comment.
  4244. old_field = new_field
  4245. new_field = CharField(max_length=255)
  4246. new_field.set_attributes_from_name("name")
  4247. with connection.schema_editor() as editor:
  4248. editor.alter_field(Author, old_field, new_field, strict=True)
  4249. self.assertIn(
  4250. self.get_column_comment(Author._meta.db_table, "name"),
  4251. [None, ""],
  4252. )
  4253. @skipUnlessDBFeature("supports_comments", "supports_foreign_keys")
  4254. def test_alter_db_comment_foreign_key(self):
  4255. with connection.schema_editor() as editor:
  4256. editor.create_model(Author)
  4257. editor.create_model(Book)
  4258. comment = "FK custom comment"
  4259. old_field = Book._meta.get_field("author")
  4260. new_field = ForeignKey(Author, CASCADE, db_comment=comment)
  4261. new_field.set_attributes_from_name("author")
  4262. with connection.schema_editor() as editor:
  4263. editor.alter_field(Book, old_field, new_field, strict=True)
  4264. self.assertEqual(
  4265. self.get_column_comment(Book._meta.db_table, "author_id"),
  4266. comment,
  4267. )
  4268. @skipUnlessDBFeature("supports_comments")
  4269. def test_alter_field_type_preserve_comment(self):
  4270. with connection.schema_editor() as editor:
  4271. editor.create_model(Author)
  4272. comment = "This is the name."
  4273. old_field = Author._meta.get_field("name")
  4274. new_field = CharField(max_length=255, db_comment=comment)
  4275. new_field.set_attributes_from_name("name")
  4276. new_field.model = Author
  4277. with connection.schema_editor() as editor:
  4278. editor.alter_field(Author, old_field, new_field, strict=True)
  4279. self.assertEqual(
  4280. self.get_column_comment(Author._meta.db_table, "name"),
  4281. comment,
  4282. )
  4283. # Changing a field type should preserve the comment.
  4284. old_field = new_field
  4285. new_field = CharField(max_length=511, db_comment=comment)
  4286. new_field.set_attributes_from_name("name")
  4287. new_field.model = Author
  4288. with connection.schema_editor() as editor:
  4289. editor.alter_field(Author, new_field, old_field, strict=True)
  4290. # Comment is preserved.
  4291. self.assertEqual(
  4292. self.get_column_comment(Author._meta.db_table, "name"),
  4293. comment,
  4294. )
  4295. @isolate_apps("schema")
  4296. @skipUnlessDBFeature("supports_comments")
  4297. def test_db_comment_table(self):
  4298. class ModelWithDbTableComment(Model):
  4299. class Meta:
  4300. app_label = "schema"
  4301. db_table_comment = "Custom table comment"
  4302. with connection.schema_editor() as editor:
  4303. editor.create_model(ModelWithDbTableComment)
  4304. self.isolated_local_models = [ModelWithDbTableComment]
  4305. self.assertEqual(
  4306. self.get_table_comment(ModelWithDbTableComment._meta.db_table),
  4307. "Custom table comment",
  4308. )
  4309. # Alter table comment.
  4310. old_db_table_comment = ModelWithDbTableComment._meta.db_table_comment
  4311. with connection.schema_editor() as editor:
  4312. editor.alter_db_table_comment(
  4313. ModelWithDbTableComment, old_db_table_comment, "New table comment"
  4314. )
  4315. self.assertEqual(
  4316. self.get_table_comment(ModelWithDbTableComment._meta.db_table),
  4317. "New table comment",
  4318. )
  4319. # Remove table comment.
  4320. old_db_table_comment = ModelWithDbTableComment._meta.db_table_comment
  4321. with connection.schema_editor() as editor:
  4322. editor.alter_db_table_comment(
  4323. ModelWithDbTableComment, old_db_table_comment, None
  4324. )
  4325. self.assertIn(
  4326. self.get_table_comment(ModelWithDbTableComment._meta.db_table),
  4327. [None, ""],
  4328. )
  4329. @isolate_apps("schema")
  4330. @skipUnlessDBFeature("supports_comments", "supports_foreign_keys")
  4331. def test_db_comments_from_abstract_model(self):
  4332. class AbstractModelWithDbComments(Model):
  4333. name = CharField(
  4334. max_length=255, db_comment="Custom comment", null=True, blank=True
  4335. )
  4336. class Meta:
  4337. app_label = "schema"
  4338. abstract = True
  4339. db_table_comment = "Custom table comment"
  4340. class ModelWithDbComments(AbstractModelWithDbComments):
  4341. pass
  4342. with connection.schema_editor() as editor:
  4343. editor.create_model(ModelWithDbComments)
  4344. self.isolated_local_models = [ModelWithDbComments]
  4345. self.assertEqual(
  4346. self.get_column_comment(ModelWithDbComments._meta.db_table, "name"),
  4347. "Custom comment",
  4348. )
  4349. self.assertEqual(
  4350. self.get_table_comment(ModelWithDbComments._meta.db_table),
  4351. "Custom table comment",
  4352. )
  4353. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  4354. def test_alter_field_add_index_to_charfield(self):
  4355. # Create the table and verify no initial indexes.
  4356. with connection.schema_editor() as editor:
  4357. editor.create_model(Author)
  4358. self.assertEqual(self.get_constraints_for_column(Author, "name"), [])
  4359. # Alter to add db_index=True and create 2 indexes.
  4360. old_field = Author._meta.get_field("name")
  4361. new_field = CharField(max_length=255, db_index=True)
  4362. new_field.set_attributes_from_name("name")
  4363. with connection.schema_editor() as editor:
  4364. editor.alter_field(Author, old_field, new_field, strict=True)
  4365. self.assertEqual(
  4366. self.get_constraints_for_column(Author, "name"),
  4367. ["schema_author_name_1fbc5617", "schema_author_name_1fbc5617_like"],
  4368. )
  4369. # Remove db_index=True to drop both indexes.
  4370. with connection.schema_editor() as editor:
  4371. editor.alter_field(Author, new_field, old_field, strict=True)
  4372. self.assertEqual(self.get_constraints_for_column(Author, "name"), [])
  4373. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  4374. def test_alter_field_add_unique_to_charfield(self):
  4375. # Create the table and verify no initial indexes.
  4376. with connection.schema_editor() as editor:
  4377. editor.create_model(Author)
  4378. self.assertEqual(self.get_constraints_for_column(Author, "name"), [])
  4379. # Alter to add unique=True and create 2 indexes.
  4380. old_field = Author._meta.get_field("name")
  4381. new_field = CharField(max_length=255, unique=True)
  4382. new_field.set_attributes_from_name("name")
  4383. with connection.schema_editor() as editor:
  4384. editor.alter_field(Author, old_field, new_field, strict=True)
  4385. self.assertEqual(
  4386. self.get_constraints_for_column(Author, "name"),
  4387. ["schema_author_name_1fbc5617_like", "schema_author_name_1fbc5617_uniq"],
  4388. )
  4389. # Remove unique=True to drop both indexes.
  4390. with connection.schema_editor() as editor:
  4391. editor.alter_field(Author, new_field, old_field, strict=True)
  4392. self.assertEqual(self.get_constraints_for_column(Author, "name"), [])
  4393. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  4394. def test_alter_field_add_index_to_textfield(self):
  4395. # Create the table and verify no initial indexes.
  4396. with connection.schema_editor() as editor:
  4397. editor.create_model(Note)
  4398. self.assertEqual(self.get_constraints_for_column(Note, "info"), [])
  4399. # Alter to add db_index=True and create 2 indexes.
  4400. old_field = Note._meta.get_field("info")
  4401. new_field = TextField(db_index=True)
  4402. new_field.set_attributes_from_name("info")
  4403. with connection.schema_editor() as editor:
  4404. editor.alter_field(Note, old_field, new_field, strict=True)
  4405. self.assertEqual(
  4406. self.get_constraints_for_column(Note, "info"),
  4407. ["schema_note_info_4b0ea695", "schema_note_info_4b0ea695_like"],
  4408. )
  4409. # Remove db_index=True to drop both indexes.
  4410. with connection.schema_editor() as editor:
  4411. editor.alter_field(Note, new_field, old_field, strict=True)
  4412. self.assertEqual(self.get_constraints_for_column(Note, "info"), [])
  4413. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  4414. def test_alter_field_add_unique_to_charfield_with_db_index(self):
  4415. # Create the table and verify initial indexes.
  4416. with connection.schema_editor() as editor:
  4417. editor.create_model(BookWithoutAuthor)
  4418. self.assertEqual(
  4419. self.get_constraints_for_column(BookWithoutAuthor, "title"),
  4420. ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"],
  4421. )
  4422. # Alter to add unique=True (should replace the index)
  4423. old_field = BookWithoutAuthor._meta.get_field("title")
  4424. new_field = CharField(max_length=100, db_index=True, unique=True)
  4425. new_field.set_attributes_from_name("title")
  4426. with connection.schema_editor() as editor:
  4427. editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True)
  4428. self.assertEqual(
  4429. self.get_constraints_for_column(BookWithoutAuthor, "title"),
  4430. ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"],
  4431. )
  4432. # Alter to remove unique=True (should drop unique index)
  4433. new_field2 = CharField(max_length=100, db_index=True)
  4434. new_field2.set_attributes_from_name("title")
  4435. with connection.schema_editor() as editor:
  4436. editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True)
  4437. self.assertEqual(
  4438. self.get_constraints_for_column(BookWithoutAuthor, "title"),
  4439. ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"],
  4440. )
  4441. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  4442. def test_alter_field_remove_unique_and_db_index_from_charfield(self):
  4443. # Create the table and verify initial indexes.
  4444. with connection.schema_editor() as editor:
  4445. editor.create_model(BookWithoutAuthor)
  4446. self.assertEqual(
  4447. self.get_constraints_for_column(BookWithoutAuthor, "title"),
  4448. ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"],
  4449. )
  4450. # Alter to add unique=True (should replace the index)
  4451. old_field = BookWithoutAuthor._meta.get_field("title")
  4452. new_field = CharField(max_length=100, db_index=True, unique=True)
  4453. new_field.set_attributes_from_name("title")
  4454. with connection.schema_editor() as editor:
  4455. editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True)
  4456. self.assertEqual(
  4457. self.get_constraints_for_column(BookWithoutAuthor, "title"),
  4458. ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"],
  4459. )
  4460. # Alter to remove both unique=True and db_index=True (should drop all indexes)
  4461. new_field2 = CharField(max_length=100)
  4462. new_field2.set_attributes_from_name("title")
  4463. with connection.schema_editor() as editor:
  4464. editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True)
  4465. self.assertEqual(
  4466. self.get_constraints_for_column(BookWithoutAuthor, "title"), []
  4467. )
  4468. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  4469. def test_alter_field_swap_unique_and_db_index_with_charfield(self):
  4470. # Create the table and verify initial indexes.
  4471. with connection.schema_editor() as editor:
  4472. editor.create_model(BookWithoutAuthor)
  4473. self.assertEqual(
  4474. self.get_constraints_for_column(BookWithoutAuthor, "title"),
  4475. ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"],
  4476. )
  4477. # Alter to set unique=True and remove db_index=True (should replace the index)
  4478. old_field = BookWithoutAuthor._meta.get_field("title")
  4479. new_field = CharField(max_length=100, unique=True)
  4480. new_field.set_attributes_from_name("title")
  4481. with connection.schema_editor() as editor:
  4482. editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True)
  4483. self.assertEqual(
  4484. self.get_constraints_for_column(BookWithoutAuthor, "title"),
  4485. ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"],
  4486. )
  4487. # Alter to set db_index=True and remove unique=True (should restore index)
  4488. new_field2 = CharField(max_length=100, db_index=True)
  4489. new_field2.set_attributes_from_name("title")
  4490. with connection.schema_editor() as editor:
  4491. editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True)
  4492. self.assertEqual(
  4493. self.get_constraints_for_column(BookWithoutAuthor, "title"),
  4494. ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"],
  4495. )
  4496. @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
  4497. def test_alter_field_add_db_index_to_charfield_with_unique(self):
  4498. # Create the table and verify initial indexes.
  4499. with connection.schema_editor() as editor:
  4500. editor.create_model(Tag)
  4501. self.assertEqual(
  4502. self.get_constraints_for_column(Tag, "slug"),
  4503. ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"],
  4504. )
  4505. # Alter to add db_index=True
  4506. old_field = Tag._meta.get_field("slug")
  4507. new_field = SlugField(db_index=True, unique=True)
  4508. new_field.set_attributes_from_name("slug")
  4509. with connection.schema_editor() as editor:
  4510. editor.alter_field(Tag, old_field, new_field, strict=True)
  4511. self.assertEqual(
  4512. self.get_constraints_for_column(Tag, "slug"),
  4513. ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"],
  4514. )
  4515. # Alter to remove db_index=True
  4516. new_field2 = SlugField(unique=True)
  4517. new_field2.set_attributes_from_name("slug")
  4518. with connection.schema_editor() as editor:
  4519. editor.alter_field(Tag, new_field, new_field2, strict=True)
  4520. self.assertEqual(
  4521. self.get_constraints_for_column(Tag, "slug"),
  4522. ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"],
  4523. )
  4524. def test_alter_field_add_index_to_integerfield(self):
  4525. # Create the table and verify no initial indexes.
  4526. with connection.schema_editor() as editor:
  4527. editor.create_model(Author)
  4528. self.assertEqual(self.get_constraints_for_column(Author, "weight"), [])
  4529. # Alter to add db_index=True and create index.
  4530. old_field = Author._meta.get_field("weight")
  4531. new_field = IntegerField(null=True, db_index=True)
  4532. new_field.set_attributes_from_name("weight")
  4533. with connection.schema_editor() as editor:
  4534. editor.alter_field(Author, old_field, new_field, strict=True)
  4535. self.assertEqual(
  4536. self.get_constraints_for_column(Author, "weight"),
  4537. ["schema_author_weight_587740f9"],
  4538. )
  4539. # Remove db_index=True to drop index.
  4540. with connection.schema_editor() as editor:
  4541. editor.alter_field(Author, new_field, old_field, strict=True)
  4542. self.assertEqual(self.get_constraints_for_column(Author, "weight"), [])
  4543. def test_alter_pk_with_self_referential_field(self):
  4544. """
  4545. Changing the primary key field name of a model with a self-referential
  4546. foreign key (#26384).
  4547. """
  4548. with connection.schema_editor() as editor:
  4549. editor.create_model(Node)
  4550. old_field = Node._meta.get_field("node_id")
  4551. new_field = AutoField(primary_key=True)
  4552. new_field.set_attributes_from_name("id")
  4553. with connection.schema_editor() as editor:
  4554. editor.alter_field(Node, old_field, new_field, strict=True)
  4555. self.assertForeignKeyExists(Node, "parent_id", Node._meta.db_table)
  4556. @mock.patch("django.db.backends.base.schema.datetime")
  4557. @mock.patch("django.db.backends.base.schema.timezone")
  4558. def test_add_datefield_and_datetimefield_use_effective_default(
  4559. self, mocked_datetime, mocked_tz
  4560. ):
  4561. """
  4562. effective_default() should be used for DateField, DateTimeField, and
  4563. TimeField if auto_now or auto_now_add is set (#25005).
  4564. """
  4565. now = datetime.datetime(month=1, day=1, year=2000, hour=1, minute=1)
  4566. now_tz = datetime.datetime(
  4567. month=1, day=1, year=2000, hour=1, minute=1, tzinfo=datetime.timezone.utc
  4568. )
  4569. mocked_datetime.now = mock.MagicMock(return_value=now)
  4570. mocked_tz.now = mock.MagicMock(return_value=now_tz)
  4571. # Create the table
  4572. with connection.schema_editor() as editor:
  4573. editor.create_model(Author)
  4574. # Check auto_now/auto_now_add attributes are not defined
  4575. columns = self.column_classes(Author)
  4576. self.assertNotIn("dob_auto_now", columns)
  4577. self.assertNotIn("dob_auto_now_add", columns)
  4578. self.assertNotIn("dtob_auto_now", columns)
  4579. self.assertNotIn("dtob_auto_now_add", columns)
  4580. self.assertNotIn("tob_auto_now", columns)
  4581. self.assertNotIn("tob_auto_now_add", columns)
  4582. # Create a row
  4583. Author.objects.create(name="Anonymous1")
  4584. # Ensure fields were added with the correct defaults
  4585. dob_auto_now = DateField(auto_now=True)
  4586. dob_auto_now.set_attributes_from_name("dob_auto_now")
  4587. self.check_added_field_default(
  4588. editor,
  4589. Author,
  4590. dob_auto_now,
  4591. "dob_auto_now",
  4592. now.date(),
  4593. cast_function=lambda x: x.date(),
  4594. )
  4595. dob_auto_now_add = DateField(auto_now_add=True)
  4596. dob_auto_now_add.set_attributes_from_name("dob_auto_now_add")
  4597. self.check_added_field_default(
  4598. editor,
  4599. Author,
  4600. dob_auto_now_add,
  4601. "dob_auto_now_add",
  4602. now.date(),
  4603. cast_function=lambda x: x.date(),
  4604. )
  4605. dtob_auto_now = DateTimeField(auto_now=True)
  4606. dtob_auto_now.set_attributes_from_name("dtob_auto_now")
  4607. self.check_added_field_default(
  4608. editor,
  4609. Author,
  4610. dtob_auto_now,
  4611. "dtob_auto_now",
  4612. now,
  4613. )
  4614. dt_tm_of_birth_auto_now_add = DateTimeField(auto_now_add=True)
  4615. dt_tm_of_birth_auto_now_add.set_attributes_from_name("dtob_auto_now_add")
  4616. self.check_added_field_default(
  4617. editor,
  4618. Author,
  4619. dt_tm_of_birth_auto_now_add,
  4620. "dtob_auto_now_add",
  4621. now,
  4622. )
  4623. tob_auto_now = TimeField(auto_now=True)
  4624. tob_auto_now.set_attributes_from_name("tob_auto_now")
  4625. self.check_added_field_default(
  4626. editor,
  4627. Author,
  4628. tob_auto_now,
  4629. "tob_auto_now",
  4630. now.time(),
  4631. cast_function=lambda x: x.time(),
  4632. )
  4633. tob_auto_now_add = TimeField(auto_now_add=True)
  4634. tob_auto_now_add.set_attributes_from_name("tob_auto_now_add")
  4635. self.check_added_field_default(
  4636. editor,
  4637. Author,
  4638. tob_auto_now_add,
  4639. "tob_auto_now_add",
  4640. now.time(),
  4641. cast_function=lambda x: x.time(),
  4642. )
  4643. def test_namespaced_db_table_create_index_name(self):
  4644. """
  4645. Table names are stripped of their namespace/schema before being used to
  4646. generate index names.
  4647. """
  4648. with connection.schema_editor() as editor:
  4649. max_name_length = connection.ops.max_name_length() or 200
  4650. namespace = "n" * max_name_length
  4651. table_name = "t" * max_name_length
  4652. namespaced_table_name = '"%s"."%s"' % (namespace, table_name)
  4653. self.assertEqual(
  4654. editor._create_index_name(table_name, []),
  4655. editor._create_index_name(namespaced_table_name, []),
  4656. )
  4657. @unittest.skipUnless(
  4658. connection.vendor == "oracle", "Oracle specific db_table syntax"
  4659. )
  4660. def test_creation_with_db_table_double_quotes(self):
  4661. oracle_user = connection.creation._test_database_user()
  4662. class Student(Model):
  4663. name = CharField(max_length=30)
  4664. class Meta:
  4665. app_label = "schema"
  4666. apps = new_apps
  4667. db_table = '"%s"."DJANGO_STUDENT_TABLE"' % oracle_user
  4668. class Document(Model):
  4669. name = CharField(max_length=30)
  4670. students = ManyToManyField(Student)
  4671. class Meta:
  4672. app_label = "schema"
  4673. apps = new_apps
  4674. db_table = '"%s"."DJANGO_DOCUMENT_TABLE"' % oracle_user
  4675. self.isolated_local_models = [Student, Document]
  4676. with connection.schema_editor() as editor:
  4677. editor.create_model(Student)
  4678. editor.create_model(Document)
  4679. doc = Document.objects.create(name="Test Name")
  4680. student = Student.objects.create(name="Some man")
  4681. doc.students.add(student)
  4682. @isolate_apps("schema")
  4683. @unittest.skipUnless(
  4684. connection.vendor == "postgresql", "PostgreSQL specific db_table syntax."
  4685. )
  4686. def test_namespaced_db_table_foreign_key_reference(self):
  4687. with connection.cursor() as cursor:
  4688. cursor.execute("CREATE SCHEMA django_schema_tests")
  4689. def delete_schema():
  4690. with connection.cursor() as cursor:
  4691. cursor.execute("DROP SCHEMA django_schema_tests CASCADE")
  4692. self.addCleanup(delete_schema)
  4693. class Author(Model):
  4694. class Meta:
  4695. app_label = "schema"
  4696. class Book(Model):
  4697. class Meta:
  4698. app_label = "schema"
  4699. db_table = '"django_schema_tests"."schema_book"'
  4700. author = ForeignKey(Author, CASCADE)
  4701. author.set_attributes_from_name("author")
  4702. with connection.schema_editor() as editor:
  4703. editor.create_model(Author)
  4704. editor.create_model(Book)
  4705. editor.add_field(Book, author)
  4706. def test_rename_table_renames_deferred_sql_references(self):
  4707. with connection.schema_editor() as editor:
  4708. editor.create_model(Author)
  4709. editor.create_model(Book)
  4710. editor.alter_db_table(Author, "schema_author", "schema_renamed_author")
  4711. editor.alter_db_table(Author, "schema_book", "schema_renamed_book")
  4712. try:
  4713. self.assertGreater(len(editor.deferred_sql), 0)
  4714. for statement in editor.deferred_sql:
  4715. self.assertIs(statement.references_table("schema_author"), False)
  4716. self.assertIs(statement.references_table("schema_book"), False)
  4717. finally:
  4718. editor.alter_db_table(Author, "schema_renamed_author", "schema_author")
  4719. editor.alter_db_table(Author, "schema_renamed_book", "schema_book")
  4720. def test_rename_column_renames_deferred_sql_references(self):
  4721. with connection.schema_editor() as editor:
  4722. editor.create_model(Author)
  4723. editor.create_model(Book)
  4724. old_title = Book._meta.get_field("title")
  4725. new_title = CharField(max_length=100, db_index=True)
  4726. new_title.set_attributes_from_name("renamed_title")
  4727. editor.alter_field(Book, old_title, new_title)
  4728. old_author = Book._meta.get_field("author")
  4729. new_author = ForeignKey(Author, CASCADE)
  4730. new_author.set_attributes_from_name("renamed_author")
  4731. editor.alter_field(Book, old_author, new_author)
  4732. self.assertGreater(len(editor.deferred_sql), 0)
  4733. for statement in editor.deferred_sql:
  4734. self.assertIs(statement.references_column("book", "title"), False)
  4735. self.assertIs(statement.references_column("book", "author_id"), False)
  4736. @isolate_apps("schema")
  4737. def test_referenced_field_without_constraint_rename_inside_atomic_block(self):
  4738. """
  4739. Foreign keys without database level constraint don't prevent the field
  4740. they reference from being renamed in an atomic block.
  4741. """
  4742. class Foo(Model):
  4743. field = CharField(max_length=255, unique=True)
  4744. class Meta:
  4745. app_label = "schema"
  4746. class Bar(Model):
  4747. foo = ForeignKey(Foo, CASCADE, to_field="field", db_constraint=False)
  4748. class Meta:
  4749. app_label = "schema"
  4750. self.isolated_local_models = [Foo, Bar]
  4751. with connection.schema_editor() as editor:
  4752. editor.create_model(Foo)
  4753. editor.create_model(Bar)
  4754. new_field = CharField(max_length=255, unique=True)
  4755. new_field.set_attributes_from_name("renamed")
  4756. with connection.schema_editor(atomic=True) as editor:
  4757. editor.alter_field(Foo, Foo._meta.get_field("field"), new_field)
  4758. @isolate_apps("schema")
  4759. def test_referenced_table_without_constraint_rename_inside_atomic_block(self):
  4760. """
  4761. Foreign keys without database level constraint don't prevent the table
  4762. they reference from being renamed in an atomic block.
  4763. """
  4764. class Foo(Model):
  4765. field = CharField(max_length=255, unique=True)
  4766. class Meta:
  4767. app_label = "schema"
  4768. class Bar(Model):
  4769. foo = ForeignKey(Foo, CASCADE, to_field="field", db_constraint=False)
  4770. class Meta:
  4771. app_label = "schema"
  4772. self.isolated_local_models = [Foo, Bar]
  4773. with connection.schema_editor() as editor:
  4774. editor.create_model(Foo)
  4775. editor.create_model(Bar)
  4776. new_field = CharField(max_length=255, unique=True)
  4777. new_field.set_attributes_from_name("renamed")
  4778. with connection.schema_editor(atomic=True) as editor:
  4779. editor.alter_db_table(Foo, Foo._meta.db_table, "renamed_table")
  4780. Foo._meta.db_table = "renamed_table"
  4781. @isolate_apps("schema")
  4782. @skipUnlessDBFeature("supports_collation_on_charfield")
  4783. def test_db_collation_charfield(self):
  4784. collation = connection.features.test_collations.get("non_default")
  4785. if not collation:
  4786. self.skipTest("Language collations are not supported.")
  4787. class Foo(Model):
  4788. field = CharField(max_length=255, db_collation=collation)
  4789. class Meta:
  4790. app_label = "schema"
  4791. self.isolated_local_models = [Foo]
  4792. with connection.schema_editor() as editor:
  4793. editor.create_model(Foo)
  4794. self.assertEqual(
  4795. self.get_column_collation(Foo._meta.db_table, "field"),
  4796. collation,
  4797. )
  4798. @isolate_apps("schema")
  4799. @skipUnlessDBFeature("supports_collation_on_textfield")
  4800. def test_db_collation_textfield(self):
  4801. collation = connection.features.test_collations.get("non_default")
  4802. if not collation:
  4803. self.skipTest("Language collations are not supported.")
  4804. class Foo(Model):
  4805. field = TextField(db_collation=collation)
  4806. class Meta:
  4807. app_label = "schema"
  4808. self.isolated_local_models = [Foo]
  4809. with connection.schema_editor() as editor:
  4810. editor.create_model(Foo)
  4811. self.assertEqual(
  4812. self.get_column_collation(Foo._meta.db_table, "field"),
  4813. collation,
  4814. )
  4815. @skipUnlessDBFeature("supports_collation_on_charfield")
  4816. def test_add_field_db_collation(self):
  4817. collation = connection.features.test_collations.get("non_default")
  4818. if not collation:
  4819. self.skipTest("Language collations are not supported.")
  4820. with connection.schema_editor() as editor:
  4821. editor.create_model(Author)
  4822. new_field = CharField(max_length=255, db_collation=collation)
  4823. new_field.set_attributes_from_name("alias")
  4824. with connection.schema_editor() as editor:
  4825. editor.add_field(Author, new_field)
  4826. columns = self.column_classes(Author)
  4827. self.assertEqual(
  4828. columns["alias"][0],
  4829. connection.features.introspected_field_types["CharField"],
  4830. )
  4831. self.assertEqual(columns["alias"][1][8], collation)
  4832. @skipUnlessDBFeature("supports_collation_on_charfield")
  4833. def test_alter_field_db_collation(self):
  4834. collation = connection.features.test_collations.get("non_default")
  4835. if not collation:
  4836. self.skipTest("Language collations are not supported.")
  4837. with connection.schema_editor() as editor:
  4838. editor.create_model(Author)
  4839. old_field = Author._meta.get_field("name")
  4840. new_field = CharField(max_length=255, db_collation=collation)
  4841. new_field.set_attributes_from_name("name")
  4842. new_field.model = Author
  4843. with connection.schema_editor() as editor:
  4844. editor.alter_field(Author, old_field, new_field, strict=True)
  4845. self.assertEqual(
  4846. self.get_column_collation(Author._meta.db_table, "name"),
  4847. collation,
  4848. )
  4849. with connection.schema_editor() as editor:
  4850. editor.alter_field(Author, new_field, old_field, strict=True)
  4851. self.assertIsNone(self.get_column_collation(Author._meta.db_table, "name"))
  4852. @skipUnlessDBFeature("supports_collation_on_charfield")
  4853. def test_alter_field_type_preserve_db_collation(self):
  4854. collation = connection.features.test_collations.get("non_default")
  4855. if not collation:
  4856. self.skipTest("Language collations are not supported.")
  4857. with connection.schema_editor() as editor:
  4858. editor.create_model(Author)
  4859. old_field = Author._meta.get_field("name")
  4860. new_field = CharField(max_length=255, db_collation=collation)
  4861. new_field.set_attributes_from_name("name")
  4862. new_field.model = Author
  4863. with connection.schema_editor() as editor:
  4864. editor.alter_field(Author, old_field, new_field, strict=True)
  4865. self.assertEqual(
  4866. self.get_column_collation(Author._meta.db_table, "name"),
  4867. collation,
  4868. )
  4869. # Changing a field type should preserve the collation.
  4870. old_field = new_field
  4871. new_field = CharField(max_length=511, db_collation=collation)
  4872. new_field.set_attributes_from_name("name")
  4873. new_field.model = Author
  4874. with connection.schema_editor() as editor:
  4875. editor.alter_field(Author, new_field, old_field, strict=True)
  4876. # Collation is preserved.
  4877. self.assertEqual(
  4878. self.get_column_collation(Author._meta.db_table, "name"),
  4879. collation,
  4880. )
  4881. @skipUnlessDBFeature("supports_collation_on_charfield")
  4882. def test_alter_primary_key_db_collation(self):
  4883. collation = connection.features.test_collations.get("non_default")
  4884. if not collation:
  4885. self.skipTest("Language collations are not supported.")
  4886. with connection.schema_editor() as editor:
  4887. editor.create_model(Thing)
  4888. old_field = Thing._meta.get_field("when")
  4889. new_field = CharField(max_length=1, db_collation=collation, primary_key=True)
  4890. new_field.set_attributes_from_name("when")
  4891. new_field.model = Thing
  4892. with connection.schema_editor() as editor:
  4893. editor.alter_field(Thing, old_field, new_field, strict=True)
  4894. self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when")
  4895. self.assertEqual(
  4896. self.get_column_collation(Thing._meta.db_table, "when"),
  4897. collation,
  4898. )
  4899. with connection.schema_editor() as editor:
  4900. editor.alter_field(Thing, new_field, old_field, strict=True)
  4901. self.assertEqual(self.get_primary_key(Thing._meta.db_table), "when")
  4902. self.assertIsNone(self.get_column_collation(Thing._meta.db_table, "when"))
  4903. @skipUnlessDBFeature(
  4904. "supports_collation_on_charfield", "supports_collation_on_textfield"
  4905. )
  4906. def test_alter_field_type_and_db_collation(self):
  4907. collation = connection.features.test_collations.get("non_default")
  4908. if not collation:
  4909. self.skipTest("Language collations are not supported.")
  4910. with connection.schema_editor() as editor:
  4911. editor.create_model(Note)
  4912. old_field = Note._meta.get_field("info")
  4913. new_field = CharField(max_length=255, db_collation=collation)
  4914. new_field.set_attributes_from_name("info")
  4915. new_field.model = Note
  4916. with connection.schema_editor() as editor:
  4917. editor.alter_field(Note, old_field, new_field, strict=True)
  4918. columns = self.column_classes(Note)
  4919. self.assertEqual(
  4920. columns["info"][0],
  4921. connection.features.introspected_field_types["CharField"],
  4922. )
  4923. self.assertEqual(columns["info"][1][8], collation)
  4924. with connection.schema_editor() as editor:
  4925. editor.alter_field(Note, new_field, old_field, strict=True)
  4926. columns = self.column_classes(Note)
  4927. self.assertEqual(columns["info"][0], "TextField")
  4928. self.assertIsNone(columns["info"][1][8])
  4929. @skipUnlessDBFeature(
  4930. "supports_collation_on_charfield",
  4931. "supports_non_deterministic_collations",
  4932. )
  4933. def test_ci_cs_db_collation(self):
  4934. cs_collation = connection.features.test_collations.get("cs")
  4935. ci_collation = connection.features.test_collations.get("ci")
  4936. try:
  4937. if connection.vendor == "mysql":
  4938. cs_collation = "latin1_general_cs"
  4939. elif connection.vendor == "postgresql":
  4940. cs_collation = "en-x-icu"
  4941. with connection.cursor() as cursor:
  4942. cursor.execute(
  4943. "CREATE COLLATION IF NOT EXISTS case_insensitive "
  4944. "(provider = icu, locale = 'und-u-ks-level2', "
  4945. "deterministic = false)"
  4946. )
  4947. ci_collation = "case_insensitive"
  4948. # Create the table.
  4949. with connection.schema_editor() as editor:
  4950. editor.create_model(Author)
  4951. # Case-insensitive collation.
  4952. old_field = Author._meta.get_field("name")
  4953. new_field_ci = CharField(max_length=255, db_collation=ci_collation)
  4954. new_field_ci.set_attributes_from_name("name")
  4955. new_field_ci.model = Author
  4956. with connection.schema_editor() as editor:
  4957. editor.alter_field(Author, old_field, new_field_ci, strict=True)
  4958. Author.objects.create(name="ANDREW")
  4959. self.assertIs(Author.objects.filter(name="Andrew").exists(), True)
  4960. # Case-sensitive collation.
  4961. new_field_cs = CharField(max_length=255, db_collation=cs_collation)
  4962. new_field_cs.set_attributes_from_name("name")
  4963. new_field_cs.model = Author
  4964. with connection.schema_editor() as editor:
  4965. editor.alter_field(Author, new_field_ci, new_field_cs, strict=True)
  4966. self.assertIs(Author.objects.filter(name="Andrew").exists(), False)
  4967. finally:
  4968. if connection.vendor == "postgresql":
  4969. with connection.cursor() as cursor:
  4970. cursor.execute("DROP COLLATION IF EXISTS case_insensitive")