tests.py 228 KB

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