tests.py 195 KB

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