test_operations.py 148 KB

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