test_operations.py 163 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368
  1. from django.core.exceptions import FieldDoesNotExist
  2. from django.db import (
  3. IntegrityError, connection, migrations, models, transaction,
  4. )
  5. from django.db.migrations.migration import Migration
  6. from django.db.migrations.operations.fields import FieldOperation
  7. from django.db.migrations.state import ModelState, ProjectState
  8. from django.db.transaction import atomic
  9. from django.test import SimpleTestCase, override_settings, skipUnlessDBFeature
  10. from .models import FoodManager, FoodQuerySet, UnicodeModel
  11. from .test_base import OperationTestBase
  12. class Mixin:
  13. pass
  14. class OperationTests(OperationTestBase):
  15. """
  16. Tests running the operations and making sure they do what they say they do.
  17. Each test looks at their state changing, and then their database operation -
  18. both forwards and backwards.
  19. """
  20. def test_create_model(self):
  21. """
  22. Tests the CreateModel operation.
  23. Most other tests use this operation as part of setup, so check failures here first.
  24. """
  25. operation = migrations.CreateModel(
  26. "Pony",
  27. [
  28. ("id", models.AutoField(primary_key=True)),
  29. ("pink", models.IntegerField(default=1)),
  30. ],
  31. )
  32. self.assertEqual(operation.describe(), "Create model Pony")
  33. self.assertEqual(operation.migration_name_fragment, 'pony')
  34. # Test the state alteration
  35. project_state = ProjectState()
  36. new_state = project_state.clone()
  37. operation.state_forwards("test_crmo", new_state)
  38. self.assertEqual(new_state.models["test_crmo", "pony"].name, "Pony")
  39. self.assertEqual(len(new_state.models["test_crmo", "pony"].fields), 2)
  40. # Test the database alteration
  41. self.assertTableNotExists("test_crmo_pony")
  42. with connection.schema_editor() as editor:
  43. operation.database_forwards("test_crmo", editor, project_state, new_state)
  44. self.assertTableExists("test_crmo_pony")
  45. # And test reversal
  46. with connection.schema_editor() as editor:
  47. operation.database_backwards("test_crmo", editor, new_state, project_state)
  48. self.assertTableNotExists("test_crmo_pony")
  49. # And deconstruction
  50. definition = operation.deconstruct()
  51. self.assertEqual(definition[0], "CreateModel")
  52. self.assertEqual(definition[1], [])
  53. self.assertEqual(sorted(definition[2]), ["fields", "name"])
  54. # And default manager not in set
  55. operation = migrations.CreateModel("Foo", fields=[], managers=[("objects", models.Manager())])
  56. definition = operation.deconstruct()
  57. self.assertNotIn('managers', definition[2])
  58. def test_create_model_with_duplicate_field_name(self):
  59. with self.assertRaisesMessage(ValueError, 'Found duplicate value pink in CreateModel fields argument.'):
  60. migrations.CreateModel(
  61. "Pony",
  62. [
  63. ("id", models.AutoField(primary_key=True)),
  64. ("pink", models.TextField()),
  65. ("pink", models.IntegerField(default=1)),
  66. ],
  67. )
  68. def test_create_model_with_duplicate_base(self):
  69. message = 'Found duplicate value test_crmo.pony in CreateModel bases argument.'
  70. with self.assertRaisesMessage(ValueError, message):
  71. migrations.CreateModel(
  72. "Pony",
  73. fields=[],
  74. bases=("test_crmo.Pony", "test_crmo.Pony",),
  75. )
  76. with self.assertRaisesMessage(ValueError, message):
  77. migrations.CreateModel(
  78. "Pony",
  79. fields=[],
  80. bases=("test_crmo.Pony", "test_crmo.pony",),
  81. )
  82. message = 'Found duplicate value migrations.unicodemodel in CreateModel bases argument.'
  83. with self.assertRaisesMessage(ValueError, message):
  84. migrations.CreateModel(
  85. "Pony",
  86. fields=[],
  87. bases=(UnicodeModel, UnicodeModel,),
  88. )
  89. with self.assertRaisesMessage(ValueError, message):
  90. migrations.CreateModel(
  91. "Pony",
  92. fields=[],
  93. bases=(UnicodeModel, 'migrations.unicodemodel',),
  94. )
  95. with self.assertRaisesMessage(ValueError, message):
  96. migrations.CreateModel(
  97. "Pony",
  98. fields=[],
  99. bases=(UnicodeModel, 'migrations.UnicodeModel',),
  100. )
  101. message = "Found duplicate value <class 'django.db.models.base.Model'> in CreateModel bases argument."
  102. with self.assertRaisesMessage(ValueError, message):
  103. migrations.CreateModel(
  104. "Pony",
  105. fields=[],
  106. bases=(models.Model, models.Model,),
  107. )
  108. message = "Found duplicate value <class 'migrations.test_operations.Mixin'> in CreateModel bases argument."
  109. with self.assertRaisesMessage(ValueError, message):
  110. migrations.CreateModel(
  111. "Pony",
  112. fields=[],
  113. bases=(Mixin, Mixin,),
  114. )
  115. def test_create_model_with_duplicate_manager_name(self):
  116. with self.assertRaisesMessage(ValueError, 'Found duplicate value objects in CreateModel managers argument.'):
  117. migrations.CreateModel(
  118. "Pony",
  119. fields=[],
  120. managers=[
  121. ("objects", models.Manager()),
  122. ("objects", models.Manager()),
  123. ],
  124. )
  125. def test_create_model_with_unique_after(self):
  126. """
  127. Tests the CreateModel operation directly followed by an
  128. AlterUniqueTogether (bug #22844 - sqlite remake issues)
  129. """
  130. operation1 = migrations.CreateModel(
  131. "Pony",
  132. [
  133. ("id", models.AutoField(primary_key=True)),
  134. ("pink", models.IntegerField(default=1)),
  135. ],
  136. )
  137. operation2 = migrations.CreateModel(
  138. "Rider",
  139. [
  140. ("id", models.AutoField(primary_key=True)),
  141. ("number", models.IntegerField(default=1)),
  142. ("pony", models.ForeignKey("test_crmoua.Pony", models.CASCADE)),
  143. ],
  144. )
  145. operation3 = migrations.AlterUniqueTogether(
  146. "Rider",
  147. [
  148. ("number", "pony"),
  149. ],
  150. )
  151. # Test the database alteration
  152. project_state = ProjectState()
  153. self.assertTableNotExists("test_crmoua_pony")
  154. self.assertTableNotExists("test_crmoua_rider")
  155. with connection.schema_editor() as editor:
  156. new_state = project_state.clone()
  157. operation1.state_forwards("test_crmoua", new_state)
  158. operation1.database_forwards("test_crmoua", editor, project_state, new_state)
  159. project_state, new_state = new_state, new_state.clone()
  160. operation2.state_forwards("test_crmoua", new_state)
  161. operation2.database_forwards("test_crmoua", editor, project_state, new_state)
  162. project_state, new_state = new_state, new_state.clone()
  163. operation3.state_forwards("test_crmoua", new_state)
  164. operation3.database_forwards("test_crmoua", editor, project_state, new_state)
  165. self.assertTableExists("test_crmoua_pony")
  166. self.assertTableExists("test_crmoua_rider")
  167. def test_create_model_m2m(self):
  168. """
  169. Test the creation of a model with a ManyToMany field and the
  170. auto-created "through" model.
  171. """
  172. project_state = self.set_up_test_model("test_crmomm")
  173. operation = migrations.CreateModel(
  174. "Stable",
  175. [
  176. ("id", models.AutoField(primary_key=True)),
  177. ("ponies", models.ManyToManyField("Pony", related_name="stables"))
  178. ]
  179. )
  180. # Test the state alteration
  181. new_state = project_state.clone()
  182. operation.state_forwards("test_crmomm", new_state)
  183. # Test the database alteration
  184. self.assertTableNotExists("test_crmomm_stable_ponies")
  185. with connection.schema_editor() as editor:
  186. operation.database_forwards("test_crmomm", editor, project_state, new_state)
  187. self.assertTableExists("test_crmomm_stable")
  188. self.assertTableExists("test_crmomm_stable_ponies")
  189. self.assertColumnNotExists("test_crmomm_stable", "ponies")
  190. # Make sure the M2M field actually works
  191. with atomic():
  192. Pony = new_state.apps.get_model("test_crmomm", "Pony")
  193. Stable = new_state.apps.get_model("test_crmomm", "Stable")
  194. stable = Stable.objects.create()
  195. p1 = Pony.objects.create(pink=False, weight=4.55)
  196. p2 = Pony.objects.create(pink=True, weight=5.43)
  197. stable.ponies.add(p1, p2)
  198. self.assertEqual(stable.ponies.count(), 2)
  199. stable.ponies.all().delete()
  200. # And test reversal
  201. with connection.schema_editor() as editor:
  202. operation.database_backwards("test_crmomm", editor, new_state, project_state)
  203. self.assertTableNotExists("test_crmomm_stable")
  204. self.assertTableNotExists("test_crmomm_stable_ponies")
  205. def test_create_model_inheritance(self):
  206. """
  207. Tests the CreateModel operation on a multi-table inheritance setup.
  208. """
  209. project_state = self.set_up_test_model("test_crmoih")
  210. # Test the state alteration
  211. operation = migrations.CreateModel(
  212. "ShetlandPony",
  213. [
  214. ('pony_ptr', models.OneToOneField(
  215. 'test_crmoih.Pony',
  216. models.CASCADE,
  217. auto_created=True,
  218. primary_key=True,
  219. to_field='id',
  220. serialize=False,
  221. )),
  222. ("cuteness", models.IntegerField(default=1)),
  223. ],
  224. )
  225. new_state = project_state.clone()
  226. operation.state_forwards("test_crmoih", new_state)
  227. self.assertIn(("test_crmoih", "shetlandpony"), new_state.models)
  228. # Test the database alteration
  229. self.assertTableNotExists("test_crmoih_shetlandpony")
  230. with connection.schema_editor() as editor:
  231. operation.database_forwards("test_crmoih", editor, project_state, new_state)
  232. self.assertTableExists("test_crmoih_shetlandpony")
  233. # And test reversal
  234. with connection.schema_editor() as editor:
  235. operation.database_backwards("test_crmoih", editor, new_state, project_state)
  236. self.assertTableNotExists("test_crmoih_shetlandpony")
  237. def test_create_proxy_model(self):
  238. """
  239. CreateModel ignores proxy models.
  240. """
  241. project_state = self.set_up_test_model("test_crprmo")
  242. # Test the state alteration
  243. operation = migrations.CreateModel(
  244. "ProxyPony",
  245. [],
  246. options={"proxy": True},
  247. bases=("test_crprmo.Pony",),
  248. )
  249. self.assertEqual(operation.describe(), "Create proxy model ProxyPony")
  250. new_state = project_state.clone()
  251. operation.state_forwards("test_crprmo", new_state)
  252. self.assertIn(("test_crprmo", "proxypony"), new_state.models)
  253. # Test the database alteration
  254. self.assertTableNotExists("test_crprmo_proxypony")
  255. self.assertTableExists("test_crprmo_pony")
  256. with connection.schema_editor() as editor:
  257. operation.database_forwards("test_crprmo", editor, project_state, new_state)
  258. self.assertTableNotExists("test_crprmo_proxypony")
  259. self.assertTableExists("test_crprmo_pony")
  260. # And test reversal
  261. with connection.schema_editor() as editor:
  262. operation.database_backwards("test_crprmo", editor, new_state, project_state)
  263. self.assertTableNotExists("test_crprmo_proxypony")
  264. self.assertTableExists("test_crprmo_pony")
  265. # And deconstruction
  266. definition = operation.deconstruct()
  267. self.assertEqual(definition[0], "CreateModel")
  268. self.assertEqual(definition[1], [])
  269. self.assertEqual(sorted(definition[2]), ["bases", "fields", "name", "options"])
  270. def test_create_unmanaged_model(self):
  271. """
  272. CreateModel ignores unmanaged models.
  273. """
  274. project_state = self.set_up_test_model("test_crummo")
  275. # Test the state alteration
  276. operation = migrations.CreateModel(
  277. "UnmanagedPony",
  278. [],
  279. options={"proxy": True},
  280. bases=("test_crummo.Pony",),
  281. )
  282. self.assertEqual(operation.describe(), "Create proxy model UnmanagedPony")
  283. new_state = project_state.clone()
  284. operation.state_forwards("test_crummo", new_state)
  285. self.assertIn(("test_crummo", "unmanagedpony"), new_state.models)
  286. # Test the database alteration
  287. self.assertTableNotExists("test_crummo_unmanagedpony")
  288. self.assertTableExists("test_crummo_pony")
  289. with connection.schema_editor() as editor:
  290. operation.database_forwards("test_crummo", editor, project_state, new_state)
  291. self.assertTableNotExists("test_crummo_unmanagedpony")
  292. self.assertTableExists("test_crummo_pony")
  293. # And test reversal
  294. with connection.schema_editor() as editor:
  295. operation.database_backwards("test_crummo", editor, new_state, project_state)
  296. self.assertTableNotExists("test_crummo_unmanagedpony")
  297. self.assertTableExists("test_crummo_pony")
  298. @skipUnlessDBFeature('supports_table_check_constraints')
  299. def test_create_model_with_constraint(self):
  300. where = models.Q(pink__gt=2)
  301. check_constraint = models.CheckConstraint(check=where, name='test_constraint_pony_pink_gt_2')
  302. operation = migrations.CreateModel(
  303. "Pony",
  304. [
  305. ("id", models.AutoField(primary_key=True)),
  306. ("pink", models.IntegerField(default=3)),
  307. ],
  308. options={'constraints': [check_constraint]},
  309. )
  310. # Test the state alteration
  311. project_state = ProjectState()
  312. new_state = project_state.clone()
  313. operation.state_forwards("test_crmo", new_state)
  314. self.assertEqual(len(new_state.models['test_crmo', 'pony'].options['constraints']), 1)
  315. # Test database alteration
  316. self.assertTableNotExists("test_crmo_pony")
  317. with connection.schema_editor() as editor:
  318. operation.database_forwards("test_crmo", editor, project_state, new_state)
  319. self.assertTableExists("test_crmo_pony")
  320. with connection.cursor() as cursor:
  321. with self.assertRaises(IntegrityError):
  322. cursor.execute("INSERT INTO test_crmo_pony (id, pink) VALUES (1, 1)")
  323. # Test reversal
  324. with connection.schema_editor() as editor:
  325. operation.database_backwards("test_crmo", editor, new_state, project_state)
  326. self.assertTableNotExists("test_crmo_pony")
  327. # Test deconstruction
  328. definition = operation.deconstruct()
  329. self.assertEqual(definition[0], "CreateModel")
  330. self.assertEqual(definition[1], [])
  331. self.assertEqual(definition[2]['options']['constraints'], [check_constraint])
  332. def test_create_model_with_partial_unique_constraint(self):
  333. partial_unique_constraint = models.UniqueConstraint(
  334. fields=['pink'],
  335. condition=models.Q(weight__gt=5),
  336. name='test_constraint_pony_pink_for_weight_gt_5_uniq',
  337. )
  338. operation = migrations.CreateModel(
  339. 'Pony',
  340. [
  341. ('id', models.AutoField(primary_key=True)),
  342. ('pink', models.IntegerField(default=3)),
  343. ('weight', models.FloatField()),
  344. ],
  345. options={'constraints': [partial_unique_constraint]},
  346. )
  347. # Test the state alteration
  348. project_state = ProjectState()
  349. new_state = project_state.clone()
  350. operation.state_forwards('test_crmo', new_state)
  351. self.assertEqual(len(new_state.models['test_crmo', 'pony'].options['constraints']), 1)
  352. # Test database alteration
  353. self.assertTableNotExists('test_crmo_pony')
  354. with connection.schema_editor() as editor:
  355. operation.database_forwards('test_crmo', editor, project_state, new_state)
  356. self.assertTableExists('test_crmo_pony')
  357. # Test constraint works
  358. Pony = new_state.apps.get_model('test_crmo', 'Pony')
  359. Pony.objects.create(pink=1, weight=4.0)
  360. Pony.objects.create(pink=1, weight=4.0)
  361. Pony.objects.create(pink=1, weight=6.0)
  362. if connection.features.supports_partial_indexes:
  363. with self.assertRaises(IntegrityError):
  364. Pony.objects.create(pink=1, weight=7.0)
  365. else:
  366. Pony.objects.create(pink=1, weight=7.0)
  367. # Test reversal
  368. with connection.schema_editor() as editor:
  369. operation.database_backwards('test_crmo', editor, new_state, project_state)
  370. self.assertTableNotExists('test_crmo_pony')
  371. # Test deconstruction
  372. definition = operation.deconstruct()
  373. self.assertEqual(definition[0], 'CreateModel')
  374. self.assertEqual(definition[1], [])
  375. self.assertEqual(definition[2]['options']['constraints'], [partial_unique_constraint])
  376. def test_create_model_with_deferred_unique_constraint(self):
  377. deferred_unique_constraint = models.UniqueConstraint(
  378. fields=['pink'],
  379. name='deferrable_pink_constraint',
  380. deferrable=models.Deferrable.DEFERRED,
  381. )
  382. operation = migrations.CreateModel(
  383. 'Pony',
  384. [
  385. ('id', models.AutoField(primary_key=True)),
  386. ('pink', models.IntegerField(default=3)),
  387. ],
  388. options={'constraints': [deferred_unique_constraint]},
  389. )
  390. project_state = ProjectState()
  391. new_state = project_state.clone()
  392. operation.state_forwards('test_crmo', new_state)
  393. self.assertEqual(len(new_state.models['test_crmo', 'pony'].options['constraints']), 1)
  394. self.assertTableNotExists('test_crmo_pony')
  395. # Create table.
  396. with connection.schema_editor() as editor:
  397. operation.database_forwards('test_crmo', editor, project_state, new_state)
  398. self.assertTableExists('test_crmo_pony')
  399. Pony = new_state.apps.get_model('test_crmo', 'Pony')
  400. Pony.objects.create(pink=1)
  401. if connection.features.supports_deferrable_unique_constraints:
  402. # Unique constraint is deferred.
  403. with transaction.atomic():
  404. obj = Pony.objects.create(pink=1)
  405. obj.pink = 2
  406. obj.save()
  407. # Constraint behavior can be changed with SET CONSTRAINTS.
  408. with self.assertRaises(IntegrityError):
  409. with transaction.atomic(), connection.cursor() as cursor:
  410. quoted_name = connection.ops.quote_name(deferred_unique_constraint.name)
  411. cursor.execute('SET CONSTRAINTS %s IMMEDIATE' % quoted_name)
  412. obj = Pony.objects.create(pink=1)
  413. obj.pink = 3
  414. obj.save()
  415. else:
  416. Pony.objects.create(pink=1)
  417. # Reversal.
  418. with connection.schema_editor() as editor:
  419. operation.database_backwards('test_crmo', editor, new_state, project_state)
  420. self.assertTableNotExists('test_crmo_pony')
  421. # Deconstruction.
  422. definition = operation.deconstruct()
  423. self.assertEqual(definition[0], 'CreateModel')
  424. self.assertEqual(definition[1], [])
  425. self.assertEqual(
  426. definition[2]['options']['constraints'],
  427. [deferred_unique_constraint],
  428. )
  429. @skipUnlessDBFeature('supports_covering_indexes')
  430. def test_create_model_with_covering_unique_constraint(self):
  431. covering_unique_constraint = models.UniqueConstraint(
  432. fields=['pink'],
  433. include=['weight'],
  434. name='test_constraint_pony_pink_covering_weight',
  435. )
  436. operation = migrations.CreateModel(
  437. 'Pony',
  438. [
  439. ('id', models.AutoField(primary_key=True)),
  440. ('pink', models.IntegerField(default=3)),
  441. ('weight', models.FloatField()),
  442. ],
  443. options={'constraints': [covering_unique_constraint]},
  444. )
  445. project_state = ProjectState()
  446. new_state = project_state.clone()
  447. operation.state_forwards('test_crmo', new_state)
  448. self.assertEqual(len(new_state.models['test_crmo', 'pony'].options['constraints']), 1)
  449. self.assertTableNotExists('test_crmo_pony')
  450. # Create table.
  451. with connection.schema_editor() as editor:
  452. operation.database_forwards('test_crmo', editor, project_state, new_state)
  453. self.assertTableExists('test_crmo_pony')
  454. Pony = new_state.apps.get_model('test_crmo', 'Pony')
  455. Pony.objects.create(pink=1, weight=4.0)
  456. with self.assertRaises(IntegrityError):
  457. Pony.objects.create(pink=1, weight=7.0)
  458. # Reversal.
  459. with connection.schema_editor() as editor:
  460. operation.database_backwards('test_crmo', editor, new_state, project_state)
  461. self.assertTableNotExists('test_crmo_pony')
  462. # Deconstruction.
  463. definition = operation.deconstruct()
  464. self.assertEqual(definition[0], 'CreateModel')
  465. self.assertEqual(definition[1], [])
  466. self.assertEqual(
  467. definition[2]['options']['constraints'],
  468. [covering_unique_constraint],
  469. )
  470. def test_create_model_managers(self):
  471. """
  472. The managers on a model are set.
  473. """
  474. project_state = self.set_up_test_model("test_cmoma")
  475. # Test the state alteration
  476. operation = migrations.CreateModel(
  477. "Food",
  478. fields=[
  479. ("id", models.AutoField(primary_key=True)),
  480. ],
  481. managers=[
  482. ("food_qs", FoodQuerySet.as_manager()),
  483. ("food_mgr", FoodManager("a", "b")),
  484. ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)),
  485. ]
  486. )
  487. self.assertEqual(operation.describe(), "Create model Food")
  488. new_state = project_state.clone()
  489. operation.state_forwards("test_cmoma", new_state)
  490. self.assertIn(("test_cmoma", "food"), new_state.models)
  491. managers = new_state.models["test_cmoma", "food"].managers
  492. self.assertEqual(managers[0][0], "food_qs")
  493. self.assertIsInstance(managers[0][1], models.Manager)
  494. self.assertEqual(managers[1][0], "food_mgr")
  495. self.assertIsInstance(managers[1][1], FoodManager)
  496. self.assertEqual(managers[1][1].args, ("a", "b", 1, 2))
  497. self.assertEqual(managers[2][0], "food_mgr_kwargs")
  498. self.assertIsInstance(managers[2][1], FoodManager)
  499. self.assertEqual(managers[2][1].args, ("x", "y", 3, 4))
  500. def test_delete_model(self):
  501. """
  502. Tests the DeleteModel operation.
  503. """
  504. project_state = self.set_up_test_model("test_dlmo")
  505. # Test the state alteration
  506. operation = migrations.DeleteModel("Pony")
  507. self.assertEqual(operation.describe(), "Delete model Pony")
  508. self.assertEqual(operation.migration_name_fragment, 'delete_pony')
  509. new_state = project_state.clone()
  510. operation.state_forwards("test_dlmo", new_state)
  511. self.assertNotIn(("test_dlmo", "pony"), new_state.models)
  512. # Test the database alteration
  513. self.assertTableExists("test_dlmo_pony")
  514. with connection.schema_editor() as editor:
  515. operation.database_forwards("test_dlmo", editor, project_state, new_state)
  516. self.assertTableNotExists("test_dlmo_pony")
  517. # And test reversal
  518. with connection.schema_editor() as editor:
  519. operation.database_backwards("test_dlmo", editor, new_state, project_state)
  520. self.assertTableExists("test_dlmo_pony")
  521. # And deconstruction
  522. definition = operation.deconstruct()
  523. self.assertEqual(definition[0], "DeleteModel")
  524. self.assertEqual(definition[1], [])
  525. self.assertEqual(list(definition[2]), ["name"])
  526. def test_delete_proxy_model(self):
  527. """
  528. Tests the DeleteModel operation ignores proxy models.
  529. """
  530. project_state = self.set_up_test_model("test_dlprmo", proxy_model=True)
  531. # Test the state alteration
  532. operation = migrations.DeleteModel("ProxyPony")
  533. new_state = project_state.clone()
  534. operation.state_forwards("test_dlprmo", new_state)
  535. self.assertIn(("test_dlprmo", "proxypony"), project_state.models)
  536. self.assertNotIn(("test_dlprmo", "proxypony"), new_state.models)
  537. # Test the database alteration
  538. self.assertTableExists("test_dlprmo_pony")
  539. self.assertTableNotExists("test_dlprmo_proxypony")
  540. with connection.schema_editor() as editor:
  541. operation.database_forwards("test_dlprmo", editor, project_state, new_state)
  542. self.assertTableExists("test_dlprmo_pony")
  543. self.assertTableNotExists("test_dlprmo_proxypony")
  544. # And test reversal
  545. with connection.schema_editor() as editor:
  546. operation.database_backwards("test_dlprmo", editor, new_state, project_state)
  547. self.assertTableExists("test_dlprmo_pony")
  548. self.assertTableNotExists("test_dlprmo_proxypony")
  549. def test_delete_mti_model(self):
  550. project_state = self.set_up_test_model('test_dlmtimo', mti_model=True)
  551. # Test the state alteration
  552. operation = migrations.DeleteModel('ShetlandPony')
  553. new_state = project_state.clone()
  554. operation.state_forwards('test_dlmtimo', new_state)
  555. self.assertIn(('test_dlmtimo', 'shetlandpony'), project_state.models)
  556. self.assertNotIn(('test_dlmtimo', 'shetlandpony'), new_state.models)
  557. # Test the database alteration
  558. self.assertTableExists('test_dlmtimo_pony')
  559. self.assertTableExists('test_dlmtimo_shetlandpony')
  560. self.assertColumnExists('test_dlmtimo_shetlandpony', 'pony_ptr_id')
  561. with connection.schema_editor() as editor:
  562. operation.database_forwards('test_dlmtimo', editor, project_state, new_state)
  563. self.assertTableExists('test_dlmtimo_pony')
  564. self.assertTableNotExists('test_dlmtimo_shetlandpony')
  565. # And test reversal
  566. with connection.schema_editor() as editor:
  567. operation.database_backwards('test_dlmtimo', editor, new_state, project_state)
  568. self.assertTableExists('test_dlmtimo_pony')
  569. self.assertTableExists('test_dlmtimo_shetlandpony')
  570. self.assertColumnExists('test_dlmtimo_shetlandpony', 'pony_ptr_id')
  571. def test_rename_model(self):
  572. """
  573. Tests the RenameModel operation.
  574. """
  575. project_state = self.set_up_test_model("test_rnmo", related_model=True)
  576. # Test the state alteration
  577. operation = migrations.RenameModel("Pony", "Horse")
  578. self.assertEqual(operation.describe(), "Rename model Pony to Horse")
  579. self.assertEqual(operation.migration_name_fragment, 'rename_pony_horse')
  580. # Test initial state and database
  581. self.assertIn(("test_rnmo", "pony"), project_state.models)
  582. self.assertNotIn(("test_rnmo", "horse"), project_state.models)
  583. self.assertTableExists("test_rnmo_pony")
  584. self.assertTableNotExists("test_rnmo_horse")
  585. if connection.features.supports_foreign_keys:
  586. self.assertFKExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id"))
  587. self.assertFKNotExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id"))
  588. # Migrate forwards
  589. new_state = project_state.clone()
  590. atomic_rename = connection.features.supports_atomic_references_rename
  591. new_state = self.apply_operations("test_rnmo", new_state, [operation], atomic=atomic_rename)
  592. # Test new state and database
  593. self.assertNotIn(("test_rnmo", "pony"), new_state.models)
  594. self.assertIn(("test_rnmo", "horse"), new_state.models)
  595. # RenameModel also repoints all incoming FKs and M2Ms
  596. self.assertEqual(
  597. new_state.models['test_rnmo', 'rider'].fields['pony'].remote_field.model,
  598. 'test_rnmo.Horse',
  599. )
  600. self.assertTableNotExists("test_rnmo_pony")
  601. self.assertTableExists("test_rnmo_horse")
  602. if connection.features.supports_foreign_keys:
  603. self.assertFKNotExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id"))
  604. self.assertFKExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id"))
  605. # Migrate backwards
  606. original_state = self.unapply_operations("test_rnmo", project_state, [operation], atomic=atomic_rename)
  607. # Test original state and database
  608. self.assertIn(("test_rnmo", "pony"), original_state.models)
  609. self.assertNotIn(("test_rnmo", "horse"), original_state.models)
  610. self.assertEqual(
  611. original_state.models['test_rnmo', 'rider'].fields['pony'].remote_field.model,
  612. 'Pony',
  613. )
  614. self.assertTableExists("test_rnmo_pony")
  615. self.assertTableNotExists("test_rnmo_horse")
  616. if connection.features.supports_foreign_keys:
  617. self.assertFKExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id"))
  618. self.assertFKNotExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id"))
  619. # And deconstruction
  620. definition = operation.deconstruct()
  621. self.assertEqual(definition[0], "RenameModel")
  622. self.assertEqual(definition[1], [])
  623. self.assertEqual(definition[2], {'old_name': "Pony", 'new_name': "Horse"})
  624. def test_rename_model_state_forwards(self):
  625. """
  626. RenameModel operations shouldn't trigger the caching of rendered apps
  627. on state without prior apps.
  628. """
  629. state = ProjectState()
  630. state.add_model(ModelState('migrations', 'Foo', []))
  631. operation = migrations.RenameModel('Foo', 'Bar')
  632. operation.state_forwards('migrations', state)
  633. self.assertNotIn('apps', state.__dict__)
  634. self.assertNotIn(('migrations', 'foo'), state.models)
  635. self.assertIn(('migrations', 'bar'), state.models)
  636. # Now with apps cached.
  637. apps = state.apps
  638. operation = migrations.RenameModel('Bar', 'Foo')
  639. operation.state_forwards('migrations', state)
  640. self.assertIs(state.apps, apps)
  641. self.assertNotIn(('migrations', 'bar'), state.models)
  642. self.assertIn(('migrations', 'foo'), state.models)
  643. def test_rename_model_with_self_referential_fk(self):
  644. """
  645. Tests the RenameModel operation on model with self referential FK.
  646. """
  647. project_state = self.set_up_test_model("test_rmwsrf", related_model=True)
  648. # Test the state alteration
  649. operation = migrations.RenameModel("Rider", "HorseRider")
  650. self.assertEqual(operation.describe(), "Rename model Rider to HorseRider")
  651. new_state = project_state.clone()
  652. operation.state_forwards("test_rmwsrf", new_state)
  653. self.assertNotIn(("test_rmwsrf", "rider"), new_state.models)
  654. self.assertIn(("test_rmwsrf", "horserider"), new_state.models)
  655. # Remember, RenameModel also repoints all incoming FKs and M2Ms
  656. self.assertEqual(
  657. 'self',
  658. new_state.models["test_rmwsrf", "horserider"].fields['friend'].remote_field.model
  659. )
  660. HorseRider = new_state.apps.get_model('test_rmwsrf', 'horserider')
  661. self.assertIs(HorseRider._meta.get_field('horserider').remote_field.model, HorseRider)
  662. # Test the database alteration
  663. self.assertTableExists("test_rmwsrf_rider")
  664. self.assertTableNotExists("test_rmwsrf_horserider")
  665. if connection.features.supports_foreign_keys:
  666. self.assertFKExists("test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id"))
  667. self.assertFKNotExists("test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id"))
  668. atomic_rename = connection.features.supports_atomic_references_rename
  669. with connection.schema_editor(atomic=atomic_rename) as editor:
  670. operation.database_forwards("test_rmwsrf", editor, project_state, new_state)
  671. self.assertTableNotExists("test_rmwsrf_rider")
  672. self.assertTableExists("test_rmwsrf_horserider")
  673. if connection.features.supports_foreign_keys:
  674. self.assertFKNotExists("test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_rider", "id"))
  675. self.assertFKExists("test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_horserider", "id"))
  676. # And test reversal
  677. with connection.schema_editor(atomic=atomic_rename) as editor:
  678. operation.database_backwards("test_rmwsrf", editor, new_state, project_state)
  679. self.assertTableExists("test_rmwsrf_rider")
  680. self.assertTableNotExists("test_rmwsrf_horserider")
  681. if connection.features.supports_foreign_keys:
  682. self.assertFKExists("test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id"))
  683. self.assertFKNotExists("test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id"))
  684. def test_rename_model_with_superclass_fk(self):
  685. """
  686. Tests the RenameModel operation on a model which has a superclass that
  687. has a foreign key.
  688. """
  689. project_state = self.set_up_test_model("test_rmwsc", related_model=True, mti_model=True)
  690. # Test the state alteration
  691. operation = migrations.RenameModel("ShetlandPony", "LittleHorse")
  692. self.assertEqual(operation.describe(), "Rename model ShetlandPony to LittleHorse")
  693. new_state = project_state.clone()
  694. operation.state_forwards("test_rmwsc", new_state)
  695. self.assertNotIn(("test_rmwsc", "shetlandpony"), new_state.models)
  696. self.assertIn(("test_rmwsc", "littlehorse"), new_state.models)
  697. # RenameModel shouldn't repoint the superclass's relations, only local ones
  698. self.assertEqual(
  699. project_state.models['test_rmwsc', 'rider'].fields['pony'].remote_field.model,
  700. new_state.models['test_rmwsc', 'rider'].fields['pony'].remote_field.model,
  701. )
  702. # Before running the migration we have a table for Shetland Pony, not Little Horse
  703. self.assertTableExists("test_rmwsc_shetlandpony")
  704. self.assertTableNotExists("test_rmwsc_littlehorse")
  705. if connection.features.supports_foreign_keys:
  706. # and the foreign key on rider points to pony, not shetland pony
  707. self.assertFKExists("test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id"))
  708. self.assertFKNotExists("test_rmwsc_rider", ["pony_id"], ("test_rmwsc_shetlandpony", "id"))
  709. with connection.schema_editor(atomic=connection.features.supports_atomic_references_rename) as editor:
  710. operation.database_forwards("test_rmwsc", editor, project_state, new_state)
  711. # Now we have a little horse table, not shetland pony
  712. self.assertTableNotExists("test_rmwsc_shetlandpony")
  713. self.assertTableExists("test_rmwsc_littlehorse")
  714. if connection.features.supports_foreign_keys:
  715. # but the Foreign keys still point at pony, not little horse
  716. self.assertFKExists("test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id"))
  717. self.assertFKNotExists("test_rmwsc_rider", ["pony_id"], ("test_rmwsc_littlehorse", "id"))
  718. def test_rename_model_with_self_referential_m2m(self):
  719. app_label = "test_rename_model_with_self_referential_m2m"
  720. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  721. migrations.CreateModel("ReflexivePony", fields=[
  722. ("id", models.AutoField(primary_key=True)),
  723. ("ponies", models.ManyToManyField("self")),
  724. ]),
  725. ])
  726. project_state = self.apply_operations(app_label, project_state, operations=[
  727. migrations.RenameModel("ReflexivePony", "ReflexivePony2"),
  728. ], atomic=connection.features.supports_atomic_references_rename)
  729. Pony = project_state.apps.get_model(app_label, "ReflexivePony2")
  730. pony = Pony.objects.create()
  731. pony.ponies.add(pony)
  732. def test_rename_model_with_m2m(self):
  733. app_label = "test_rename_model_with_m2m"
  734. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  735. migrations.CreateModel("Rider", fields=[
  736. ("id", models.AutoField(primary_key=True)),
  737. ]),
  738. migrations.CreateModel("Pony", fields=[
  739. ("id", models.AutoField(primary_key=True)),
  740. ("riders", models.ManyToManyField("Rider")),
  741. ]),
  742. ])
  743. Pony = project_state.apps.get_model(app_label, "Pony")
  744. Rider = project_state.apps.get_model(app_label, "Rider")
  745. pony = Pony.objects.create()
  746. rider = Rider.objects.create()
  747. pony.riders.add(rider)
  748. project_state = self.apply_operations(app_label, project_state, operations=[
  749. migrations.RenameModel("Pony", "Pony2"),
  750. ], atomic=connection.features.supports_atomic_references_rename)
  751. Pony = project_state.apps.get_model(app_label, "Pony2")
  752. Rider = project_state.apps.get_model(app_label, "Rider")
  753. pony = Pony.objects.create()
  754. rider = Rider.objects.create()
  755. pony.riders.add(rider)
  756. self.assertEqual(Pony.objects.count(), 2)
  757. self.assertEqual(Rider.objects.count(), 2)
  758. self.assertEqual(Pony._meta.get_field('riders').remote_field.through.objects.count(), 2)
  759. def test_rename_m2m_target_model(self):
  760. app_label = "test_rename_m2m_target_model"
  761. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  762. migrations.CreateModel("Rider", fields=[
  763. ("id", models.AutoField(primary_key=True)),
  764. ]),
  765. migrations.CreateModel("Pony", fields=[
  766. ("id", models.AutoField(primary_key=True)),
  767. ("riders", models.ManyToManyField("Rider")),
  768. ]),
  769. ])
  770. Pony = project_state.apps.get_model(app_label, "Pony")
  771. Rider = project_state.apps.get_model(app_label, "Rider")
  772. pony = Pony.objects.create()
  773. rider = Rider.objects.create()
  774. pony.riders.add(rider)
  775. project_state = self.apply_operations(app_label, project_state, operations=[
  776. migrations.RenameModel("Rider", "Rider2"),
  777. ], atomic=connection.features.supports_atomic_references_rename)
  778. Pony = project_state.apps.get_model(app_label, "Pony")
  779. Rider = project_state.apps.get_model(app_label, "Rider2")
  780. pony = Pony.objects.create()
  781. rider = Rider.objects.create()
  782. pony.riders.add(rider)
  783. self.assertEqual(Pony.objects.count(), 2)
  784. self.assertEqual(Rider.objects.count(), 2)
  785. self.assertEqual(Pony._meta.get_field('riders').remote_field.through.objects.count(), 2)
  786. def test_rename_m2m_through_model(self):
  787. app_label = "test_rename_through"
  788. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  789. migrations.CreateModel("Rider", fields=[
  790. ("id", models.AutoField(primary_key=True)),
  791. ]),
  792. migrations.CreateModel("Pony", fields=[
  793. ("id", models.AutoField(primary_key=True)),
  794. ]),
  795. migrations.CreateModel("PonyRider", fields=[
  796. ("id", models.AutoField(primary_key=True)),
  797. ("rider", models.ForeignKey("test_rename_through.Rider", models.CASCADE)),
  798. ("pony", models.ForeignKey("test_rename_through.Pony", models.CASCADE)),
  799. ]),
  800. migrations.AddField(
  801. "Pony",
  802. "riders",
  803. models.ManyToManyField("test_rename_through.Rider", through="test_rename_through.PonyRider"),
  804. ),
  805. ])
  806. Pony = project_state.apps.get_model(app_label, "Pony")
  807. Rider = project_state.apps.get_model(app_label, "Rider")
  808. PonyRider = project_state.apps.get_model(app_label, "PonyRider")
  809. pony = Pony.objects.create()
  810. rider = Rider.objects.create()
  811. PonyRider.objects.create(pony=pony, rider=rider)
  812. project_state = self.apply_operations(app_label, project_state, operations=[
  813. migrations.RenameModel("PonyRider", "PonyRider2"),
  814. ])
  815. Pony = project_state.apps.get_model(app_label, "Pony")
  816. Rider = project_state.apps.get_model(app_label, "Rider")
  817. PonyRider = project_state.apps.get_model(app_label, "PonyRider2")
  818. pony = Pony.objects.first()
  819. rider = Rider.objects.create()
  820. PonyRider.objects.create(pony=pony, rider=rider)
  821. self.assertEqual(Pony.objects.count(), 1)
  822. self.assertEqual(Rider.objects.count(), 2)
  823. self.assertEqual(PonyRider.objects.count(), 2)
  824. self.assertEqual(pony.riders.count(), 2)
  825. def test_rename_m2m_model_after_rename_field(self):
  826. """RenameModel renames a many-to-many column after a RenameField."""
  827. app_label = 'test_rename_multiple'
  828. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  829. migrations.CreateModel('Pony', fields=[
  830. ('id', models.AutoField(primary_key=True)),
  831. ('name', models.CharField(max_length=20)),
  832. ]),
  833. migrations.CreateModel('Rider', fields=[
  834. ('id', models.AutoField(primary_key=True)),
  835. ('pony', models.ForeignKey('test_rename_multiple.Pony', models.CASCADE)),
  836. ]),
  837. migrations.CreateModel('PonyRider', fields=[
  838. ('id', models.AutoField(primary_key=True)),
  839. ('riders', models.ManyToManyField('Rider')),
  840. ]),
  841. migrations.RenameField(model_name='pony', old_name='name', new_name='fancy_name'),
  842. migrations.RenameModel(old_name='Rider', new_name='Jockey'),
  843. ], atomic=connection.features.supports_atomic_references_rename)
  844. Pony = project_state.apps.get_model(app_label, 'Pony')
  845. Jockey = project_state.apps.get_model(app_label, 'Jockey')
  846. PonyRider = project_state.apps.get_model(app_label, 'PonyRider')
  847. # No "no such column" error means the column was renamed correctly.
  848. pony = Pony.objects.create(fancy_name='a good name')
  849. jockey = Jockey.objects.create(pony=pony)
  850. ponyrider = PonyRider.objects.create()
  851. ponyrider.riders.add(jockey)
  852. def test_add_field(self):
  853. """
  854. Tests the AddField operation.
  855. """
  856. # Test the state alteration
  857. operation = migrations.AddField(
  858. "Pony",
  859. "height",
  860. models.FloatField(null=True, default=5),
  861. )
  862. self.assertEqual(operation.describe(), "Add field height to Pony")
  863. self.assertEqual(operation.migration_name_fragment, 'pony_height')
  864. project_state, new_state = self.make_test_state("test_adfl", operation)
  865. self.assertEqual(len(new_state.models["test_adfl", "pony"].fields), 4)
  866. field = new_state.models['test_adfl', 'pony'].fields['height']
  867. self.assertEqual(field.default, 5)
  868. # Test the database alteration
  869. self.assertColumnNotExists("test_adfl_pony", "height")
  870. with connection.schema_editor() as editor:
  871. operation.database_forwards("test_adfl", editor, project_state, new_state)
  872. self.assertColumnExists("test_adfl_pony", "height")
  873. # And test reversal
  874. with connection.schema_editor() as editor:
  875. operation.database_backwards("test_adfl", editor, new_state, project_state)
  876. self.assertColumnNotExists("test_adfl_pony", "height")
  877. # And deconstruction
  878. definition = operation.deconstruct()
  879. self.assertEqual(definition[0], "AddField")
  880. self.assertEqual(definition[1], [])
  881. self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"])
  882. def test_add_charfield(self):
  883. """
  884. Tests the AddField operation on TextField.
  885. """
  886. project_state = self.set_up_test_model("test_adchfl")
  887. Pony = project_state.apps.get_model("test_adchfl", "Pony")
  888. pony = Pony.objects.create(weight=42)
  889. new_state = self.apply_operations("test_adchfl", project_state, [
  890. migrations.AddField(
  891. "Pony",
  892. "text",
  893. models.CharField(max_length=10, default="some text"),
  894. ),
  895. migrations.AddField(
  896. "Pony",
  897. "empty",
  898. models.CharField(max_length=10, default=""),
  899. ),
  900. # If not properly quoted digits would be interpreted as an int.
  901. migrations.AddField(
  902. "Pony",
  903. "digits",
  904. models.CharField(max_length=10, default="42"),
  905. ),
  906. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  907. migrations.AddField(
  908. "Pony",
  909. "quotes",
  910. models.CharField(max_length=10, default='"\'"'),
  911. ),
  912. ])
  913. Pony = new_state.apps.get_model("test_adchfl", "Pony")
  914. pony = Pony.objects.get(pk=pony.pk)
  915. self.assertEqual(pony.text, "some text")
  916. self.assertEqual(pony.empty, "")
  917. self.assertEqual(pony.digits, "42")
  918. self.assertEqual(pony.quotes, '"\'"')
  919. def test_add_textfield(self):
  920. """
  921. Tests the AddField operation on TextField.
  922. """
  923. project_state = self.set_up_test_model("test_adtxtfl")
  924. Pony = project_state.apps.get_model("test_adtxtfl", "Pony")
  925. pony = Pony.objects.create(weight=42)
  926. new_state = self.apply_operations("test_adtxtfl", project_state, [
  927. migrations.AddField(
  928. "Pony",
  929. "text",
  930. models.TextField(default="some text"),
  931. ),
  932. migrations.AddField(
  933. "Pony",
  934. "empty",
  935. models.TextField(default=""),
  936. ),
  937. # If not properly quoted digits would be interpreted as an int.
  938. migrations.AddField(
  939. "Pony",
  940. "digits",
  941. models.TextField(default="42"),
  942. ),
  943. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  944. migrations.AddField(
  945. "Pony",
  946. "quotes",
  947. models.TextField(default='"\'"'),
  948. ),
  949. ])
  950. Pony = new_state.apps.get_model("test_adtxtfl", "Pony")
  951. pony = Pony.objects.get(pk=pony.pk)
  952. self.assertEqual(pony.text, "some text")
  953. self.assertEqual(pony.empty, "")
  954. self.assertEqual(pony.digits, "42")
  955. self.assertEqual(pony.quotes, '"\'"')
  956. def test_add_binaryfield(self):
  957. """
  958. Tests the AddField operation on TextField/BinaryField.
  959. """
  960. project_state = self.set_up_test_model("test_adbinfl")
  961. Pony = project_state.apps.get_model("test_adbinfl", "Pony")
  962. pony = Pony.objects.create(weight=42)
  963. new_state = self.apply_operations("test_adbinfl", project_state, [
  964. migrations.AddField(
  965. "Pony",
  966. "blob",
  967. models.BinaryField(default=b"some text"),
  968. ),
  969. migrations.AddField(
  970. "Pony",
  971. "empty",
  972. models.BinaryField(default=b""),
  973. ),
  974. # If not properly quoted digits would be interpreted as an int.
  975. migrations.AddField(
  976. "Pony",
  977. "digits",
  978. models.BinaryField(default=b"42"),
  979. ),
  980. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  981. migrations.AddField(
  982. "Pony",
  983. "quotes",
  984. models.BinaryField(default=b'"\'"'),
  985. ),
  986. ])
  987. Pony = new_state.apps.get_model("test_adbinfl", "Pony")
  988. pony = Pony.objects.get(pk=pony.pk)
  989. # SQLite returns buffer/memoryview, cast to bytes for checking.
  990. self.assertEqual(bytes(pony.blob), b"some text")
  991. self.assertEqual(bytes(pony.empty), b"")
  992. self.assertEqual(bytes(pony.digits), b"42")
  993. self.assertEqual(bytes(pony.quotes), b'"\'"')
  994. def test_column_name_quoting(self):
  995. """
  996. Column names that are SQL keywords shouldn't cause problems when used
  997. in migrations (#22168).
  998. """
  999. project_state = self.set_up_test_model("test_regr22168")
  1000. operation = migrations.AddField(
  1001. "Pony",
  1002. "order",
  1003. models.IntegerField(default=0),
  1004. )
  1005. new_state = project_state.clone()
  1006. operation.state_forwards("test_regr22168", new_state)
  1007. with connection.schema_editor() as editor:
  1008. operation.database_forwards("test_regr22168", editor, project_state, new_state)
  1009. self.assertColumnExists("test_regr22168_pony", "order")
  1010. def test_add_field_preserve_default(self):
  1011. """
  1012. Tests the AddField operation's state alteration
  1013. when preserve_default = False.
  1014. """
  1015. project_state = self.set_up_test_model("test_adflpd")
  1016. # Test the state alteration
  1017. operation = migrations.AddField(
  1018. "Pony",
  1019. "height",
  1020. models.FloatField(null=True, default=4),
  1021. preserve_default=False,
  1022. )
  1023. new_state = project_state.clone()
  1024. operation.state_forwards("test_adflpd", new_state)
  1025. self.assertEqual(len(new_state.models["test_adflpd", "pony"].fields), 4)
  1026. field = new_state.models['test_adflpd', 'pony'].fields['height']
  1027. self.assertEqual(field.default, models.NOT_PROVIDED)
  1028. # Test the database alteration
  1029. project_state.apps.get_model("test_adflpd", "pony").objects.create(
  1030. weight=4,
  1031. )
  1032. self.assertColumnNotExists("test_adflpd_pony", "height")
  1033. with connection.schema_editor() as editor:
  1034. operation.database_forwards("test_adflpd", editor, project_state, new_state)
  1035. self.assertColumnExists("test_adflpd_pony", "height")
  1036. # And deconstruction
  1037. definition = operation.deconstruct()
  1038. self.assertEqual(definition[0], "AddField")
  1039. self.assertEqual(definition[1], [])
  1040. self.assertEqual(sorted(definition[2]), ["field", "model_name", "name", "preserve_default"])
  1041. def test_add_field_m2m(self):
  1042. """
  1043. Tests the AddField operation with a ManyToManyField.
  1044. """
  1045. project_state = self.set_up_test_model("test_adflmm", second_model=True)
  1046. # Test the state alteration
  1047. operation = migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
  1048. new_state = project_state.clone()
  1049. operation.state_forwards("test_adflmm", new_state)
  1050. self.assertEqual(len(new_state.models["test_adflmm", "pony"].fields), 4)
  1051. # Test the database alteration
  1052. self.assertTableNotExists("test_adflmm_pony_stables")
  1053. with connection.schema_editor() as editor:
  1054. operation.database_forwards("test_adflmm", editor, project_state, new_state)
  1055. self.assertTableExists("test_adflmm_pony_stables")
  1056. self.assertColumnNotExists("test_adflmm_pony", "stables")
  1057. # Make sure the M2M field actually works
  1058. with atomic():
  1059. Pony = new_state.apps.get_model("test_adflmm", "Pony")
  1060. p = Pony.objects.create(pink=False, weight=4.55)
  1061. p.stables.create()
  1062. self.assertEqual(p.stables.count(), 1)
  1063. p.stables.all().delete()
  1064. # And test reversal
  1065. with connection.schema_editor() as editor:
  1066. operation.database_backwards("test_adflmm", editor, new_state, project_state)
  1067. self.assertTableNotExists("test_adflmm_pony_stables")
  1068. def test_alter_field_m2m(self):
  1069. project_state = self.set_up_test_model("test_alflmm", second_model=True)
  1070. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  1071. migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
  1072. ])
  1073. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1074. self.assertFalse(Pony._meta.get_field('stables').blank)
  1075. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  1076. migrations.AlterField(
  1077. "Pony", "stables", models.ManyToManyField(to="Stable", related_name="ponies", blank=True)
  1078. )
  1079. ])
  1080. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1081. self.assertTrue(Pony._meta.get_field('stables').blank)
  1082. def test_repoint_field_m2m(self):
  1083. project_state = self.set_up_test_model("test_alflmm", second_model=True, third_model=True)
  1084. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  1085. migrations.AddField("Pony", "places", models.ManyToManyField("Stable", related_name="ponies"))
  1086. ])
  1087. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1088. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  1089. migrations.AlterField("Pony", "places", models.ManyToManyField(to="Van", related_name="ponies"))
  1090. ])
  1091. # Ensure the new field actually works
  1092. Pony = project_state.apps.get_model("test_alflmm", "Pony")
  1093. p = Pony.objects.create(pink=False, weight=4.55)
  1094. p.places.create()
  1095. self.assertEqual(p.places.count(), 1)
  1096. p.places.all().delete()
  1097. def test_remove_field_m2m(self):
  1098. project_state = self.set_up_test_model("test_rmflmm", second_model=True)
  1099. project_state = self.apply_operations("test_rmflmm", project_state, operations=[
  1100. migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
  1101. ])
  1102. self.assertTableExists("test_rmflmm_pony_stables")
  1103. with_field_state = project_state.clone()
  1104. operations = [migrations.RemoveField("Pony", "stables")]
  1105. project_state = self.apply_operations("test_rmflmm", project_state, operations=operations)
  1106. self.assertTableNotExists("test_rmflmm_pony_stables")
  1107. # And test reversal
  1108. self.unapply_operations("test_rmflmm", with_field_state, operations=operations)
  1109. self.assertTableExists("test_rmflmm_pony_stables")
  1110. def test_remove_field_m2m_with_through(self):
  1111. project_state = self.set_up_test_model("test_rmflmmwt", second_model=True)
  1112. self.assertTableNotExists("test_rmflmmwt_ponystables")
  1113. project_state = self.apply_operations("test_rmflmmwt", project_state, operations=[
  1114. migrations.CreateModel("PonyStables", fields=[
  1115. ("pony", models.ForeignKey('test_rmflmmwt.Pony', models.CASCADE)),
  1116. ("stable", models.ForeignKey('test_rmflmmwt.Stable', models.CASCADE)),
  1117. ]),
  1118. migrations.AddField(
  1119. "Pony", "stables",
  1120. models.ManyToManyField("Stable", related_name="ponies", through='test_rmflmmwt.PonyStables')
  1121. )
  1122. ])
  1123. self.assertTableExists("test_rmflmmwt_ponystables")
  1124. operations = [migrations.RemoveField("Pony", "stables"), migrations.DeleteModel("PonyStables")]
  1125. self.apply_operations("test_rmflmmwt", project_state, operations=operations)
  1126. def test_remove_field(self):
  1127. """
  1128. Tests the RemoveField operation.
  1129. """
  1130. project_state = self.set_up_test_model("test_rmfl")
  1131. # Test the state alteration
  1132. operation = migrations.RemoveField("Pony", "pink")
  1133. self.assertEqual(operation.describe(), "Remove field pink from Pony")
  1134. self.assertEqual(operation.migration_name_fragment, 'remove_pony_pink')
  1135. new_state = project_state.clone()
  1136. operation.state_forwards("test_rmfl", new_state)
  1137. self.assertEqual(len(new_state.models["test_rmfl", "pony"].fields), 2)
  1138. # Test the database alteration
  1139. self.assertColumnExists("test_rmfl_pony", "pink")
  1140. with connection.schema_editor() as editor:
  1141. operation.database_forwards("test_rmfl", editor, project_state, new_state)
  1142. self.assertColumnNotExists("test_rmfl_pony", "pink")
  1143. # And test reversal
  1144. with connection.schema_editor() as editor:
  1145. operation.database_backwards("test_rmfl", editor, new_state, project_state)
  1146. self.assertColumnExists("test_rmfl_pony", "pink")
  1147. # And deconstruction
  1148. definition = operation.deconstruct()
  1149. self.assertEqual(definition[0], "RemoveField")
  1150. self.assertEqual(definition[1], [])
  1151. self.assertEqual(definition[2], {'model_name': "Pony", 'name': 'pink'})
  1152. def test_remove_fk(self):
  1153. """
  1154. Tests the RemoveField operation on a foreign key.
  1155. """
  1156. project_state = self.set_up_test_model("test_rfk", related_model=True)
  1157. self.assertColumnExists("test_rfk_rider", "pony_id")
  1158. operation = migrations.RemoveField("Rider", "pony")
  1159. new_state = project_state.clone()
  1160. operation.state_forwards("test_rfk", new_state)
  1161. with connection.schema_editor() as editor:
  1162. operation.database_forwards("test_rfk", editor, project_state, new_state)
  1163. self.assertColumnNotExists("test_rfk_rider", "pony_id")
  1164. with connection.schema_editor() as editor:
  1165. operation.database_backwards("test_rfk", editor, new_state, project_state)
  1166. self.assertColumnExists("test_rfk_rider", "pony_id")
  1167. def test_alter_model_table(self):
  1168. """
  1169. Tests the AlterModelTable operation.
  1170. """
  1171. project_state = self.set_up_test_model("test_almota")
  1172. # Test the state alteration
  1173. operation = migrations.AlterModelTable("Pony", "test_almota_pony_2")
  1174. self.assertEqual(operation.describe(), "Rename table for Pony to test_almota_pony_2")
  1175. self.assertEqual(operation.migration_name_fragment, 'alter_pony_table')
  1176. new_state = project_state.clone()
  1177. operation.state_forwards("test_almota", new_state)
  1178. self.assertEqual(new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony_2")
  1179. # Test the database alteration
  1180. self.assertTableExists("test_almota_pony")
  1181. self.assertTableNotExists("test_almota_pony_2")
  1182. with connection.schema_editor() as editor:
  1183. operation.database_forwards("test_almota", editor, project_state, new_state)
  1184. self.assertTableNotExists("test_almota_pony")
  1185. self.assertTableExists("test_almota_pony_2")
  1186. # And test reversal
  1187. with connection.schema_editor() as editor:
  1188. operation.database_backwards("test_almota", editor, new_state, project_state)
  1189. self.assertTableExists("test_almota_pony")
  1190. self.assertTableNotExists("test_almota_pony_2")
  1191. # And deconstruction
  1192. definition = operation.deconstruct()
  1193. self.assertEqual(definition[0], "AlterModelTable")
  1194. self.assertEqual(definition[1], [])
  1195. self.assertEqual(definition[2], {'name': "Pony", 'table': "test_almota_pony_2"})
  1196. def test_alter_model_table_none(self):
  1197. """
  1198. Tests the AlterModelTable operation if the table name is set to None.
  1199. """
  1200. operation = migrations.AlterModelTable("Pony", None)
  1201. self.assertEqual(operation.describe(), "Rename table for Pony to (default)")
  1202. def test_alter_model_table_noop(self):
  1203. """
  1204. Tests the AlterModelTable operation if the table name is not changed.
  1205. """
  1206. project_state = self.set_up_test_model("test_almota")
  1207. # Test the state alteration
  1208. operation = migrations.AlterModelTable("Pony", "test_almota_pony")
  1209. new_state = project_state.clone()
  1210. operation.state_forwards("test_almota", new_state)
  1211. self.assertEqual(new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony")
  1212. # Test the database alteration
  1213. self.assertTableExists("test_almota_pony")
  1214. with connection.schema_editor() as editor:
  1215. operation.database_forwards("test_almota", editor, project_state, new_state)
  1216. self.assertTableExists("test_almota_pony")
  1217. # And test reversal
  1218. with connection.schema_editor() as editor:
  1219. operation.database_backwards("test_almota", editor, new_state, project_state)
  1220. self.assertTableExists("test_almota_pony")
  1221. def test_alter_model_table_m2m(self):
  1222. """
  1223. AlterModelTable should rename auto-generated M2M tables.
  1224. """
  1225. app_label = "test_talflmltlm2m"
  1226. pony_db_table = 'pony_foo'
  1227. project_state = self.set_up_test_model(app_label, second_model=True, db_table=pony_db_table)
  1228. # Add the M2M field
  1229. first_state = project_state.clone()
  1230. operation = migrations.AddField("Pony", "stables", models.ManyToManyField("Stable"))
  1231. operation.state_forwards(app_label, first_state)
  1232. with connection.schema_editor() as editor:
  1233. operation.database_forwards(app_label, editor, project_state, first_state)
  1234. original_m2m_table = "%s_%s" % (pony_db_table, "stables")
  1235. new_m2m_table = "%s_%s" % (app_label, "pony_stables")
  1236. self.assertTableExists(original_m2m_table)
  1237. self.assertTableNotExists(new_m2m_table)
  1238. # Rename the Pony db_table which should also rename the m2m table.
  1239. second_state = first_state.clone()
  1240. operation = migrations.AlterModelTable(name='pony', table=None)
  1241. operation.state_forwards(app_label, second_state)
  1242. atomic_rename = connection.features.supports_atomic_references_rename
  1243. with connection.schema_editor(atomic=atomic_rename) as editor:
  1244. operation.database_forwards(app_label, editor, first_state, second_state)
  1245. self.assertTableExists(new_m2m_table)
  1246. self.assertTableNotExists(original_m2m_table)
  1247. # And test reversal
  1248. with connection.schema_editor(atomic=atomic_rename) as editor:
  1249. operation.database_backwards(app_label, editor, second_state, first_state)
  1250. self.assertTableExists(original_m2m_table)
  1251. self.assertTableNotExists(new_m2m_table)
  1252. def test_alter_field(self):
  1253. """
  1254. Tests the AlterField operation.
  1255. """
  1256. project_state = self.set_up_test_model("test_alfl")
  1257. # Test the state alteration
  1258. operation = migrations.AlterField("Pony", "pink", models.IntegerField(null=True))
  1259. self.assertEqual(operation.describe(), "Alter field pink on Pony")
  1260. self.assertEqual(operation.migration_name_fragment, 'alter_pony_pink')
  1261. new_state = project_state.clone()
  1262. operation.state_forwards("test_alfl", new_state)
  1263. self.assertIs(project_state.models['test_alfl', 'pony'].fields['pink'].null, False)
  1264. self.assertIs(new_state.models['test_alfl', 'pony'].fields['pink'].null, True)
  1265. # Test the database alteration
  1266. self.assertColumnNotNull("test_alfl_pony", "pink")
  1267. with connection.schema_editor() as editor:
  1268. operation.database_forwards("test_alfl", editor, project_state, new_state)
  1269. self.assertColumnNull("test_alfl_pony", "pink")
  1270. # And test reversal
  1271. with connection.schema_editor() as editor:
  1272. operation.database_backwards("test_alfl", editor, new_state, project_state)
  1273. self.assertColumnNotNull("test_alfl_pony", "pink")
  1274. # And deconstruction
  1275. definition = operation.deconstruct()
  1276. self.assertEqual(definition[0], "AlterField")
  1277. self.assertEqual(definition[1], [])
  1278. self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"])
  1279. def test_alter_field_pk(self):
  1280. """
  1281. Tests the AlterField operation on primary keys (for things like PostgreSQL's SERIAL weirdness)
  1282. """
  1283. project_state = self.set_up_test_model("test_alflpk")
  1284. # Test the state alteration
  1285. operation = migrations.AlterField("Pony", "id", models.IntegerField(primary_key=True))
  1286. new_state = project_state.clone()
  1287. operation.state_forwards("test_alflpk", new_state)
  1288. self.assertIsInstance(
  1289. project_state.models['test_alflpk', 'pony'].fields['id'],
  1290. models.AutoField,
  1291. )
  1292. self.assertIsInstance(
  1293. new_state.models['test_alflpk', 'pony'].fields['id'],
  1294. models.IntegerField,
  1295. )
  1296. # Test the database alteration
  1297. with connection.schema_editor() as editor:
  1298. operation.database_forwards("test_alflpk", editor, project_state, new_state)
  1299. # And test reversal
  1300. with connection.schema_editor() as editor:
  1301. operation.database_backwards("test_alflpk", editor, new_state, project_state)
  1302. @skipUnlessDBFeature('supports_foreign_keys')
  1303. def test_alter_field_pk_fk(self):
  1304. """
  1305. Tests the AlterField operation on primary keys changes any FKs pointing to it.
  1306. """
  1307. project_state = self.set_up_test_model("test_alflpkfk", related_model=True)
  1308. project_state = self.apply_operations('test_alflpkfk', project_state, [
  1309. migrations.CreateModel('Stable', fields=[
  1310. ('ponies', models.ManyToManyField('Pony')),
  1311. ]),
  1312. migrations.AddField(
  1313. 'Pony',
  1314. 'stables',
  1315. models.ManyToManyField('Stable'),
  1316. ),
  1317. ])
  1318. # Test the state alteration
  1319. operation = migrations.AlterField("Pony", "id", models.FloatField(primary_key=True))
  1320. new_state = project_state.clone()
  1321. operation.state_forwards("test_alflpkfk", new_state)
  1322. self.assertIsInstance(
  1323. project_state.models['test_alflpkfk', 'pony'].fields['id'],
  1324. models.AutoField,
  1325. )
  1326. self.assertIsInstance(
  1327. new_state.models['test_alflpkfk', 'pony'].fields['id'],
  1328. models.FloatField,
  1329. )
  1330. def assertIdTypeEqualsFkType():
  1331. with connection.cursor() as cursor:
  1332. id_type, id_null = [
  1333. (c.type_code, c.null_ok)
  1334. for c in connection.introspection.get_table_description(cursor, "test_alflpkfk_pony")
  1335. if c.name == "id"
  1336. ][0]
  1337. fk_type, fk_null = [
  1338. (c.type_code, c.null_ok)
  1339. for c in connection.introspection.get_table_description(cursor, "test_alflpkfk_rider")
  1340. if c.name == "pony_id"
  1341. ][0]
  1342. m2m_fk_type, m2m_fk_null = [
  1343. (c.type_code, c.null_ok)
  1344. for c in connection.introspection.get_table_description(
  1345. cursor,
  1346. 'test_alflpkfk_pony_stables',
  1347. ) if c.name == 'pony_id'
  1348. ][0]
  1349. remote_m2m_fk_type, remote_m2m_fk_null = [
  1350. (c.type_code, c.null_ok)
  1351. for c in connection.introspection.get_table_description(
  1352. cursor,
  1353. 'test_alflpkfk_stable_ponies',
  1354. ) if c.name == 'pony_id'
  1355. ][0]
  1356. self.assertEqual(id_type, fk_type)
  1357. self.assertEqual(id_type, m2m_fk_type)
  1358. self.assertEqual(id_type, remote_m2m_fk_type)
  1359. self.assertEqual(id_null, fk_null)
  1360. self.assertEqual(id_null, m2m_fk_null)
  1361. self.assertEqual(id_null, remote_m2m_fk_null)
  1362. assertIdTypeEqualsFkType()
  1363. # Test the database alteration
  1364. with connection.schema_editor() as editor:
  1365. operation.database_forwards("test_alflpkfk", editor, project_state, new_state)
  1366. assertIdTypeEqualsFkType()
  1367. # And test reversal
  1368. with connection.schema_editor() as editor:
  1369. operation.database_backwards("test_alflpkfk", editor, new_state, project_state)
  1370. assertIdTypeEqualsFkType()
  1371. @skipUnlessDBFeature('supports_foreign_keys')
  1372. def test_alter_field_reloads_state_on_fk_with_to_field_target_type_change(self):
  1373. app_label = 'test_alflrsfkwtflttc'
  1374. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  1375. migrations.CreateModel('Rider', fields=[
  1376. ('id', models.AutoField(primary_key=True)),
  1377. ('code', models.IntegerField(unique=True)),
  1378. ]),
  1379. migrations.CreateModel('Pony', fields=[
  1380. ('id', models.AutoField(primary_key=True)),
  1381. ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE, to_field='code')),
  1382. ]),
  1383. ])
  1384. operation = migrations.AlterField(
  1385. 'Rider',
  1386. 'code',
  1387. models.CharField(max_length=100, unique=True),
  1388. )
  1389. self.apply_operations(app_label, project_state, operations=[operation])
  1390. id_type, id_null = [
  1391. (c.type_code, c.null_ok)
  1392. for c in self.get_table_description('%s_rider' % app_label)
  1393. if c.name == 'code'
  1394. ][0]
  1395. fk_type, fk_null = [
  1396. (c.type_code, c.null_ok)
  1397. for c in self.get_table_description('%s_pony' % app_label)
  1398. if c.name == 'rider_id'
  1399. ][0]
  1400. self.assertEqual(id_type, fk_type)
  1401. self.assertEqual(id_null, fk_null)
  1402. @skipUnlessDBFeature('supports_foreign_keys')
  1403. def test_alter_field_reloads_state_on_fk_with_to_field_related_name_target_type_change(self):
  1404. app_label = 'test_alflrsfkwtflrnttc'
  1405. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  1406. migrations.CreateModel('Rider', fields=[
  1407. ('id', models.AutoField(primary_key=True)),
  1408. ('code', models.PositiveIntegerField(unique=True)),
  1409. ]),
  1410. migrations.CreateModel('Pony', fields=[
  1411. ('id', models.AutoField(primary_key=True)),
  1412. ('rider', models.ForeignKey(
  1413. '%s.Rider' % app_label,
  1414. models.CASCADE,
  1415. to_field='code',
  1416. related_name='+',
  1417. )),
  1418. ]),
  1419. ])
  1420. operation = migrations.AlterField(
  1421. 'Rider',
  1422. 'code',
  1423. models.CharField(max_length=100, unique=True),
  1424. )
  1425. self.apply_operations(app_label, project_state, operations=[operation])
  1426. def test_alter_field_reloads_state_on_fk_target_changes(self):
  1427. """
  1428. If AlterField doesn't reload state appropriately, the second AlterField
  1429. crashes on MySQL due to not dropping the PonyRider.pony foreign key
  1430. constraint before modifying the column.
  1431. """
  1432. app_label = 'alter_alter_field_reloads_state_on_fk_target_changes'
  1433. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  1434. migrations.CreateModel('Rider', fields=[
  1435. ('id', models.CharField(primary_key=True, max_length=100)),
  1436. ]),
  1437. migrations.CreateModel('Pony', fields=[
  1438. ('id', models.CharField(primary_key=True, max_length=100)),
  1439. ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE)),
  1440. ]),
  1441. migrations.CreateModel('PonyRider', fields=[
  1442. ('id', models.AutoField(primary_key=True)),
  1443. ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE)),
  1444. ]),
  1445. ])
  1446. project_state = self.apply_operations(app_label, project_state, operations=[
  1447. migrations.AlterField('Rider', 'id', models.CharField(primary_key=True, max_length=99)),
  1448. migrations.AlterField('Pony', 'id', models.CharField(primary_key=True, max_length=99)),
  1449. ])
  1450. def test_alter_field_reloads_state_on_fk_with_to_field_target_changes(self):
  1451. """
  1452. If AlterField doesn't reload state appropriately, the second AlterField
  1453. crashes on MySQL due to not dropping the PonyRider.pony foreign key
  1454. constraint before modifying the column.
  1455. """
  1456. app_label = 'alter_alter_field_reloads_state_on_fk_with_to_field_target_changes'
  1457. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  1458. migrations.CreateModel('Rider', fields=[
  1459. ('id', models.CharField(primary_key=True, max_length=100)),
  1460. ('slug', models.CharField(unique=True, max_length=100)),
  1461. ]),
  1462. migrations.CreateModel('Pony', fields=[
  1463. ('id', models.CharField(primary_key=True, max_length=100)),
  1464. ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE, to_field='slug')),
  1465. ('slug', models.CharField(unique=True, max_length=100)),
  1466. ]),
  1467. migrations.CreateModel('PonyRider', fields=[
  1468. ('id', models.AutoField(primary_key=True)),
  1469. ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE, to_field='slug')),
  1470. ]),
  1471. ])
  1472. project_state = self.apply_operations(app_label, project_state, operations=[
  1473. migrations.AlterField('Rider', 'slug', models.CharField(unique=True, max_length=99)),
  1474. migrations.AlterField('Pony', 'slug', models.CharField(unique=True, max_length=99)),
  1475. ])
  1476. def test_rename_field_reloads_state_on_fk_target_changes(self):
  1477. """
  1478. If RenameField doesn't reload state appropriately, the AlterField
  1479. crashes on MySQL due to not dropping the PonyRider.pony foreign key
  1480. constraint before modifying the column.
  1481. """
  1482. app_label = 'alter_rename_field_reloads_state_on_fk_target_changes'
  1483. project_state = self.apply_operations(app_label, ProjectState(), operations=[
  1484. migrations.CreateModel('Rider', fields=[
  1485. ('id', models.CharField(primary_key=True, max_length=100)),
  1486. ]),
  1487. migrations.CreateModel('Pony', fields=[
  1488. ('id', models.CharField(primary_key=True, max_length=100)),
  1489. ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE)),
  1490. ]),
  1491. migrations.CreateModel('PonyRider', fields=[
  1492. ('id', models.AutoField(primary_key=True)),
  1493. ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE)),
  1494. ]),
  1495. ])
  1496. project_state = self.apply_operations(app_label, project_state, operations=[
  1497. migrations.RenameField('Rider', 'id', 'id2'),
  1498. migrations.AlterField('Pony', 'id', models.CharField(primary_key=True, max_length=99)),
  1499. ], atomic=connection.features.supports_atomic_references_rename)
  1500. def test_rename_field(self):
  1501. """
  1502. Tests the RenameField operation.
  1503. """
  1504. project_state = self.set_up_test_model("test_rnfl", unique_together=True, index_together=True)
  1505. # Test the state alteration
  1506. operation = migrations.RenameField("Pony", "pink", "blue")
  1507. self.assertEqual(operation.describe(), "Rename field pink on Pony to blue")
  1508. self.assertEqual(operation.migration_name_fragment, 'rename_pink_pony_blue')
  1509. new_state = project_state.clone()
  1510. operation.state_forwards("test_rnfl", new_state)
  1511. self.assertIn("blue", new_state.models["test_rnfl", "pony"].fields)
  1512. self.assertNotIn("pink", new_state.models["test_rnfl", "pony"].fields)
  1513. # Make sure the unique_together has the renamed column too
  1514. self.assertIn("blue", new_state.models["test_rnfl", "pony"].options['unique_together'][0])
  1515. self.assertNotIn("pink", new_state.models["test_rnfl", "pony"].options['unique_together'][0])
  1516. # Make sure the index_together has the renamed column too
  1517. self.assertIn("blue", new_state.models["test_rnfl", "pony"].options['index_together'][0])
  1518. self.assertNotIn("pink", new_state.models["test_rnfl", "pony"].options['index_together'][0])
  1519. # Test the database alteration
  1520. self.assertColumnExists("test_rnfl_pony", "pink")
  1521. self.assertColumnNotExists("test_rnfl_pony", "blue")
  1522. with connection.schema_editor() as editor:
  1523. operation.database_forwards("test_rnfl", editor, project_state, new_state)
  1524. self.assertColumnExists("test_rnfl_pony", "blue")
  1525. self.assertColumnNotExists("test_rnfl_pony", "pink")
  1526. # Ensure the unique constraint has been ported over
  1527. with connection.cursor() as cursor:
  1528. cursor.execute("INSERT INTO test_rnfl_pony (blue, weight) VALUES (1, 1)")
  1529. with self.assertRaises(IntegrityError):
  1530. with atomic():
  1531. cursor.execute("INSERT INTO test_rnfl_pony (blue, weight) VALUES (1, 1)")
  1532. cursor.execute("DELETE FROM test_rnfl_pony")
  1533. # Ensure the index constraint has been ported over
  1534. self.assertIndexExists("test_rnfl_pony", ["weight", "blue"])
  1535. # And test reversal
  1536. with connection.schema_editor() as editor:
  1537. operation.database_backwards("test_rnfl", editor, new_state, project_state)
  1538. self.assertColumnExists("test_rnfl_pony", "pink")
  1539. self.assertColumnNotExists("test_rnfl_pony", "blue")
  1540. # Ensure the index constraint has been reset
  1541. self.assertIndexExists("test_rnfl_pony", ["weight", "pink"])
  1542. # And deconstruction
  1543. definition = operation.deconstruct()
  1544. self.assertEqual(definition[0], "RenameField")
  1545. self.assertEqual(definition[1], [])
  1546. self.assertEqual(definition[2], {'model_name': "Pony", 'old_name': "pink", 'new_name': "blue"})
  1547. def test_rename_missing_field(self):
  1548. state = ProjectState()
  1549. state.add_model(ModelState('app', 'model', []))
  1550. with self.assertRaisesMessage(FieldDoesNotExist, "app.model has no field named 'field'"):
  1551. migrations.RenameField('model', 'field', 'new_field').state_forwards('app', state)
  1552. def test_rename_referenced_field_state_forward(self):
  1553. state = ProjectState()
  1554. state.add_model(ModelState('app', 'Model', [
  1555. ('id', models.AutoField(primary_key=True)),
  1556. ('field', models.IntegerField(unique=True)),
  1557. ]))
  1558. state.add_model(ModelState('app', 'OtherModel', [
  1559. ('id', models.AutoField(primary_key=True)),
  1560. ('fk', models.ForeignKey('Model', models.CASCADE, to_field='field')),
  1561. ('fo', models.ForeignObject('Model', models.CASCADE, from_fields=('fk',), to_fields=('field',))),
  1562. ]))
  1563. operation = migrations.RenameField('Model', 'field', 'renamed')
  1564. new_state = state.clone()
  1565. operation.state_forwards('app', new_state)
  1566. self.assertEqual(new_state.models['app', 'othermodel'].fields['fk'].remote_field.field_name, 'renamed')
  1567. self.assertEqual(new_state.models['app', 'othermodel'].fields['fk'].from_fields, ['self'])
  1568. self.assertEqual(new_state.models['app', 'othermodel'].fields['fk'].to_fields, ('renamed',))
  1569. self.assertEqual(new_state.models['app', 'othermodel'].fields['fo'].from_fields, ('fk',))
  1570. self.assertEqual(new_state.models['app', 'othermodel'].fields['fo'].to_fields, ('renamed',))
  1571. operation = migrations.RenameField('OtherModel', 'fk', 'renamed_fk')
  1572. new_state = state.clone()
  1573. operation.state_forwards('app', new_state)
  1574. self.assertEqual(new_state.models['app', 'othermodel'].fields['renamed_fk'].remote_field.field_name, 'renamed')
  1575. self.assertEqual(new_state.models['app', 'othermodel'].fields['renamed_fk'].from_fields, ('self',))
  1576. self.assertEqual(new_state.models['app', 'othermodel'].fields['renamed_fk'].to_fields, ('renamed',))
  1577. self.assertEqual(new_state.models['app', 'othermodel'].fields['fo'].from_fields, ('renamed_fk',))
  1578. self.assertEqual(new_state.models['app', 'othermodel'].fields['fo'].to_fields, ('renamed',))
  1579. def test_alter_unique_together(self):
  1580. """
  1581. Tests the AlterUniqueTogether operation.
  1582. """
  1583. project_state = self.set_up_test_model("test_alunto")
  1584. # Test the state alteration
  1585. operation = migrations.AlterUniqueTogether("Pony", [("pink", "weight")])
  1586. self.assertEqual(operation.describe(), "Alter unique_together for Pony (1 constraint(s))")
  1587. self.assertEqual(
  1588. operation.migration_name_fragment,
  1589. 'alter_pony_unique_together',
  1590. )
  1591. new_state = project_state.clone()
  1592. operation.state_forwards("test_alunto", new_state)
  1593. self.assertEqual(len(project_state.models["test_alunto", "pony"].options.get("unique_together", set())), 0)
  1594. self.assertEqual(len(new_state.models["test_alunto", "pony"].options.get("unique_together", set())), 1)
  1595. # Make sure we can insert duplicate rows
  1596. with connection.cursor() as cursor:
  1597. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  1598. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  1599. cursor.execute("DELETE FROM test_alunto_pony")
  1600. # Test the database alteration
  1601. with connection.schema_editor() as editor:
  1602. operation.database_forwards("test_alunto", editor, project_state, new_state)
  1603. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  1604. with self.assertRaises(IntegrityError):
  1605. with atomic():
  1606. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  1607. cursor.execute("DELETE FROM test_alunto_pony")
  1608. # And test reversal
  1609. with connection.schema_editor() as editor:
  1610. operation.database_backwards("test_alunto", editor, new_state, project_state)
  1611. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  1612. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  1613. cursor.execute("DELETE FROM test_alunto_pony")
  1614. # Test flat unique_together
  1615. operation = migrations.AlterUniqueTogether("Pony", ("pink", "weight"))
  1616. operation.state_forwards("test_alunto", new_state)
  1617. self.assertEqual(len(new_state.models["test_alunto", "pony"].options.get("unique_together", set())), 1)
  1618. # And deconstruction
  1619. definition = operation.deconstruct()
  1620. self.assertEqual(definition[0], "AlterUniqueTogether")
  1621. self.assertEqual(definition[1], [])
  1622. self.assertEqual(definition[2], {'name': "Pony", 'unique_together': {("pink", "weight")}})
  1623. def test_alter_unique_together_remove(self):
  1624. operation = migrations.AlterUniqueTogether("Pony", None)
  1625. self.assertEqual(operation.describe(), "Alter unique_together for Pony (0 constraint(s))")
  1626. def test_add_index(self):
  1627. """
  1628. Test the AddIndex operation.
  1629. """
  1630. project_state = self.set_up_test_model("test_adin")
  1631. msg = (
  1632. "Indexes passed to AddIndex operations require a name argument. "
  1633. "<Index: fields='pink'> doesn't have one."
  1634. )
  1635. with self.assertRaisesMessage(ValueError, msg):
  1636. migrations.AddIndex("Pony", models.Index(fields=["pink"]))
  1637. index = models.Index(fields=["pink"], name="test_adin_pony_pink_idx")
  1638. operation = migrations.AddIndex("Pony", index)
  1639. self.assertEqual(operation.describe(), "Create index test_adin_pony_pink_idx on field(s) pink of model Pony")
  1640. self.assertEqual(
  1641. operation.migration_name_fragment,
  1642. 'pony_test_adin_pony_pink_idx',
  1643. )
  1644. new_state = project_state.clone()
  1645. operation.state_forwards("test_adin", new_state)
  1646. # Test the database alteration
  1647. self.assertEqual(len(new_state.models["test_adin", "pony"].options['indexes']), 1)
  1648. self.assertIndexNotExists("test_adin_pony", ["pink"])
  1649. with connection.schema_editor() as editor:
  1650. operation.database_forwards("test_adin", editor, project_state, new_state)
  1651. self.assertIndexExists("test_adin_pony", ["pink"])
  1652. # And test reversal
  1653. with connection.schema_editor() as editor:
  1654. operation.database_backwards("test_adin", editor, new_state, project_state)
  1655. self.assertIndexNotExists("test_adin_pony", ["pink"])
  1656. # And deconstruction
  1657. definition = operation.deconstruct()
  1658. self.assertEqual(definition[0], "AddIndex")
  1659. self.assertEqual(definition[1], [])
  1660. self.assertEqual(definition[2], {'model_name': "Pony", 'index': index})
  1661. def test_remove_index(self):
  1662. """
  1663. Test the RemoveIndex operation.
  1664. """
  1665. project_state = self.set_up_test_model("test_rmin", multicol_index=True)
  1666. self.assertTableExists("test_rmin_pony")
  1667. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  1668. operation = migrations.RemoveIndex("Pony", "pony_test_idx")
  1669. self.assertEqual(operation.describe(), "Remove index pony_test_idx from Pony")
  1670. self.assertEqual(
  1671. operation.migration_name_fragment,
  1672. 'remove_pony_pony_test_idx',
  1673. )
  1674. new_state = project_state.clone()
  1675. operation.state_forwards("test_rmin", new_state)
  1676. # Test the state alteration
  1677. self.assertEqual(len(new_state.models["test_rmin", "pony"].options['indexes']), 0)
  1678. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  1679. # Test the database alteration
  1680. with connection.schema_editor() as editor:
  1681. operation.database_forwards("test_rmin", editor, project_state, new_state)
  1682. self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"])
  1683. # And test reversal
  1684. with connection.schema_editor() as editor:
  1685. operation.database_backwards("test_rmin", editor, new_state, project_state)
  1686. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  1687. # And deconstruction
  1688. definition = operation.deconstruct()
  1689. self.assertEqual(definition[0], "RemoveIndex")
  1690. self.assertEqual(definition[1], [])
  1691. self.assertEqual(definition[2], {'model_name': "Pony", 'name': "pony_test_idx"})
  1692. # Also test a field dropped with index - sqlite remake issue
  1693. operations = [
  1694. migrations.RemoveIndex("Pony", "pony_test_idx"),
  1695. migrations.RemoveField("Pony", "pink"),
  1696. ]
  1697. self.assertColumnExists("test_rmin_pony", "pink")
  1698. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  1699. # Test database alteration
  1700. new_state = project_state.clone()
  1701. self.apply_operations('test_rmin', new_state, operations=operations)
  1702. self.assertColumnNotExists("test_rmin_pony", "pink")
  1703. self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"])
  1704. # And test reversal
  1705. self.unapply_operations("test_rmin", project_state, operations=operations)
  1706. self.assertIndexExists("test_rmin_pony", ["pink", "weight"])
  1707. def test_add_index_state_forwards(self):
  1708. project_state = self.set_up_test_model('test_adinsf')
  1709. index = models.Index(fields=['pink'], name='test_adinsf_pony_pink_idx')
  1710. old_model = project_state.apps.get_model('test_adinsf', 'Pony')
  1711. new_state = project_state.clone()
  1712. operation = migrations.AddIndex('Pony', index)
  1713. operation.state_forwards('test_adinsf', new_state)
  1714. new_model = new_state.apps.get_model('test_adinsf', 'Pony')
  1715. self.assertIsNot(old_model, new_model)
  1716. def test_remove_index_state_forwards(self):
  1717. project_state = self.set_up_test_model('test_rminsf')
  1718. index = models.Index(fields=['pink'], name='test_rminsf_pony_pink_idx')
  1719. migrations.AddIndex('Pony', index).state_forwards('test_rminsf', project_state)
  1720. old_model = project_state.apps.get_model('test_rminsf', 'Pony')
  1721. new_state = project_state.clone()
  1722. operation = migrations.RemoveIndex('Pony', 'test_rminsf_pony_pink_idx')
  1723. operation.state_forwards('test_rminsf', new_state)
  1724. new_model = new_state.apps.get_model('test_rminsf', 'Pony')
  1725. self.assertIsNot(old_model, new_model)
  1726. def test_alter_field_with_index(self):
  1727. """
  1728. Test AlterField operation with an index to ensure indexes created via
  1729. Meta.indexes don't get dropped with sqlite3 remake.
  1730. """
  1731. project_state = self.set_up_test_model("test_alflin", index=True)
  1732. operation = migrations.AlterField("Pony", "pink", models.IntegerField(null=True))
  1733. new_state = project_state.clone()
  1734. operation.state_forwards("test_alflin", new_state)
  1735. # Test the database alteration
  1736. self.assertColumnNotNull("test_alflin_pony", "pink")
  1737. with connection.schema_editor() as editor:
  1738. operation.database_forwards("test_alflin", editor, project_state, new_state)
  1739. # Index hasn't been dropped
  1740. self.assertIndexExists("test_alflin_pony", ["pink"])
  1741. # And test reversal
  1742. with connection.schema_editor() as editor:
  1743. operation.database_backwards("test_alflin", editor, new_state, project_state)
  1744. # Ensure the index is still there
  1745. self.assertIndexExists("test_alflin_pony", ["pink"])
  1746. def test_alter_index_together(self):
  1747. """
  1748. Tests the AlterIndexTogether operation.
  1749. """
  1750. project_state = self.set_up_test_model("test_alinto")
  1751. # Test the state alteration
  1752. operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")])
  1753. self.assertEqual(operation.describe(), "Alter index_together for Pony (1 constraint(s))")
  1754. self.assertEqual(
  1755. operation.migration_name_fragment,
  1756. 'alter_pony_index_together',
  1757. )
  1758. new_state = project_state.clone()
  1759. operation.state_forwards("test_alinto", new_state)
  1760. self.assertEqual(len(project_state.models["test_alinto", "pony"].options.get("index_together", set())), 0)
  1761. self.assertEqual(len(new_state.models["test_alinto", "pony"].options.get("index_together", set())), 1)
  1762. # Make sure there's no matching index
  1763. self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"])
  1764. # Test the database alteration
  1765. with connection.schema_editor() as editor:
  1766. operation.database_forwards("test_alinto", editor, project_state, new_state)
  1767. self.assertIndexExists("test_alinto_pony", ["pink", "weight"])
  1768. # And test reversal
  1769. with connection.schema_editor() as editor:
  1770. operation.database_backwards("test_alinto", editor, new_state, project_state)
  1771. self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"])
  1772. # And deconstruction
  1773. definition = operation.deconstruct()
  1774. self.assertEqual(definition[0], "AlterIndexTogether")
  1775. self.assertEqual(definition[1], [])
  1776. self.assertEqual(definition[2], {'name': "Pony", 'index_together': {("pink", "weight")}})
  1777. def test_alter_index_together_remove(self):
  1778. operation = migrations.AlterIndexTogether("Pony", None)
  1779. self.assertEqual(operation.describe(), "Alter index_together for Pony (0 constraint(s))")
  1780. @skipUnlessDBFeature('allows_multiple_constraints_on_same_fields')
  1781. def test_alter_index_together_remove_with_unique_together(self):
  1782. app_label = 'test_alintoremove_wunto'
  1783. table_name = '%s_pony' % app_label
  1784. project_state = self.set_up_test_model(app_label, unique_together=True)
  1785. self.assertUniqueConstraintExists(table_name, ['pink', 'weight'])
  1786. # Add index together.
  1787. new_state = project_state.clone()
  1788. operation = migrations.AlterIndexTogether('Pony', [('pink', 'weight')])
  1789. operation.state_forwards(app_label, new_state)
  1790. with connection.schema_editor() as editor:
  1791. operation.database_forwards(app_label, editor, project_state, new_state)
  1792. self.assertIndexExists(table_name, ['pink', 'weight'])
  1793. # Remove index together.
  1794. project_state = new_state
  1795. new_state = project_state.clone()
  1796. operation = migrations.AlterIndexTogether('Pony', set())
  1797. operation.state_forwards(app_label, new_state)
  1798. with connection.schema_editor() as editor:
  1799. operation.database_forwards(app_label, editor, project_state, new_state)
  1800. self.assertIndexNotExists(table_name, ['pink', 'weight'])
  1801. self.assertUniqueConstraintExists(table_name, ['pink', 'weight'])
  1802. @skipUnlessDBFeature('supports_table_check_constraints')
  1803. def test_add_constraint(self):
  1804. project_state = self.set_up_test_model("test_addconstraint")
  1805. gt_check = models.Q(pink__gt=2)
  1806. gt_constraint = models.CheckConstraint(check=gt_check, name="test_add_constraint_pony_pink_gt_2")
  1807. gt_operation = migrations.AddConstraint("Pony", gt_constraint)
  1808. self.assertEqual(
  1809. gt_operation.describe(), "Create constraint test_add_constraint_pony_pink_gt_2 on model Pony"
  1810. )
  1811. self.assertEqual(
  1812. gt_operation.migration_name_fragment,
  1813. 'pony_test_add_constraint_pony_pink_gt_2',
  1814. )
  1815. # Test the state alteration
  1816. new_state = project_state.clone()
  1817. gt_operation.state_forwards("test_addconstraint", new_state)
  1818. self.assertEqual(len(new_state.models["test_addconstraint", "pony"].options["constraints"]), 1)
  1819. Pony = new_state.apps.get_model("test_addconstraint", "Pony")
  1820. self.assertEqual(len(Pony._meta.constraints), 1)
  1821. # Test the database alteration
  1822. with connection.schema_editor() as editor:
  1823. gt_operation.database_forwards("test_addconstraint", editor, project_state, new_state)
  1824. with self.assertRaises(IntegrityError), transaction.atomic():
  1825. Pony.objects.create(pink=1, weight=1.0)
  1826. # Add another one.
  1827. lt_check = models.Q(pink__lt=100)
  1828. lt_constraint = models.CheckConstraint(check=lt_check, name="test_add_constraint_pony_pink_lt_100")
  1829. lt_operation = migrations.AddConstraint("Pony", lt_constraint)
  1830. lt_operation.state_forwards("test_addconstraint", new_state)
  1831. self.assertEqual(len(new_state.models["test_addconstraint", "pony"].options["constraints"]), 2)
  1832. Pony = new_state.apps.get_model("test_addconstraint", "Pony")
  1833. self.assertEqual(len(Pony._meta.constraints), 2)
  1834. with connection.schema_editor() as editor:
  1835. lt_operation.database_forwards("test_addconstraint", editor, project_state, new_state)
  1836. with self.assertRaises(IntegrityError), transaction.atomic():
  1837. Pony.objects.create(pink=100, weight=1.0)
  1838. # Test reversal
  1839. with connection.schema_editor() as editor:
  1840. gt_operation.database_backwards("test_addconstraint", editor, new_state, project_state)
  1841. Pony.objects.create(pink=1, weight=1.0)
  1842. # Test deconstruction
  1843. definition = gt_operation.deconstruct()
  1844. self.assertEqual(definition[0], "AddConstraint")
  1845. self.assertEqual(definition[1], [])
  1846. self.assertEqual(definition[2], {'model_name': "Pony", 'constraint': gt_constraint})
  1847. @skipUnlessDBFeature('supports_table_check_constraints')
  1848. def test_add_constraint_percent_escaping(self):
  1849. app_label = 'add_constraint_string_quoting'
  1850. operations = [
  1851. migrations.CreateModel(
  1852. 'Author',
  1853. fields=[
  1854. ('id', models.AutoField(primary_key=True)),
  1855. ('name', models.CharField(max_length=100)),
  1856. ('rebate', models.CharField(max_length=100)),
  1857. ],
  1858. ),
  1859. ]
  1860. from_state = self.apply_operations(app_label, ProjectState(), operations)
  1861. # "%" generated in startswith lookup should be escaped in a way that is
  1862. # considered a leading wildcard.
  1863. check = models.Q(name__startswith='Albert')
  1864. constraint = models.CheckConstraint(check=check, name='name_constraint')
  1865. operation = migrations.AddConstraint('Author', constraint)
  1866. to_state = from_state.clone()
  1867. operation.state_forwards(app_label, to_state)
  1868. with connection.schema_editor() as editor:
  1869. operation.database_forwards(app_label, editor, from_state, to_state)
  1870. Author = to_state.apps.get_model(app_label, 'Author')
  1871. with self.assertRaises(IntegrityError), transaction.atomic():
  1872. Author.objects.create(name='Artur')
  1873. # Literal "%" should be escaped in a way that is not a considered a
  1874. # wildcard.
  1875. check = models.Q(rebate__endswith='%')
  1876. constraint = models.CheckConstraint(check=check, name='rebate_constraint')
  1877. operation = migrations.AddConstraint('Author', constraint)
  1878. from_state = to_state
  1879. to_state = from_state.clone()
  1880. operation.state_forwards(app_label, to_state)
  1881. Author = to_state.apps.get_model(app_label, 'Author')
  1882. with connection.schema_editor() as editor:
  1883. operation.database_forwards(app_label, editor, from_state, to_state)
  1884. Author = to_state.apps.get_model(app_label, 'Author')
  1885. with self.assertRaises(IntegrityError), transaction.atomic():
  1886. Author.objects.create(name='Albert', rebate='10$')
  1887. author = Author.objects.create(name='Albert', rebate='10%')
  1888. self.assertEqual(Author.objects.get(), author)
  1889. @skipUnlessDBFeature('supports_table_check_constraints')
  1890. def test_add_or_constraint(self):
  1891. app_label = 'test_addorconstraint'
  1892. constraint_name = 'add_constraint_or'
  1893. from_state = self.set_up_test_model(app_label)
  1894. check = models.Q(pink__gt=2, weight__gt=2) | models.Q(weight__lt=0)
  1895. constraint = models.CheckConstraint(check=check, name=constraint_name)
  1896. operation = migrations.AddConstraint('Pony', constraint)
  1897. to_state = from_state.clone()
  1898. operation.state_forwards(app_label, to_state)
  1899. with connection.schema_editor() as editor:
  1900. operation.database_forwards(app_label, editor, from_state, to_state)
  1901. Pony = to_state.apps.get_model(app_label, 'Pony')
  1902. with self.assertRaises(IntegrityError), transaction.atomic():
  1903. Pony.objects.create(pink=2, weight=3.0)
  1904. with self.assertRaises(IntegrityError), transaction.atomic():
  1905. Pony.objects.create(pink=3, weight=1.0)
  1906. Pony.objects.bulk_create([
  1907. Pony(pink=3, weight=-1.0),
  1908. Pony(pink=1, weight=-1.0),
  1909. Pony(pink=3, weight=3.0),
  1910. ])
  1911. @skipUnlessDBFeature('supports_table_check_constraints')
  1912. def test_add_constraint_combinable(self):
  1913. app_label = 'test_addconstraint_combinable'
  1914. operations = [
  1915. migrations.CreateModel(
  1916. 'Book',
  1917. fields=[
  1918. ('id', models.AutoField(primary_key=True)),
  1919. ('read', models.PositiveIntegerField()),
  1920. ('unread', models.PositiveIntegerField()),
  1921. ],
  1922. ),
  1923. ]
  1924. from_state = self.apply_operations(app_label, ProjectState(), operations)
  1925. constraint = models.CheckConstraint(
  1926. check=models.Q(read=(100 - models.F('unread'))),
  1927. name='test_addconstraint_combinable_sum_100',
  1928. )
  1929. operation = migrations.AddConstraint('Book', constraint)
  1930. to_state = from_state.clone()
  1931. operation.state_forwards(app_label, to_state)
  1932. with connection.schema_editor() as editor:
  1933. operation.database_forwards(app_label, editor, from_state, to_state)
  1934. Book = to_state.apps.get_model(app_label, 'Book')
  1935. with self.assertRaises(IntegrityError), transaction.atomic():
  1936. Book.objects.create(read=70, unread=10)
  1937. Book.objects.create(read=70, unread=30)
  1938. @skipUnlessDBFeature('supports_table_check_constraints')
  1939. def test_remove_constraint(self):
  1940. project_state = self.set_up_test_model("test_removeconstraint", constraints=[
  1941. models.CheckConstraint(check=models.Q(pink__gt=2), name="test_remove_constraint_pony_pink_gt_2"),
  1942. models.CheckConstraint(check=models.Q(pink__lt=100), name="test_remove_constraint_pony_pink_lt_100"),
  1943. ])
  1944. gt_operation = migrations.RemoveConstraint("Pony", "test_remove_constraint_pony_pink_gt_2")
  1945. self.assertEqual(
  1946. gt_operation.describe(), "Remove constraint test_remove_constraint_pony_pink_gt_2 from model Pony"
  1947. )
  1948. self.assertEqual(
  1949. gt_operation.migration_name_fragment,
  1950. 'remove_pony_test_remove_constraint_pony_pink_gt_2',
  1951. )
  1952. # Test state alteration
  1953. new_state = project_state.clone()
  1954. gt_operation.state_forwards("test_removeconstraint", new_state)
  1955. self.assertEqual(len(new_state.models["test_removeconstraint", "pony"].options['constraints']), 1)
  1956. Pony = new_state.apps.get_model("test_removeconstraint", "Pony")
  1957. self.assertEqual(len(Pony._meta.constraints), 1)
  1958. # Test database alteration
  1959. with connection.schema_editor() as editor:
  1960. gt_operation.database_forwards("test_removeconstraint", editor, project_state, new_state)
  1961. Pony.objects.create(pink=1, weight=1.0).delete()
  1962. with self.assertRaises(IntegrityError), transaction.atomic():
  1963. Pony.objects.create(pink=100, weight=1.0)
  1964. # Remove the other one.
  1965. lt_operation = migrations.RemoveConstraint("Pony", "test_remove_constraint_pony_pink_lt_100")
  1966. lt_operation.state_forwards("test_removeconstraint", new_state)
  1967. self.assertEqual(len(new_state.models["test_removeconstraint", "pony"].options['constraints']), 0)
  1968. Pony = new_state.apps.get_model("test_removeconstraint", "Pony")
  1969. self.assertEqual(len(Pony._meta.constraints), 0)
  1970. with connection.schema_editor() as editor:
  1971. lt_operation.database_forwards("test_removeconstraint", editor, project_state, new_state)
  1972. Pony.objects.create(pink=100, weight=1.0).delete()
  1973. # Test reversal
  1974. with connection.schema_editor() as editor:
  1975. gt_operation.database_backwards("test_removeconstraint", editor, new_state, project_state)
  1976. with self.assertRaises(IntegrityError), transaction.atomic():
  1977. Pony.objects.create(pink=1, weight=1.0)
  1978. # Test deconstruction
  1979. definition = gt_operation.deconstruct()
  1980. self.assertEqual(definition[0], "RemoveConstraint")
  1981. self.assertEqual(definition[1], [])
  1982. self.assertEqual(definition[2], {'model_name': "Pony", 'name': "test_remove_constraint_pony_pink_gt_2"})
  1983. def test_add_partial_unique_constraint(self):
  1984. project_state = self.set_up_test_model('test_addpartialuniqueconstraint')
  1985. partial_unique_constraint = models.UniqueConstraint(
  1986. fields=['pink'],
  1987. condition=models.Q(weight__gt=5),
  1988. name='test_constraint_pony_pink_for_weight_gt_5_uniq',
  1989. )
  1990. operation = migrations.AddConstraint('Pony', partial_unique_constraint)
  1991. self.assertEqual(
  1992. operation.describe(),
  1993. 'Create constraint test_constraint_pony_pink_for_weight_gt_5_uniq '
  1994. 'on model Pony'
  1995. )
  1996. # Test the state alteration
  1997. new_state = project_state.clone()
  1998. operation.state_forwards('test_addpartialuniqueconstraint', new_state)
  1999. self.assertEqual(len(new_state.models['test_addpartialuniqueconstraint', 'pony'].options['constraints']), 1)
  2000. Pony = new_state.apps.get_model('test_addpartialuniqueconstraint', 'Pony')
  2001. self.assertEqual(len(Pony._meta.constraints), 1)
  2002. # Test the database alteration
  2003. with connection.schema_editor() as editor:
  2004. operation.database_forwards('test_addpartialuniqueconstraint', editor, project_state, new_state)
  2005. # Test constraint works
  2006. Pony.objects.create(pink=1, weight=4.0)
  2007. Pony.objects.create(pink=1, weight=4.0)
  2008. Pony.objects.create(pink=1, weight=6.0)
  2009. if connection.features.supports_partial_indexes:
  2010. with self.assertRaises(IntegrityError), transaction.atomic():
  2011. Pony.objects.create(pink=1, weight=7.0)
  2012. else:
  2013. Pony.objects.create(pink=1, weight=7.0)
  2014. # Test reversal
  2015. with connection.schema_editor() as editor:
  2016. operation.database_backwards('test_addpartialuniqueconstraint', editor, new_state, project_state)
  2017. # Test constraint doesn't work
  2018. Pony.objects.create(pink=1, weight=7.0)
  2019. # Test deconstruction
  2020. definition = operation.deconstruct()
  2021. self.assertEqual(definition[0], 'AddConstraint')
  2022. self.assertEqual(definition[1], [])
  2023. self.assertEqual(definition[2], {'model_name': 'Pony', 'constraint': partial_unique_constraint})
  2024. def test_remove_partial_unique_constraint(self):
  2025. project_state = self.set_up_test_model('test_removepartialuniqueconstraint', constraints=[
  2026. models.UniqueConstraint(
  2027. fields=['pink'],
  2028. condition=models.Q(weight__gt=5),
  2029. name='test_constraint_pony_pink_for_weight_gt_5_uniq',
  2030. ),
  2031. ])
  2032. gt_operation = migrations.RemoveConstraint('Pony', 'test_constraint_pony_pink_for_weight_gt_5_uniq')
  2033. self.assertEqual(
  2034. gt_operation.describe(), 'Remove constraint test_constraint_pony_pink_for_weight_gt_5_uniq from model Pony'
  2035. )
  2036. # Test state alteration
  2037. new_state = project_state.clone()
  2038. gt_operation.state_forwards('test_removepartialuniqueconstraint', new_state)
  2039. self.assertEqual(len(new_state.models['test_removepartialuniqueconstraint', 'pony'].options['constraints']), 0)
  2040. Pony = new_state.apps.get_model('test_removepartialuniqueconstraint', 'Pony')
  2041. self.assertEqual(len(Pony._meta.constraints), 0)
  2042. # Test database alteration
  2043. with connection.schema_editor() as editor:
  2044. gt_operation.database_forwards('test_removepartialuniqueconstraint', editor, project_state, new_state)
  2045. # Test constraint doesn't work
  2046. Pony.objects.create(pink=1, weight=4.0)
  2047. Pony.objects.create(pink=1, weight=4.0)
  2048. Pony.objects.create(pink=1, weight=6.0)
  2049. Pony.objects.create(pink=1, weight=7.0).delete()
  2050. # Test reversal
  2051. with connection.schema_editor() as editor:
  2052. gt_operation.database_backwards('test_removepartialuniqueconstraint', editor, new_state, project_state)
  2053. # Test constraint works
  2054. if connection.features.supports_partial_indexes:
  2055. with self.assertRaises(IntegrityError), transaction.atomic():
  2056. Pony.objects.create(pink=1, weight=7.0)
  2057. else:
  2058. Pony.objects.create(pink=1, weight=7.0)
  2059. # Test deconstruction
  2060. definition = gt_operation.deconstruct()
  2061. self.assertEqual(definition[0], 'RemoveConstraint')
  2062. self.assertEqual(definition[1], [])
  2063. self.assertEqual(definition[2], {
  2064. 'model_name': 'Pony',
  2065. 'name': 'test_constraint_pony_pink_for_weight_gt_5_uniq',
  2066. })
  2067. def test_add_deferred_unique_constraint(self):
  2068. app_label = 'test_adddeferred_uc'
  2069. project_state = self.set_up_test_model(app_label)
  2070. deferred_unique_constraint = models.UniqueConstraint(
  2071. fields=['pink'],
  2072. name='deferred_pink_constraint_add',
  2073. deferrable=models.Deferrable.DEFERRED,
  2074. )
  2075. operation = migrations.AddConstraint('Pony', deferred_unique_constraint)
  2076. self.assertEqual(
  2077. operation.describe(),
  2078. 'Create constraint deferred_pink_constraint_add on model Pony',
  2079. )
  2080. # Add constraint.
  2081. new_state = project_state.clone()
  2082. operation.state_forwards(app_label, new_state)
  2083. self.assertEqual(len(new_state.models[app_label, 'pony'].options['constraints']), 1)
  2084. Pony = new_state.apps.get_model(app_label, 'Pony')
  2085. self.assertEqual(len(Pony._meta.constraints), 1)
  2086. with connection.schema_editor() as editor:
  2087. operation.database_forwards(app_label, editor, project_state, new_state)
  2088. Pony.objects.create(pink=1, weight=4.0)
  2089. if connection.features.supports_deferrable_unique_constraints:
  2090. # Unique constraint is deferred.
  2091. with transaction.atomic():
  2092. obj = Pony.objects.create(pink=1, weight=4.0)
  2093. obj.pink = 2
  2094. obj.save()
  2095. # Constraint behavior can be changed with SET CONSTRAINTS.
  2096. with self.assertRaises(IntegrityError):
  2097. with transaction.atomic(), connection.cursor() as cursor:
  2098. quoted_name = connection.ops.quote_name(deferred_unique_constraint.name)
  2099. cursor.execute('SET CONSTRAINTS %s IMMEDIATE' % quoted_name)
  2100. obj = Pony.objects.create(pink=1, weight=4.0)
  2101. obj.pink = 3
  2102. obj.save()
  2103. else:
  2104. Pony.objects.create(pink=1, weight=4.0)
  2105. # Reversal.
  2106. with connection.schema_editor() as editor:
  2107. operation.database_backwards(app_label, editor, new_state, project_state)
  2108. # Constraint doesn't work.
  2109. Pony.objects.create(pink=1, weight=4.0)
  2110. # Deconstruction.
  2111. definition = operation.deconstruct()
  2112. self.assertEqual(definition[0], 'AddConstraint')
  2113. self.assertEqual(definition[1], [])
  2114. self.assertEqual(
  2115. definition[2],
  2116. {'model_name': 'Pony', 'constraint': deferred_unique_constraint},
  2117. )
  2118. def test_remove_deferred_unique_constraint(self):
  2119. app_label = 'test_removedeferred_uc'
  2120. deferred_unique_constraint = models.UniqueConstraint(
  2121. fields=['pink'],
  2122. name='deferred_pink_constraint_rm',
  2123. deferrable=models.Deferrable.DEFERRED,
  2124. )
  2125. project_state = self.set_up_test_model(app_label, constraints=[deferred_unique_constraint])
  2126. operation = migrations.RemoveConstraint('Pony', deferred_unique_constraint.name)
  2127. self.assertEqual(
  2128. operation.describe(),
  2129. 'Remove constraint deferred_pink_constraint_rm from model Pony',
  2130. )
  2131. # Remove constraint.
  2132. new_state = project_state.clone()
  2133. operation.state_forwards(app_label, new_state)
  2134. self.assertEqual(len(new_state.models[app_label, 'pony'].options['constraints']), 0)
  2135. Pony = new_state.apps.get_model(app_label, 'Pony')
  2136. self.assertEqual(len(Pony._meta.constraints), 0)
  2137. with connection.schema_editor() as editor:
  2138. operation.database_forwards(app_label, editor, project_state, new_state)
  2139. # Constraint doesn't work.
  2140. Pony.objects.create(pink=1, weight=4.0)
  2141. Pony.objects.create(pink=1, weight=4.0).delete()
  2142. # Reversal.
  2143. with connection.schema_editor() as editor:
  2144. operation.database_backwards(app_label, editor, new_state, project_state)
  2145. if connection.features.supports_deferrable_unique_constraints:
  2146. # Unique constraint is deferred.
  2147. with transaction.atomic():
  2148. obj = Pony.objects.create(pink=1, weight=4.0)
  2149. obj.pink = 2
  2150. obj.save()
  2151. # Constraint behavior can be changed with SET CONSTRAINTS.
  2152. with self.assertRaises(IntegrityError):
  2153. with transaction.atomic(), connection.cursor() as cursor:
  2154. quoted_name = connection.ops.quote_name(deferred_unique_constraint.name)
  2155. cursor.execute('SET CONSTRAINTS %s IMMEDIATE' % quoted_name)
  2156. obj = Pony.objects.create(pink=1, weight=4.0)
  2157. obj.pink = 3
  2158. obj.save()
  2159. else:
  2160. Pony.objects.create(pink=1, weight=4.0)
  2161. # Deconstruction.
  2162. definition = operation.deconstruct()
  2163. self.assertEqual(definition[0], 'RemoveConstraint')
  2164. self.assertEqual(definition[1], [])
  2165. self.assertEqual(definition[2], {
  2166. 'model_name': 'Pony',
  2167. 'name': 'deferred_pink_constraint_rm',
  2168. })
  2169. def test_add_covering_unique_constraint(self):
  2170. app_label = 'test_addcovering_uc'
  2171. project_state = self.set_up_test_model(app_label)
  2172. covering_unique_constraint = models.UniqueConstraint(
  2173. fields=['pink'],
  2174. name='covering_pink_constraint_add',
  2175. include=['weight'],
  2176. )
  2177. operation = migrations.AddConstraint('Pony', covering_unique_constraint)
  2178. self.assertEqual(
  2179. operation.describe(),
  2180. 'Create constraint covering_pink_constraint_add on model Pony',
  2181. )
  2182. # Add constraint.
  2183. new_state = project_state.clone()
  2184. operation.state_forwards(app_label, new_state)
  2185. self.assertEqual(len(new_state.models[app_label, 'pony'].options['constraints']), 1)
  2186. Pony = new_state.apps.get_model(app_label, 'Pony')
  2187. self.assertEqual(len(Pony._meta.constraints), 1)
  2188. with connection.schema_editor() as editor:
  2189. operation.database_forwards(app_label, editor, project_state, new_state)
  2190. Pony.objects.create(pink=1, weight=4.0)
  2191. if connection.features.supports_covering_indexes:
  2192. with self.assertRaises(IntegrityError):
  2193. Pony.objects.create(pink=1, weight=4.0)
  2194. else:
  2195. Pony.objects.create(pink=1, weight=4.0)
  2196. # Reversal.
  2197. with connection.schema_editor() as editor:
  2198. operation.database_backwards(app_label, editor, new_state, project_state)
  2199. # Constraint doesn't work.
  2200. Pony.objects.create(pink=1, weight=4.0)
  2201. # Deconstruction.
  2202. definition = operation.deconstruct()
  2203. self.assertEqual(definition[0], 'AddConstraint')
  2204. self.assertEqual(definition[1], [])
  2205. self.assertEqual(
  2206. definition[2],
  2207. {'model_name': 'Pony', 'constraint': covering_unique_constraint},
  2208. )
  2209. def test_remove_covering_unique_constraint(self):
  2210. app_label = 'test_removecovering_uc'
  2211. covering_unique_constraint = models.UniqueConstraint(
  2212. fields=['pink'],
  2213. name='covering_pink_constraint_rm',
  2214. include=['weight'],
  2215. )
  2216. project_state = self.set_up_test_model(app_label, constraints=[covering_unique_constraint])
  2217. operation = migrations.RemoveConstraint('Pony', covering_unique_constraint.name)
  2218. self.assertEqual(
  2219. operation.describe(),
  2220. 'Remove constraint covering_pink_constraint_rm from model Pony',
  2221. )
  2222. # Remove constraint.
  2223. new_state = project_state.clone()
  2224. operation.state_forwards(app_label, new_state)
  2225. self.assertEqual(len(new_state.models[app_label, 'pony'].options['constraints']), 0)
  2226. Pony = new_state.apps.get_model(app_label, 'Pony')
  2227. self.assertEqual(len(Pony._meta.constraints), 0)
  2228. with connection.schema_editor() as editor:
  2229. operation.database_forwards(app_label, editor, project_state, new_state)
  2230. # Constraint doesn't work.
  2231. Pony.objects.create(pink=1, weight=4.0)
  2232. Pony.objects.create(pink=1, weight=4.0).delete()
  2233. # Reversal.
  2234. with connection.schema_editor() as editor:
  2235. operation.database_backwards(app_label, editor, new_state, project_state)
  2236. if connection.features.supports_covering_indexes:
  2237. with self.assertRaises(IntegrityError):
  2238. Pony.objects.create(pink=1, weight=4.0)
  2239. else:
  2240. Pony.objects.create(pink=1, weight=4.0)
  2241. # Deconstruction.
  2242. definition = operation.deconstruct()
  2243. self.assertEqual(definition[0], 'RemoveConstraint')
  2244. self.assertEqual(definition[1], [])
  2245. self.assertEqual(definition[2], {
  2246. 'model_name': 'Pony',
  2247. 'name': 'covering_pink_constraint_rm',
  2248. })
  2249. def test_alter_model_options(self):
  2250. """
  2251. Tests the AlterModelOptions operation.
  2252. """
  2253. project_state = self.set_up_test_model("test_almoop")
  2254. # Test the state alteration (no DB alteration to test)
  2255. operation = migrations.AlterModelOptions("Pony", {"permissions": [("can_groom", "Can groom")]})
  2256. self.assertEqual(operation.describe(), "Change Meta options on Pony")
  2257. self.assertEqual(operation.migration_name_fragment, 'alter_pony_options')
  2258. new_state = project_state.clone()
  2259. operation.state_forwards("test_almoop", new_state)
  2260. self.assertEqual(len(project_state.models["test_almoop", "pony"].options.get("permissions", [])), 0)
  2261. self.assertEqual(len(new_state.models["test_almoop", "pony"].options.get("permissions", [])), 1)
  2262. self.assertEqual(new_state.models["test_almoop", "pony"].options["permissions"][0][0], "can_groom")
  2263. # And deconstruction
  2264. definition = operation.deconstruct()
  2265. self.assertEqual(definition[0], "AlterModelOptions")
  2266. self.assertEqual(definition[1], [])
  2267. self.assertEqual(definition[2], {'name': "Pony", 'options': {"permissions": [("can_groom", "Can groom")]}})
  2268. def test_alter_model_options_emptying(self):
  2269. """
  2270. The AlterModelOptions operation removes keys from the dict (#23121)
  2271. """
  2272. project_state = self.set_up_test_model("test_almoop", options=True)
  2273. # Test the state alteration (no DB alteration to test)
  2274. operation = migrations.AlterModelOptions("Pony", {})
  2275. self.assertEqual(operation.describe(), "Change Meta options on Pony")
  2276. new_state = project_state.clone()
  2277. operation.state_forwards("test_almoop", new_state)
  2278. self.assertEqual(len(project_state.models["test_almoop", "pony"].options.get("permissions", [])), 1)
  2279. self.assertEqual(len(new_state.models["test_almoop", "pony"].options.get("permissions", [])), 0)
  2280. # And deconstruction
  2281. definition = operation.deconstruct()
  2282. self.assertEqual(definition[0], "AlterModelOptions")
  2283. self.assertEqual(definition[1], [])
  2284. self.assertEqual(definition[2], {'name': "Pony", 'options': {}})
  2285. def test_alter_order_with_respect_to(self):
  2286. """
  2287. Tests the AlterOrderWithRespectTo operation.
  2288. """
  2289. project_state = self.set_up_test_model("test_alorwrtto", related_model=True)
  2290. # Test the state alteration
  2291. operation = migrations.AlterOrderWithRespectTo("Rider", "pony")
  2292. self.assertEqual(operation.describe(), "Set order_with_respect_to on Rider to pony")
  2293. self.assertEqual(
  2294. operation.migration_name_fragment,
  2295. 'alter_rider_order_with_respect_to',
  2296. )
  2297. new_state = project_state.clone()
  2298. operation.state_forwards("test_alorwrtto", new_state)
  2299. self.assertIsNone(
  2300. project_state.models["test_alorwrtto", "rider"].options.get("order_with_respect_to", None)
  2301. )
  2302. self.assertEqual(
  2303. new_state.models["test_alorwrtto", "rider"].options.get("order_with_respect_to", None),
  2304. "pony"
  2305. )
  2306. # Make sure there's no matching index
  2307. self.assertColumnNotExists("test_alorwrtto_rider", "_order")
  2308. # Create some rows before alteration
  2309. rendered_state = project_state.apps
  2310. pony = rendered_state.get_model("test_alorwrtto", "Pony").objects.create(weight=50)
  2311. rendered_state.get_model("test_alorwrtto", "Rider").objects.create(pony=pony, friend_id=1)
  2312. rendered_state.get_model("test_alorwrtto", "Rider").objects.create(pony=pony, friend_id=2)
  2313. # Test the database alteration
  2314. with connection.schema_editor() as editor:
  2315. operation.database_forwards("test_alorwrtto", editor, project_state, new_state)
  2316. self.assertColumnExists("test_alorwrtto_rider", "_order")
  2317. # Check for correct value in rows
  2318. updated_riders = new_state.apps.get_model("test_alorwrtto", "Rider").objects.all()
  2319. self.assertEqual(updated_riders[0]._order, 0)
  2320. self.assertEqual(updated_riders[1]._order, 0)
  2321. # And test reversal
  2322. with connection.schema_editor() as editor:
  2323. operation.database_backwards("test_alorwrtto", editor, new_state, project_state)
  2324. self.assertColumnNotExists("test_alorwrtto_rider", "_order")
  2325. # And deconstruction
  2326. definition = operation.deconstruct()
  2327. self.assertEqual(definition[0], "AlterOrderWithRespectTo")
  2328. self.assertEqual(definition[1], [])
  2329. self.assertEqual(definition[2], {'name': "Rider", 'order_with_respect_to': "pony"})
  2330. def test_alter_model_managers(self):
  2331. """
  2332. The managers on a model are set.
  2333. """
  2334. project_state = self.set_up_test_model("test_almoma")
  2335. # Test the state alteration
  2336. operation = migrations.AlterModelManagers(
  2337. "Pony",
  2338. managers=[
  2339. ("food_qs", FoodQuerySet.as_manager()),
  2340. ("food_mgr", FoodManager("a", "b")),
  2341. ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)),
  2342. ]
  2343. )
  2344. self.assertEqual(operation.describe(), "Change managers on Pony")
  2345. self.assertEqual(operation.migration_name_fragment, 'alter_pony_managers')
  2346. managers = project_state.models["test_almoma", "pony"].managers
  2347. self.assertEqual(managers, [])
  2348. new_state = project_state.clone()
  2349. operation.state_forwards("test_almoma", new_state)
  2350. self.assertIn(("test_almoma", "pony"), new_state.models)
  2351. managers = new_state.models["test_almoma", "pony"].managers
  2352. self.assertEqual(managers[0][0], "food_qs")
  2353. self.assertIsInstance(managers[0][1], models.Manager)
  2354. self.assertEqual(managers[1][0], "food_mgr")
  2355. self.assertIsInstance(managers[1][1], FoodManager)
  2356. self.assertEqual(managers[1][1].args, ("a", "b", 1, 2))
  2357. self.assertEqual(managers[2][0], "food_mgr_kwargs")
  2358. self.assertIsInstance(managers[2][1], FoodManager)
  2359. self.assertEqual(managers[2][1].args, ("x", "y", 3, 4))
  2360. rendered_state = new_state.apps
  2361. model = rendered_state.get_model('test_almoma', 'pony')
  2362. self.assertIsInstance(model.food_qs, models.Manager)
  2363. self.assertIsInstance(model.food_mgr, FoodManager)
  2364. self.assertIsInstance(model.food_mgr_kwargs, FoodManager)
  2365. def test_alter_model_managers_emptying(self):
  2366. """
  2367. The managers on a model are set.
  2368. """
  2369. project_state = self.set_up_test_model("test_almomae", manager_model=True)
  2370. # Test the state alteration
  2371. operation = migrations.AlterModelManagers("Food", managers=[])
  2372. self.assertEqual(operation.describe(), "Change managers on Food")
  2373. self.assertIn(("test_almomae", "food"), project_state.models)
  2374. managers = project_state.models["test_almomae", "food"].managers
  2375. self.assertEqual(managers[0][0], "food_qs")
  2376. self.assertIsInstance(managers[0][1], models.Manager)
  2377. self.assertEqual(managers[1][0], "food_mgr")
  2378. self.assertIsInstance(managers[1][1], FoodManager)
  2379. self.assertEqual(managers[1][1].args, ("a", "b", 1, 2))
  2380. self.assertEqual(managers[2][0], "food_mgr_kwargs")
  2381. self.assertIsInstance(managers[2][1], FoodManager)
  2382. self.assertEqual(managers[2][1].args, ("x", "y", 3, 4))
  2383. new_state = project_state.clone()
  2384. operation.state_forwards("test_almomae", new_state)
  2385. managers = new_state.models["test_almomae", "food"].managers
  2386. self.assertEqual(managers, [])
  2387. def test_alter_fk(self):
  2388. """
  2389. Creating and then altering an FK works correctly
  2390. and deals with the pending SQL (#23091)
  2391. """
  2392. project_state = self.set_up_test_model("test_alfk")
  2393. # Test adding and then altering the FK in one go
  2394. create_operation = migrations.CreateModel(
  2395. name="Rider",
  2396. fields=[
  2397. ("id", models.AutoField(primary_key=True)),
  2398. ("pony", models.ForeignKey("Pony", models.CASCADE)),
  2399. ],
  2400. )
  2401. create_state = project_state.clone()
  2402. create_operation.state_forwards("test_alfk", create_state)
  2403. alter_operation = migrations.AlterField(
  2404. model_name='Rider',
  2405. name='pony',
  2406. field=models.ForeignKey("Pony", models.CASCADE, editable=False),
  2407. )
  2408. alter_state = create_state.clone()
  2409. alter_operation.state_forwards("test_alfk", alter_state)
  2410. with connection.schema_editor() as editor:
  2411. create_operation.database_forwards("test_alfk", editor, project_state, create_state)
  2412. alter_operation.database_forwards("test_alfk", editor, create_state, alter_state)
  2413. def test_alter_fk_non_fk(self):
  2414. """
  2415. Altering an FK to a non-FK works (#23244)
  2416. """
  2417. # Test the state alteration
  2418. operation = migrations.AlterField(
  2419. model_name="Rider",
  2420. name="pony",
  2421. field=models.FloatField(),
  2422. )
  2423. project_state, new_state = self.make_test_state("test_afknfk", operation, related_model=True)
  2424. # Test the database alteration
  2425. self.assertColumnExists("test_afknfk_rider", "pony_id")
  2426. self.assertColumnNotExists("test_afknfk_rider", "pony")
  2427. with connection.schema_editor() as editor:
  2428. operation.database_forwards("test_afknfk", editor, project_state, new_state)
  2429. self.assertColumnExists("test_afknfk_rider", "pony")
  2430. self.assertColumnNotExists("test_afknfk_rider", "pony_id")
  2431. # And test reversal
  2432. with connection.schema_editor() as editor:
  2433. operation.database_backwards("test_afknfk", editor, new_state, project_state)
  2434. self.assertColumnExists("test_afknfk_rider", "pony_id")
  2435. self.assertColumnNotExists("test_afknfk_rider", "pony")
  2436. def test_run_sql(self):
  2437. """
  2438. Tests the RunSQL operation.
  2439. """
  2440. project_state = self.set_up_test_model("test_runsql")
  2441. # Create the operation
  2442. operation = migrations.RunSQL(
  2443. # Use a multi-line string with a comment to test splitting on SQLite and MySQL respectively
  2444. "CREATE TABLE i_love_ponies (id int, special_thing varchar(15));\n"
  2445. "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 'i love ponies'); -- this is magic!\n"
  2446. "INSERT INTO i_love_ponies (id, special_thing) VALUES (2, 'i love django');\n"
  2447. "UPDATE i_love_ponies SET special_thing = 'Ponies' WHERE special_thing LIKE '%%ponies';"
  2448. "UPDATE i_love_ponies SET special_thing = 'Django' WHERE special_thing LIKE '%django';",
  2449. # Run delete queries to test for parameter substitution failure
  2450. # reported in #23426
  2451. "DELETE FROM i_love_ponies WHERE special_thing LIKE '%Django%';"
  2452. "DELETE FROM i_love_ponies WHERE special_thing LIKE '%%Ponies%%';"
  2453. "DROP TABLE i_love_ponies",
  2454. state_operations=[migrations.CreateModel("SomethingElse", [("id", models.AutoField(primary_key=True))])],
  2455. )
  2456. self.assertEqual(operation.describe(), "Raw SQL operation")
  2457. # Test the state alteration
  2458. new_state = project_state.clone()
  2459. operation.state_forwards("test_runsql", new_state)
  2460. self.assertEqual(len(new_state.models["test_runsql", "somethingelse"].fields), 1)
  2461. # Make sure there's no table
  2462. self.assertTableNotExists("i_love_ponies")
  2463. # Test SQL collection
  2464. with connection.schema_editor(collect_sql=True) as editor:
  2465. operation.database_forwards("test_runsql", editor, project_state, new_state)
  2466. self.assertIn("LIKE '%%ponies';", "\n".join(editor.collected_sql))
  2467. operation.database_backwards("test_runsql", editor, project_state, new_state)
  2468. self.assertIn("LIKE '%%Ponies%%';", "\n".join(editor.collected_sql))
  2469. # Test the database alteration
  2470. with connection.schema_editor() as editor:
  2471. operation.database_forwards("test_runsql", editor, project_state, new_state)
  2472. self.assertTableExists("i_love_ponies")
  2473. # Make sure all the SQL was processed
  2474. with connection.cursor() as cursor:
  2475. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  2476. self.assertEqual(cursor.fetchall()[0][0], 2)
  2477. cursor.execute("SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Django'")
  2478. self.assertEqual(cursor.fetchall()[0][0], 1)
  2479. cursor.execute("SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Ponies'")
  2480. self.assertEqual(cursor.fetchall()[0][0], 1)
  2481. # And test reversal
  2482. self.assertTrue(operation.reversible)
  2483. with connection.schema_editor() as editor:
  2484. operation.database_backwards("test_runsql", editor, new_state, project_state)
  2485. self.assertTableNotExists("i_love_ponies")
  2486. # And deconstruction
  2487. definition = operation.deconstruct()
  2488. self.assertEqual(definition[0], "RunSQL")
  2489. self.assertEqual(definition[1], [])
  2490. self.assertEqual(sorted(definition[2]), ["reverse_sql", "sql", "state_operations"])
  2491. # And elidable reduction
  2492. self.assertIs(False, operation.reduce(operation, []))
  2493. elidable_operation = migrations.RunSQL('SELECT 1 FROM void;', elidable=True)
  2494. self.assertEqual(elidable_operation.reduce(operation, []), [operation])
  2495. def test_run_sql_params(self):
  2496. """
  2497. #23426 - RunSQL should accept parameters.
  2498. """
  2499. project_state = self.set_up_test_model("test_runsql")
  2500. # Create the operation
  2501. operation = migrations.RunSQL(
  2502. ["CREATE TABLE i_love_ponies (id int, special_thing varchar(15));"],
  2503. ["DROP TABLE i_love_ponies"],
  2504. )
  2505. param_operation = migrations.RunSQL(
  2506. # forwards
  2507. (
  2508. "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 'Django');",
  2509. ["INSERT INTO i_love_ponies (id, special_thing) VALUES (2, %s);", ['Ponies']],
  2510. ("INSERT INTO i_love_ponies (id, special_thing) VALUES (%s, %s);", (3, 'Python',)),
  2511. ),
  2512. # backwards
  2513. [
  2514. "DELETE FROM i_love_ponies WHERE special_thing = 'Django';",
  2515. ["DELETE FROM i_love_ponies WHERE special_thing = 'Ponies';", None],
  2516. ("DELETE FROM i_love_ponies WHERE id = %s OR special_thing = %s;", [3, 'Python']),
  2517. ]
  2518. )
  2519. # Make sure there's no table
  2520. self.assertTableNotExists("i_love_ponies")
  2521. new_state = project_state.clone()
  2522. # Test the database alteration
  2523. with connection.schema_editor() as editor:
  2524. operation.database_forwards("test_runsql", editor, project_state, new_state)
  2525. # Test parameter passing
  2526. with connection.schema_editor() as editor:
  2527. param_operation.database_forwards("test_runsql", editor, project_state, new_state)
  2528. # Make sure all the SQL was processed
  2529. with connection.cursor() as cursor:
  2530. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  2531. self.assertEqual(cursor.fetchall()[0][0], 3)
  2532. with connection.schema_editor() as editor:
  2533. param_operation.database_backwards("test_runsql", editor, new_state, project_state)
  2534. with connection.cursor() as cursor:
  2535. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  2536. self.assertEqual(cursor.fetchall()[0][0], 0)
  2537. # And test reversal
  2538. with connection.schema_editor() as editor:
  2539. operation.database_backwards("test_runsql", editor, new_state, project_state)
  2540. self.assertTableNotExists("i_love_ponies")
  2541. def test_run_sql_params_invalid(self):
  2542. """
  2543. #23426 - RunSQL should fail when a list of statements with an incorrect
  2544. number of tuples is given.
  2545. """
  2546. project_state = self.set_up_test_model("test_runsql")
  2547. new_state = project_state.clone()
  2548. operation = migrations.RunSQL(
  2549. # forwards
  2550. [
  2551. ["INSERT INTO foo (bar) VALUES ('buz');"]
  2552. ],
  2553. # backwards
  2554. (
  2555. ("DELETE FROM foo WHERE bar = 'buz';", 'invalid', 'parameter count'),
  2556. ),
  2557. )
  2558. with connection.schema_editor() as editor:
  2559. with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 1"):
  2560. operation.database_forwards("test_runsql", editor, project_state, new_state)
  2561. with connection.schema_editor() as editor:
  2562. with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 3"):
  2563. operation.database_backwards("test_runsql", editor, new_state, project_state)
  2564. def test_run_sql_noop(self):
  2565. """
  2566. #24098 - Tests no-op RunSQL operations.
  2567. """
  2568. operation = migrations.RunSQL(migrations.RunSQL.noop, migrations.RunSQL.noop)
  2569. with connection.schema_editor() as editor:
  2570. operation.database_forwards("test_runsql", editor, None, None)
  2571. operation.database_backwards("test_runsql", editor, None, None)
  2572. def test_run_python(self):
  2573. """
  2574. Tests the RunPython operation
  2575. """
  2576. project_state = self.set_up_test_model("test_runpython", mti_model=True)
  2577. # Create the operation
  2578. def inner_method(models, schema_editor):
  2579. Pony = models.get_model("test_runpython", "Pony")
  2580. Pony.objects.create(pink=1, weight=3.55)
  2581. Pony.objects.create(weight=5)
  2582. def inner_method_reverse(models, schema_editor):
  2583. Pony = models.get_model("test_runpython", "Pony")
  2584. Pony.objects.filter(pink=1, weight=3.55).delete()
  2585. Pony.objects.filter(weight=5).delete()
  2586. operation = migrations.RunPython(inner_method, reverse_code=inner_method_reverse)
  2587. self.assertEqual(operation.describe(), "Raw Python operation")
  2588. # Test the state alteration does nothing
  2589. new_state = project_state.clone()
  2590. operation.state_forwards("test_runpython", new_state)
  2591. self.assertEqual(new_state, project_state)
  2592. # Test the database alteration
  2593. self.assertEqual(project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0)
  2594. with connection.schema_editor() as editor:
  2595. operation.database_forwards("test_runpython", editor, project_state, new_state)
  2596. self.assertEqual(project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2)
  2597. # Now test reversal
  2598. self.assertTrue(operation.reversible)
  2599. with connection.schema_editor() as editor:
  2600. operation.database_backwards("test_runpython", editor, project_state, new_state)
  2601. self.assertEqual(project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0)
  2602. # Now test we can't use a string
  2603. with self.assertRaisesMessage(ValueError, 'RunPython must be supplied with a callable'):
  2604. migrations.RunPython("print 'ahahaha'")
  2605. # And deconstruction
  2606. definition = operation.deconstruct()
  2607. self.assertEqual(definition[0], "RunPython")
  2608. self.assertEqual(definition[1], [])
  2609. self.assertEqual(sorted(definition[2]), ["code", "reverse_code"])
  2610. # Also test reversal fails, with an operation identical to above but without reverse_code set
  2611. no_reverse_operation = migrations.RunPython(inner_method)
  2612. self.assertFalse(no_reverse_operation.reversible)
  2613. with connection.schema_editor() as editor:
  2614. no_reverse_operation.database_forwards("test_runpython", editor, project_state, new_state)
  2615. with self.assertRaises(NotImplementedError):
  2616. no_reverse_operation.database_backwards("test_runpython", editor, new_state, project_state)
  2617. self.assertEqual(project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2)
  2618. def create_ponies(models, schema_editor):
  2619. Pony = models.get_model("test_runpython", "Pony")
  2620. pony1 = Pony.objects.create(pink=1, weight=3.55)
  2621. self.assertIsNot(pony1.pk, None)
  2622. pony2 = Pony.objects.create(weight=5)
  2623. self.assertIsNot(pony2.pk, None)
  2624. self.assertNotEqual(pony1.pk, pony2.pk)
  2625. operation = migrations.RunPython(create_ponies)
  2626. with connection.schema_editor() as editor:
  2627. operation.database_forwards("test_runpython", editor, project_state, new_state)
  2628. self.assertEqual(project_state.apps.get_model("test_runpython", "Pony").objects.count(), 4)
  2629. # And deconstruction
  2630. definition = operation.deconstruct()
  2631. self.assertEqual(definition[0], "RunPython")
  2632. self.assertEqual(definition[1], [])
  2633. self.assertEqual(sorted(definition[2]), ["code"])
  2634. def create_shetlandponies(models, schema_editor):
  2635. ShetlandPony = models.get_model("test_runpython", "ShetlandPony")
  2636. pony1 = ShetlandPony.objects.create(weight=4.0)
  2637. self.assertIsNot(pony1.pk, None)
  2638. pony2 = ShetlandPony.objects.create(weight=5.0)
  2639. self.assertIsNot(pony2.pk, None)
  2640. self.assertNotEqual(pony1.pk, pony2.pk)
  2641. operation = migrations.RunPython(create_shetlandponies)
  2642. with connection.schema_editor() as editor:
  2643. operation.database_forwards("test_runpython", editor, project_state, new_state)
  2644. self.assertEqual(project_state.apps.get_model("test_runpython", "Pony").objects.count(), 6)
  2645. self.assertEqual(project_state.apps.get_model("test_runpython", "ShetlandPony").objects.count(), 2)
  2646. # And elidable reduction
  2647. self.assertIs(False, operation.reduce(operation, []))
  2648. elidable_operation = migrations.RunPython(inner_method, elidable=True)
  2649. self.assertEqual(elidable_operation.reduce(operation, []), [operation])
  2650. def test_run_python_atomic(self):
  2651. """
  2652. Tests the RunPython operation correctly handles the "atomic" keyword
  2653. """
  2654. project_state = self.set_up_test_model("test_runpythonatomic", mti_model=True)
  2655. def inner_method(models, schema_editor):
  2656. Pony = models.get_model("test_runpythonatomic", "Pony")
  2657. Pony.objects.create(pink=1, weight=3.55)
  2658. raise ValueError("Adrian hates ponies.")
  2659. # Verify atomicity when applying.
  2660. atomic_migration = Migration("test", "test_runpythonatomic")
  2661. atomic_migration.operations = [migrations.RunPython(inner_method, reverse_code=inner_method)]
  2662. non_atomic_migration = Migration("test", "test_runpythonatomic")
  2663. non_atomic_migration.operations = [migrations.RunPython(inner_method, reverse_code=inner_method, atomic=False)]
  2664. # If we're a fully-transactional database, both versions should rollback
  2665. if connection.features.can_rollback_ddl:
  2666. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2667. with self.assertRaises(ValueError):
  2668. with connection.schema_editor() as editor:
  2669. atomic_migration.apply(project_state, editor)
  2670. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2671. with self.assertRaises(ValueError):
  2672. with connection.schema_editor() as editor:
  2673. non_atomic_migration.apply(project_state, editor)
  2674. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2675. # Otherwise, the non-atomic operation should leave a row there
  2676. else:
  2677. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2678. with self.assertRaises(ValueError):
  2679. with connection.schema_editor() as editor:
  2680. atomic_migration.apply(project_state, editor)
  2681. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2682. with self.assertRaises(ValueError):
  2683. with connection.schema_editor() as editor:
  2684. non_atomic_migration.apply(project_state, editor)
  2685. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 1)
  2686. # Reset object count to zero and verify atomicity when unapplying.
  2687. project_state.apps.get_model("test_runpythonatomic", "Pony").objects.all().delete()
  2688. # On a fully-transactional database, both versions rollback.
  2689. if connection.features.can_rollback_ddl:
  2690. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2691. with self.assertRaises(ValueError):
  2692. with connection.schema_editor() as editor:
  2693. atomic_migration.unapply(project_state, editor)
  2694. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2695. with self.assertRaises(ValueError):
  2696. with connection.schema_editor() as editor:
  2697. non_atomic_migration.unapply(project_state, editor)
  2698. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2699. # Otherwise, the non-atomic operation leaves a row there.
  2700. else:
  2701. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2702. with self.assertRaises(ValueError):
  2703. with connection.schema_editor() as editor:
  2704. atomic_migration.unapply(project_state, editor)
  2705. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  2706. with self.assertRaises(ValueError):
  2707. with connection.schema_editor() as editor:
  2708. non_atomic_migration.unapply(project_state, editor)
  2709. self.assertEqual(project_state.apps.get_model("test_runpythonatomic", "Pony").objects.count(), 1)
  2710. # Verify deconstruction.
  2711. definition = non_atomic_migration.operations[0].deconstruct()
  2712. self.assertEqual(definition[0], "RunPython")
  2713. self.assertEqual(definition[1], [])
  2714. self.assertEqual(sorted(definition[2]), ["atomic", "code", "reverse_code"])
  2715. def test_run_python_related_assignment(self):
  2716. """
  2717. #24282 - Model changes to a FK reverse side update the model
  2718. on the FK side as well.
  2719. """
  2720. def inner_method(models, schema_editor):
  2721. Author = models.get_model("test_authors", "Author")
  2722. Book = models.get_model("test_books", "Book")
  2723. author = Author.objects.create(name="Hemingway")
  2724. Book.objects.create(title="Old Man and The Sea", author=author)
  2725. create_author = migrations.CreateModel(
  2726. "Author",
  2727. [
  2728. ("id", models.AutoField(primary_key=True)),
  2729. ("name", models.CharField(max_length=100)),
  2730. ],
  2731. options={},
  2732. )
  2733. create_book = migrations.CreateModel(
  2734. "Book",
  2735. [
  2736. ("id", models.AutoField(primary_key=True)),
  2737. ("title", models.CharField(max_length=100)),
  2738. ("author", models.ForeignKey("test_authors.Author", models.CASCADE))
  2739. ],
  2740. options={},
  2741. )
  2742. add_hometown = migrations.AddField(
  2743. "Author",
  2744. "hometown",
  2745. models.CharField(max_length=100),
  2746. )
  2747. create_old_man = migrations.RunPython(inner_method, inner_method)
  2748. project_state = ProjectState()
  2749. new_state = project_state.clone()
  2750. with connection.schema_editor() as editor:
  2751. create_author.state_forwards("test_authors", new_state)
  2752. create_author.database_forwards("test_authors", editor, project_state, new_state)
  2753. project_state = new_state
  2754. new_state = new_state.clone()
  2755. with connection.schema_editor() as editor:
  2756. create_book.state_forwards("test_books", new_state)
  2757. create_book.database_forwards("test_books", editor, project_state, new_state)
  2758. project_state = new_state
  2759. new_state = new_state.clone()
  2760. with connection.schema_editor() as editor:
  2761. add_hometown.state_forwards("test_authors", new_state)
  2762. add_hometown.database_forwards("test_authors", editor, project_state, new_state)
  2763. project_state = new_state
  2764. new_state = new_state.clone()
  2765. with connection.schema_editor() as editor:
  2766. create_old_man.state_forwards("test_books", new_state)
  2767. create_old_man.database_forwards("test_books", editor, project_state, new_state)
  2768. def test_model_with_bigautofield(self):
  2769. """
  2770. A model with BigAutoField can be created.
  2771. """
  2772. def create_data(models, schema_editor):
  2773. Author = models.get_model("test_author", "Author")
  2774. Book = models.get_model("test_book", "Book")
  2775. author1 = Author.objects.create(name="Hemingway")
  2776. Book.objects.create(title="Old Man and The Sea", author=author1)
  2777. Book.objects.create(id=2 ** 33, title="A farewell to arms", author=author1)
  2778. author2 = Author.objects.create(id=2 ** 33, name="Remarque")
  2779. Book.objects.create(title="All quiet on the western front", author=author2)
  2780. Book.objects.create(title="Arc de Triomphe", author=author2)
  2781. create_author = migrations.CreateModel(
  2782. "Author",
  2783. [
  2784. ("id", models.BigAutoField(primary_key=True)),
  2785. ("name", models.CharField(max_length=100)),
  2786. ],
  2787. options={},
  2788. )
  2789. create_book = migrations.CreateModel(
  2790. "Book",
  2791. [
  2792. ("id", models.BigAutoField(primary_key=True)),
  2793. ("title", models.CharField(max_length=100)),
  2794. ("author", models.ForeignKey(to="test_author.Author", on_delete=models.CASCADE))
  2795. ],
  2796. options={},
  2797. )
  2798. fill_data = migrations.RunPython(create_data)
  2799. project_state = ProjectState()
  2800. new_state = project_state.clone()
  2801. with connection.schema_editor() as editor:
  2802. create_author.state_forwards("test_author", new_state)
  2803. create_author.database_forwards("test_author", editor, project_state, new_state)
  2804. project_state = new_state
  2805. new_state = new_state.clone()
  2806. with connection.schema_editor() as editor:
  2807. create_book.state_forwards("test_book", new_state)
  2808. create_book.database_forwards("test_book", editor, project_state, new_state)
  2809. project_state = new_state
  2810. new_state = new_state.clone()
  2811. with connection.schema_editor() as editor:
  2812. fill_data.state_forwards("fill_data", new_state)
  2813. fill_data.database_forwards("fill_data", editor, project_state, new_state)
  2814. def _test_autofield_foreignfield_growth(self, source_field, target_field, target_value):
  2815. """
  2816. A field may be migrated in the following ways:
  2817. - AutoField to BigAutoField
  2818. - SmallAutoField to AutoField
  2819. - SmallAutoField to BigAutoField
  2820. """
  2821. def create_initial_data(models, schema_editor):
  2822. Article = models.get_model("test_article", "Article")
  2823. Blog = models.get_model("test_blog", "Blog")
  2824. blog = Blog.objects.create(name="web development done right")
  2825. Article.objects.create(name="Frameworks", blog=blog)
  2826. Article.objects.create(name="Programming Languages", blog=blog)
  2827. def create_big_data(models, schema_editor):
  2828. Article = models.get_model("test_article", "Article")
  2829. Blog = models.get_model("test_blog", "Blog")
  2830. blog2 = Blog.objects.create(name="Frameworks", id=target_value)
  2831. Article.objects.create(name="Django", blog=blog2)
  2832. Article.objects.create(id=target_value, name="Django2", blog=blog2)
  2833. create_blog = migrations.CreateModel(
  2834. "Blog",
  2835. [
  2836. ("id", source_field(primary_key=True)),
  2837. ("name", models.CharField(max_length=100)),
  2838. ],
  2839. options={},
  2840. )
  2841. create_article = migrations.CreateModel(
  2842. "Article",
  2843. [
  2844. ("id", source_field(primary_key=True)),
  2845. ("blog", models.ForeignKey(to="test_blog.Blog", on_delete=models.CASCADE)),
  2846. ("name", models.CharField(max_length=100)),
  2847. ("data", models.TextField(default="")),
  2848. ],
  2849. options={},
  2850. )
  2851. fill_initial_data = migrations.RunPython(create_initial_data, create_initial_data)
  2852. fill_big_data = migrations.RunPython(create_big_data, create_big_data)
  2853. grow_article_id = migrations.AlterField('Article', 'id', target_field(primary_key=True))
  2854. grow_blog_id = migrations.AlterField('Blog', 'id', target_field(primary_key=True))
  2855. project_state = ProjectState()
  2856. new_state = project_state.clone()
  2857. with connection.schema_editor() as editor:
  2858. create_blog.state_forwards("test_blog", new_state)
  2859. create_blog.database_forwards("test_blog", editor, project_state, new_state)
  2860. project_state = new_state
  2861. new_state = new_state.clone()
  2862. with connection.schema_editor() as editor:
  2863. create_article.state_forwards("test_article", new_state)
  2864. create_article.database_forwards("test_article", editor, project_state, new_state)
  2865. project_state = new_state
  2866. new_state = new_state.clone()
  2867. with connection.schema_editor() as editor:
  2868. fill_initial_data.state_forwards("fill_initial_data", new_state)
  2869. fill_initial_data.database_forwards("fill_initial_data", editor, project_state, new_state)
  2870. project_state = new_state
  2871. new_state = new_state.clone()
  2872. with connection.schema_editor() as editor:
  2873. grow_article_id.state_forwards("test_article", new_state)
  2874. grow_article_id.database_forwards("test_article", editor, project_state, new_state)
  2875. state = new_state.clone()
  2876. article = state.apps.get_model("test_article.Article")
  2877. self.assertIsInstance(article._meta.pk, target_field)
  2878. project_state = new_state
  2879. new_state = new_state.clone()
  2880. with connection.schema_editor() as editor:
  2881. grow_blog_id.state_forwards("test_blog", new_state)
  2882. grow_blog_id.database_forwards("test_blog", editor, project_state, new_state)
  2883. state = new_state.clone()
  2884. blog = state.apps.get_model("test_blog.Blog")
  2885. self.assertIsInstance(blog._meta.pk, target_field)
  2886. project_state = new_state
  2887. new_state = new_state.clone()
  2888. with connection.schema_editor() as editor:
  2889. fill_big_data.state_forwards("fill_big_data", new_state)
  2890. fill_big_data.database_forwards("fill_big_data", editor, project_state, new_state)
  2891. def test_autofield__bigautofield_foreignfield_growth(self):
  2892. """A field may be migrated from AutoField to BigAutoField."""
  2893. self._test_autofield_foreignfield_growth(
  2894. models.AutoField,
  2895. models.BigAutoField,
  2896. 2 ** 33,
  2897. )
  2898. def test_smallfield_autofield_foreignfield_growth(self):
  2899. """A field may be migrated from SmallAutoField to AutoField."""
  2900. self._test_autofield_foreignfield_growth(
  2901. models.SmallAutoField,
  2902. models.AutoField,
  2903. 2 ** 22,
  2904. )
  2905. def test_smallfield_bigautofield_foreignfield_growth(self):
  2906. """A field may be migrated from SmallAutoField to BigAutoField."""
  2907. self._test_autofield_foreignfield_growth(
  2908. models.SmallAutoField,
  2909. models.BigAutoField,
  2910. 2 ** 33,
  2911. )
  2912. def test_run_python_noop(self):
  2913. """
  2914. #24098 - Tests no-op RunPython operations.
  2915. """
  2916. project_state = ProjectState()
  2917. new_state = project_state.clone()
  2918. operation = migrations.RunPython(migrations.RunPython.noop, migrations.RunPython.noop)
  2919. with connection.schema_editor() as editor:
  2920. operation.database_forwards("test_runpython", editor, project_state, new_state)
  2921. operation.database_backwards("test_runpython", editor, new_state, project_state)
  2922. def test_separate_database_and_state(self):
  2923. """
  2924. Tests the SeparateDatabaseAndState operation.
  2925. """
  2926. project_state = self.set_up_test_model("test_separatedatabaseandstate")
  2927. # Create the operation
  2928. database_operation = migrations.RunSQL(
  2929. "CREATE TABLE i_love_ponies (id int, special_thing int);",
  2930. "DROP TABLE i_love_ponies;"
  2931. )
  2932. state_operation = migrations.CreateModel("SomethingElse", [("id", models.AutoField(primary_key=True))])
  2933. operation = migrations.SeparateDatabaseAndState(
  2934. state_operations=[state_operation],
  2935. database_operations=[database_operation]
  2936. )
  2937. self.assertEqual(operation.describe(), "Custom state/database change combination")
  2938. # Test the state alteration
  2939. new_state = project_state.clone()
  2940. operation.state_forwards("test_separatedatabaseandstate", new_state)
  2941. self.assertEqual(len(new_state.models["test_separatedatabaseandstate", "somethingelse"].fields), 1)
  2942. # Make sure there's no table
  2943. self.assertTableNotExists("i_love_ponies")
  2944. # Test the database alteration
  2945. with connection.schema_editor() as editor:
  2946. operation.database_forwards("test_separatedatabaseandstate", editor, project_state, new_state)
  2947. self.assertTableExists("i_love_ponies")
  2948. # And test reversal
  2949. self.assertTrue(operation.reversible)
  2950. with connection.schema_editor() as editor:
  2951. operation.database_backwards("test_separatedatabaseandstate", editor, new_state, project_state)
  2952. self.assertTableNotExists("i_love_ponies")
  2953. # And deconstruction
  2954. definition = operation.deconstruct()
  2955. self.assertEqual(definition[0], "SeparateDatabaseAndState")
  2956. self.assertEqual(definition[1], [])
  2957. self.assertEqual(sorted(definition[2]), ["database_operations", "state_operations"])
  2958. def test_separate_database_and_state2(self):
  2959. """
  2960. A complex SeparateDatabaseAndState operation: Multiple operations both
  2961. for state and database. Verify the state dependencies within each list
  2962. and that state ops don't affect the database.
  2963. """
  2964. app_label = "test_separatedatabaseandstate2"
  2965. project_state = self.set_up_test_model(app_label)
  2966. # Create the operation
  2967. database_operations = [
  2968. migrations.CreateModel(
  2969. "ILovePonies",
  2970. [("id", models.AutoField(primary_key=True))],
  2971. options={"db_table": "iloveponies"},
  2972. ),
  2973. migrations.CreateModel(
  2974. "ILoveMorePonies",
  2975. # We use IntegerField and not AutoField because
  2976. # the model is going to be deleted immediately
  2977. # and with an AutoField this fails on Oracle
  2978. [("id", models.IntegerField(primary_key=True))],
  2979. options={"db_table": "ilovemoreponies"},
  2980. ),
  2981. migrations.DeleteModel("ILoveMorePonies"),
  2982. migrations.CreateModel(
  2983. "ILoveEvenMorePonies",
  2984. [("id", models.AutoField(primary_key=True))],
  2985. options={"db_table": "iloveevenmoreponies"},
  2986. ),
  2987. ]
  2988. state_operations = [
  2989. migrations.CreateModel(
  2990. "SomethingElse",
  2991. [("id", models.AutoField(primary_key=True))],
  2992. options={"db_table": "somethingelse"},
  2993. ),
  2994. migrations.DeleteModel("SomethingElse"),
  2995. migrations.CreateModel(
  2996. "SomethingCompletelyDifferent",
  2997. [("id", models.AutoField(primary_key=True))],
  2998. options={"db_table": "somethingcompletelydifferent"},
  2999. ),
  3000. ]
  3001. operation = migrations.SeparateDatabaseAndState(
  3002. state_operations=state_operations,
  3003. database_operations=database_operations,
  3004. )
  3005. # Test the state alteration
  3006. new_state = project_state.clone()
  3007. operation.state_forwards(app_label, new_state)
  3008. def assertModelsAndTables(after_db):
  3009. # Tables and models exist, or don't, as they should:
  3010. self.assertNotIn((app_label, "somethingelse"), new_state.models)
  3011. self.assertEqual(len(new_state.models[app_label, "somethingcompletelydifferent"].fields), 1)
  3012. self.assertNotIn((app_label, "iloveponiesonies"), new_state.models)
  3013. self.assertNotIn((app_label, "ilovemoreponies"), new_state.models)
  3014. self.assertNotIn((app_label, "iloveevenmoreponies"), new_state.models)
  3015. self.assertTableNotExists("somethingelse")
  3016. self.assertTableNotExists("somethingcompletelydifferent")
  3017. self.assertTableNotExists("ilovemoreponies")
  3018. if after_db:
  3019. self.assertTableExists("iloveponies")
  3020. self.assertTableExists("iloveevenmoreponies")
  3021. else:
  3022. self.assertTableNotExists("iloveponies")
  3023. self.assertTableNotExists("iloveevenmoreponies")
  3024. assertModelsAndTables(after_db=False)
  3025. # Test the database alteration
  3026. with connection.schema_editor() as editor:
  3027. operation.database_forwards(app_label, editor, project_state, new_state)
  3028. assertModelsAndTables(after_db=True)
  3029. # And test reversal
  3030. self.assertTrue(operation.reversible)
  3031. with connection.schema_editor() as editor:
  3032. operation.database_backwards(app_label, editor, new_state, project_state)
  3033. assertModelsAndTables(after_db=False)
  3034. class SwappableOperationTests(OperationTestBase):
  3035. """
  3036. Key operations ignore swappable models
  3037. (we don't want to replicate all of them here, as the functionality
  3038. is in a common base class anyway)
  3039. """
  3040. available_apps = ['migrations']
  3041. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  3042. def test_create_ignore_swapped(self):
  3043. """
  3044. The CreateTable operation ignores swapped models.
  3045. """
  3046. operation = migrations.CreateModel(
  3047. "Pony",
  3048. [
  3049. ("id", models.AutoField(primary_key=True)),
  3050. ("pink", models.IntegerField(default=1)),
  3051. ],
  3052. options={
  3053. "swappable": "TEST_SWAP_MODEL",
  3054. },
  3055. )
  3056. # Test the state alteration (it should still be there!)
  3057. project_state = ProjectState()
  3058. new_state = project_state.clone()
  3059. operation.state_forwards("test_crigsw", new_state)
  3060. self.assertEqual(new_state.models["test_crigsw", "pony"].name, "Pony")
  3061. self.assertEqual(len(new_state.models["test_crigsw", "pony"].fields), 2)
  3062. # Test the database alteration
  3063. self.assertTableNotExists("test_crigsw_pony")
  3064. with connection.schema_editor() as editor:
  3065. operation.database_forwards("test_crigsw", editor, project_state, new_state)
  3066. self.assertTableNotExists("test_crigsw_pony")
  3067. # And test reversal
  3068. with connection.schema_editor() as editor:
  3069. operation.database_backwards("test_crigsw", editor, new_state, project_state)
  3070. self.assertTableNotExists("test_crigsw_pony")
  3071. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  3072. def test_delete_ignore_swapped(self):
  3073. """
  3074. Tests the DeleteModel operation ignores swapped models.
  3075. """
  3076. operation = migrations.DeleteModel("Pony")
  3077. project_state, new_state = self.make_test_state("test_dligsw", operation)
  3078. # Test the database alteration
  3079. self.assertTableNotExists("test_dligsw_pony")
  3080. with connection.schema_editor() as editor:
  3081. operation.database_forwards("test_dligsw", editor, project_state, new_state)
  3082. self.assertTableNotExists("test_dligsw_pony")
  3083. # And test reversal
  3084. with connection.schema_editor() as editor:
  3085. operation.database_backwards("test_dligsw", editor, new_state, project_state)
  3086. self.assertTableNotExists("test_dligsw_pony")
  3087. @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel")
  3088. def test_add_field_ignore_swapped(self):
  3089. """
  3090. Tests the AddField operation.
  3091. """
  3092. # Test the state alteration
  3093. operation = migrations.AddField(
  3094. "Pony",
  3095. "height",
  3096. models.FloatField(null=True, default=5),
  3097. )
  3098. project_state, new_state = self.make_test_state("test_adfligsw", operation)
  3099. # Test the database alteration
  3100. self.assertTableNotExists("test_adfligsw_pony")
  3101. with connection.schema_editor() as editor:
  3102. operation.database_forwards("test_adfligsw", editor, project_state, new_state)
  3103. self.assertTableNotExists("test_adfligsw_pony")
  3104. # And test reversal
  3105. with connection.schema_editor() as editor:
  3106. operation.database_backwards("test_adfligsw", editor, new_state, project_state)
  3107. self.assertTableNotExists("test_adfligsw_pony")
  3108. @override_settings(TEST_SWAP_MODEL='migrations.SomeFakeModel')
  3109. def test_indexes_ignore_swapped(self):
  3110. """
  3111. Add/RemoveIndex operations ignore swapped models.
  3112. """
  3113. operation = migrations.AddIndex('Pony', models.Index(fields=['pink'], name='my_name_idx'))
  3114. project_state, new_state = self.make_test_state('test_adinigsw', operation)
  3115. with connection.schema_editor() as editor:
  3116. # No database queries should be run for swapped models
  3117. operation.database_forwards('test_adinigsw', editor, project_state, new_state)
  3118. operation.database_backwards('test_adinigsw', editor, new_state, project_state)
  3119. operation = migrations.RemoveIndex('Pony', models.Index(fields=['pink'], name='my_name_idx'))
  3120. project_state, new_state = self.make_test_state("test_rminigsw", operation)
  3121. with connection.schema_editor() as editor:
  3122. operation.database_forwards('test_rminigsw', editor, project_state, new_state)
  3123. operation.database_backwards('test_rminigsw', editor, new_state, project_state)
  3124. class TestCreateModel(SimpleTestCase):
  3125. def test_references_model_mixin(self):
  3126. migrations.CreateModel(
  3127. 'name',
  3128. fields=[],
  3129. bases=(Mixin, models.Model),
  3130. ).references_model('other_model', 'migrations')
  3131. class FieldOperationTests(SimpleTestCase):
  3132. def test_references_model(self):
  3133. operation = FieldOperation('MoDel', 'field', models.ForeignKey('Other', models.CASCADE))
  3134. # Model name match.
  3135. self.assertIs(operation.references_model('mOdEl', 'migrations'), True)
  3136. # Referenced field.
  3137. self.assertIs(operation.references_model('oTher', 'migrations'), True)
  3138. # Doesn't reference.
  3139. self.assertIs(operation.references_model('Whatever', 'migrations'), False)
  3140. def test_references_field_by_name(self):
  3141. operation = FieldOperation('MoDel', 'field', models.BooleanField(default=False))
  3142. self.assertIs(operation.references_field('model', 'field', 'migrations'), True)
  3143. def test_references_field_by_remote_field_model(self):
  3144. operation = FieldOperation('Model', 'field', models.ForeignKey('Other', models.CASCADE))
  3145. self.assertIs(operation.references_field('Other', 'whatever', 'migrations'), True)
  3146. self.assertIs(operation.references_field('Missing', 'whatever', 'migrations'), False)
  3147. def test_references_field_by_from_fields(self):
  3148. operation = FieldOperation(
  3149. 'Model', 'field', models.fields.related.ForeignObject('Other', models.CASCADE, ['from'], ['to'])
  3150. )
  3151. self.assertIs(operation.references_field('Model', 'from', 'migrations'), True)
  3152. self.assertIs(operation.references_field('Model', 'to', 'migrations'), False)
  3153. self.assertIs(operation.references_field('Other', 'from', 'migrations'), False)
  3154. self.assertIs(operation.references_field('Model', 'to', 'migrations'), False)
  3155. def test_references_field_by_to_fields(self):
  3156. operation = FieldOperation('Model', 'field', models.ForeignKey('Other', models.CASCADE, to_field='field'))
  3157. self.assertIs(operation.references_field('Other', 'field', 'migrations'), True)
  3158. self.assertIs(operation.references_field('Other', 'whatever', 'migrations'), False)
  3159. self.assertIs(operation.references_field('Missing', 'whatever', 'migrations'), False)
  3160. def test_references_field_by_through(self):
  3161. operation = FieldOperation('Model', 'field', models.ManyToManyField('Other', through='Through'))
  3162. self.assertIs(operation.references_field('Other', 'whatever', 'migrations'), True)
  3163. self.assertIs(operation.references_field('Through', 'whatever', 'migrations'), True)
  3164. self.assertIs(operation.references_field('Missing', 'whatever', 'migrations'), False)
  3165. def test_reference_field_by_through_fields(self):
  3166. operation = FieldOperation(
  3167. 'Model', 'field', models.ManyToManyField('Other', through='Through', through_fields=('first', 'second'))
  3168. )
  3169. self.assertIs(operation.references_field('Other', 'whatever', 'migrations'), True)
  3170. self.assertIs(operation.references_field('Through', 'whatever', 'migrations'), False)
  3171. self.assertIs(operation.references_field('Through', 'first', 'migrations'), True)
  3172. self.assertIs(operation.references_field('Through', 'second', 'migrations'), True)