tests.py 217 KB

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