tests.py 190 KB

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