test_operations.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. from __future__ import unicode_literals
  2. import unittest
  3. try:
  4. import sqlparse
  5. except ImportError:
  6. sqlparse = None
  7. from django import test
  8. from django.db import connection, migrations, models, router
  9. from django.db.migrations.migration import Migration
  10. from django.db.migrations.state import ProjectState
  11. from django.db.models.fields import NOT_PROVIDED
  12. from django.db.transaction import atomic
  13. from django.db.utils import IntegrityError, DatabaseError
  14. from .test_base import MigrationTestBase
  15. class OperationTests(MigrationTestBase):
  16. """
  17. Tests running the operations and making sure they do what they say they do.
  18. Each test looks at their state changing, and then their database operation -
  19. both forwards and backwards.
  20. """
  21. def apply_operations(self, app_label, project_state, operations):
  22. migration = Migration('name', app_label)
  23. migration.operations = operations
  24. with connection.schema_editor() as editor:
  25. return migration.apply(project_state, editor)
  26. def unapply_operations(self, app_label, project_state, operations):
  27. migration = Migration('name', app_label)
  28. migration.operations = operations
  29. with connection.schema_editor() as editor:
  30. return migration.unapply(project_state, editor)
  31. def set_up_test_model(self, app_label, second_model=False, third_model=False, related_model=False, mti_model=False):
  32. """
  33. Creates a test model state and database table.
  34. """
  35. # Delete the tables if they already exist
  36. with connection.cursor() as cursor:
  37. # Start with ManyToMany tables
  38. try:
  39. cursor.execute("DROP TABLE %s_pony_stables" % app_label)
  40. except DatabaseError:
  41. pass
  42. try:
  43. cursor.execute("DROP TABLE %s_pony_vans" % app_label)
  44. except DatabaseError:
  45. pass
  46. # Then standard model tables
  47. try:
  48. cursor.execute("DROP TABLE %s_pony" % app_label)
  49. except DatabaseError:
  50. pass
  51. try:
  52. cursor.execute("DROP TABLE %s_stable" % app_label)
  53. except DatabaseError:
  54. pass
  55. try:
  56. cursor.execute("DROP TABLE %s_van" % app_label)
  57. except DatabaseError:
  58. pass
  59. # Make the "current" state
  60. operations = [migrations.CreateModel(
  61. "Pony",
  62. [
  63. ("id", models.AutoField(primary_key=True)),
  64. ("pink", models.IntegerField(default=3)),
  65. ("weight", models.FloatField()),
  66. ],
  67. )]
  68. if second_model:
  69. operations.append(migrations.CreateModel(
  70. "Stable",
  71. [
  72. ("id", models.AutoField(primary_key=True)),
  73. ]
  74. ))
  75. if third_model:
  76. operations.append(migrations.CreateModel(
  77. "Van",
  78. [
  79. ("id", models.AutoField(primary_key=True)),
  80. ]
  81. ))
  82. if related_model:
  83. operations.append(migrations.CreateModel(
  84. "Rider",
  85. [
  86. ("id", models.AutoField(primary_key=True)),
  87. ("pony", models.ForeignKey("Pony")),
  88. ],
  89. ))
  90. if mti_model:
  91. operations.append(migrations.CreateModel(
  92. "ShetlandPony",
  93. fields=[
  94. ('pony_ptr', models.OneToOneField(
  95. auto_created=True,
  96. primary_key=True,
  97. to_field='id',
  98. serialize=False,
  99. to='Pony',
  100. )),
  101. ("cuteness", models.IntegerField(default=1)),
  102. ],
  103. bases=['%s.Pony' % app_label],
  104. ))
  105. return self.apply_operations(app_label, ProjectState(), operations)
  106. def test_create_model(self):
  107. """
  108. Tests the CreateModel operation.
  109. Most other tests use this operation as part of setup, so check failures here first.
  110. """
  111. operation = migrations.CreateModel(
  112. "Pony",
  113. [
  114. ("id", models.AutoField(primary_key=True)),
  115. ("pink", models.IntegerField(default=1)),
  116. ],
  117. )
  118. # Test the state alteration
  119. project_state = ProjectState()
  120. new_state = project_state.clone()
  121. operation.state_forwards("test_crmo", new_state)
  122. self.assertEqual(new_state.models["test_crmo", "pony"].name, "Pony")
  123. self.assertEqual(len(new_state.models["test_crmo", "pony"].fields), 2)
  124. # Test the database alteration
  125. self.assertTableNotExists("test_crmo_pony")
  126. with connection.schema_editor() as editor:
  127. operation.database_forwards("test_crmo", editor, project_state, new_state)
  128. self.assertTableExists("test_crmo_pony")
  129. # And test reversal
  130. with connection.schema_editor() as editor:
  131. operation.database_backwards("test_crmo", editor, new_state, project_state)
  132. self.assertTableNotExists("test_crmo_pony")
  133. # And deconstruction
  134. definition = operation.deconstruct()
  135. self.assertEqual(definition[0], "CreateModel")
  136. self.assertEqual(len(definition[1]), 2)
  137. self.assertEqual(len(definition[2]), 0)
  138. self.assertEqual(definition[1][0], "Pony")
  139. def test_create_model_m2m(self):
  140. """
  141. Test the creation of a model with a ManyToMany field and the
  142. auto-created "through" model.
  143. """
  144. project_state = self.set_up_test_model("test_crmomm")
  145. operation = migrations.CreateModel(
  146. "Stable",
  147. [
  148. ("id", models.AutoField(primary_key=True)),
  149. ("ponies", models.ManyToManyField("Pony", related_name="stables"))
  150. ]
  151. )
  152. # Test the state alteration
  153. new_state = project_state.clone()
  154. operation.state_forwards("test_crmomm", new_state)
  155. # Test the database alteration
  156. self.assertTableNotExists("test_crmomm_stable_ponies")
  157. with connection.schema_editor() as editor:
  158. operation.database_forwards("test_crmomm", editor, project_state, new_state)
  159. self.assertTableExists("test_crmomm_stable")
  160. self.assertTableExists("test_crmomm_stable_ponies")
  161. self.assertColumnNotExists("test_crmomm_stable", "ponies")
  162. # Make sure the M2M field actually works
  163. with atomic():
  164. new_apps = new_state.render()
  165. Pony = new_apps.get_model("test_crmomm", "Pony")
  166. Stable = new_apps.get_model("test_crmomm", "Stable")
  167. stable = Stable.objects.create()
  168. p1 = Pony.objects.create(pink=False, weight=4.55)
  169. p2 = Pony.objects.create(pink=True, weight=5.43)
  170. stable.ponies.add(p1, p2)
  171. self.assertEqual(stable.ponies.count(), 2)
  172. stable.ponies.all().delete()
  173. # And test reversal
  174. with connection.schema_editor() as editor:
  175. operation.database_backwards("test_crmomm", editor, new_state, project_state)
  176. self.assertTableNotExists("test_crmomm_stable")
  177. self.assertTableNotExists("test_crmomm_stable_ponies")
  178. def test_create_model_inheritance(self):
  179. """
  180. Tests the CreateModel operation on a multi-table inheritance setup.
  181. """
  182. project_state = self.set_up_test_model("test_crmoih")
  183. # Test the state alteration
  184. operation = migrations.CreateModel(
  185. "ShetlandPony",
  186. [
  187. ('pony_ptr', models.OneToOneField(
  188. auto_created=True,
  189. primary_key=True,
  190. to_field='id',
  191. serialize=False,
  192. to='test_crmoih.Pony',
  193. )),
  194. ("cuteness", models.IntegerField(default=1)),
  195. ],
  196. )
  197. new_state = project_state.clone()
  198. operation.state_forwards("test_crmoih", new_state)
  199. self.assertIn(("test_crmoih", "shetlandpony"), new_state.models)
  200. # Test the database alteration
  201. self.assertTableNotExists("test_crmoih_shetlandpony")
  202. with connection.schema_editor() as editor:
  203. operation.database_forwards("test_crmoih", editor, project_state, new_state)
  204. self.assertTableExists("test_crmoih_shetlandpony")
  205. # And test reversal
  206. with connection.schema_editor() as editor:
  207. operation.database_backwards("test_crmoih", editor, new_state, project_state)
  208. self.assertTableNotExists("test_crmoih_shetlandpony")
  209. def test_delete_model(self):
  210. """
  211. Tests the DeleteModel operation.
  212. """
  213. project_state = self.set_up_test_model("test_dlmo")
  214. # Test the state alteration
  215. operation = migrations.DeleteModel("Pony")
  216. new_state = project_state.clone()
  217. operation.state_forwards("test_dlmo", new_state)
  218. self.assertNotIn(("test_dlmo", "pony"), new_state.models)
  219. # Test the database alteration
  220. self.assertTableExists("test_dlmo_pony")
  221. with connection.schema_editor() as editor:
  222. operation.database_forwards("test_dlmo", editor, project_state, new_state)
  223. self.assertTableNotExists("test_dlmo_pony")
  224. # And test reversal
  225. with connection.schema_editor() as editor:
  226. operation.database_backwards("test_dlmo", editor, new_state, project_state)
  227. self.assertTableExists("test_dlmo_pony")
  228. def test_rename_model(self):
  229. """
  230. Tests the RenameModel operation.
  231. """
  232. project_state = self.set_up_test_model("test_rnmo", related_model=True)
  233. # Test the state alteration
  234. operation = migrations.RenameModel("Pony", "Horse")
  235. new_state = project_state.clone()
  236. operation.state_forwards("test_rnmo", new_state)
  237. self.assertNotIn(("test_rnmo", "pony"), new_state.models)
  238. self.assertIn(("test_rnmo", "horse"), new_state.models)
  239. # Remember, RenameModel also repoints all incoming FKs and M2Ms
  240. self.assertEqual("test_rnmo.Horse", new_state.models["test_rnmo", "rider"].fields[1][1].rel.to)
  241. # Test the database alteration
  242. self.assertTableExists("test_rnmo_pony")
  243. self.assertTableNotExists("test_rnmo_horse")
  244. if connection.features.supports_foreign_keys:
  245. self.assertFKExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id"))
  246. self.assertFKNotExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id"))
  247. with connection.schema_editor() as editor:
  248. operation.database_forwards("test_rnmo", editor, project_state, new_state)
  249. self.assertTableNotExists("test_rnmo_pony")
  250. self.assertTableExists("test_rnmo_horse")
  251. if connection.features.supports_foreign_keys:
  252. self.assertFKNotExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id"))
  253. self.assertFKExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id"))
  254. # And test reversal
  255. with connection.schema_editor() as editor:
  256. operation.database_backwards("test_rnmo", editor, new_state, project_state)
  257. self.assertTableExists("test_rnmo_pony")
  258. self.assertTableNotExists("test_rnmo_horse")
  259. if connection.features.supports_foreign_keys:
  260. self.assertFKExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id"))
  261. self.assertFKNotExists("test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id"))
  262. def test_add_field(self):
  263. """
  264. Tests the AddField operation.
  265. """
  266. project_state = self.set_up_test_model("test_adfl")
  267. # Test the state alteration
  268. operation = migrations.AddField(
  269. "Pony",
  270. "height",
  271. models.FloatField(null=True, default=5),
  272. )
  273. new_state = project_state.clone()
  274. operation.state_forwards("test_adfl", new_state)
  275. self.assertEqual(len(new_state.models["test_adfl", "pony"].fields), 4)
  276. field = [
  277. f for n, f in new_state.models["test_adfl", "pony"].fields
  278. if n == "height"
  279. ][0]
  280. self.assertEqual(field.default, 5)
  281. # Test the database alteration
  282. self.assertColumnNotExists("test_adfl_pony", "height")
  283. with connection.schema_editor() as editor:
  284. operation.database_forwards("test_adfl", editor, project_state, new_state)
  285. self.assertColumnExists("test_adfl_pony", "height")
  286. # And test reversal
  287. with connection.schema_editor() as editor:
  288. operation.database_backwards("test_adfl", editor, new_state, project_state)
  289. self.assertColumnNotExists("test_adfl_pony", "height")
  290. def test_add_charfield(self):
  291. """
  292. Tests the AddField operation on TextField.
  293. """
  294. project_state = self.set_up_test_model("test_adchfl")
  295. new_apps = project_state.render()
  296. Pony = new_apps.get_model("test_adchfl", "Pony")
  297. pony = Pony.objects.create(weight=42)
  298. new_state = self.apply_operations("test_adchfl", project_state, [
  299. migrations.AddField(
  300. "Pony",
  301. "text",
  302. models.CharField(max_length=10, default="some text"),
  303. ),
  304. migrations.AddField(
  305. "Pony",
  306. "empty",
  307. models.CharField(max_length=10, default=""),
  308. ),
  309. # If not properly quoted digits would be interpreted as an int.
  310. migrations.AddField(
  311. "Pony",
  312. "digits",
  313. models.CharField(max_length=10, default="42"),
  314. ),
  315. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  316. migrations.AddField(
  317. "Pony",
  318. "quotes",
  319. models.CharField(max_length=10, default='"\'"'),
  320. ),
  321. ])
  322. new_apps = new_state.render()
  323. Pony = new_apps.get_model("test_adchfl", "Pony")
  324. pony = Pony.objects.get(pk=pony.pk)
  325. self.assertEqual(pony.text, "some text")
  326. self.assertEqual(pony.empty, "")
  327. self.assertEqual(pony.digits, "42")
  328. self.assertEqual(pony.quotes, '"\'"')
  329. def test_add_textfield(self):
  330. """
  331. Tests the AddField operation on TextField.
  332. """
  333. project_state = self.set_up_test_model("test_adtxtfl")
  334. new_apps = project_state.render()
  335. Pony = new_apps.get_model("test_adtxtfl", "Pony")
  336. pony = Pony.objects.create(weight=42)
  337. new_state = self.apply_operations("test_adtxtfl", project_state, [
  338. migrations.AddField(
  339. "Pony",
  340. "text",
  341. models.TextField(default="some text"),
  342. ),
  343. migrations.AddField(
  344. "Pony",
  345. "empty",
  346. models.TextField(default=""),
  347. ),
  348. # If not properly quoted digits would be interpreted as an int.
  349. migrations.AddField(
  350. "Pony",
  351. "digits",
  352. models.TextField(default="42"),
  353. ),
  354. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  355. migrations.AddField(
  356. "Pony",
  357. "quotes",
  358. models.TextField(default='"\'"'),
  359. ),
  360. ])
  361. new_apps = new_state.render()
  362. Pony = new_apps.get_model("test_adtxtfl", "Pony")
  363. pony = Pony.objects.get(pk=pony.pk)
  364. self.assertEqual(pony.text, "some text")
  365. self.assertEqual(pony.empty, "")
  366. self.assertEqual(pony.digits, "42")
  367. self.assertEqual(pony.quotes, '"\'"')
  368. @test.skipUnlessDBFeature('supports_binary_field')
  369. def test_add_binaryfield(self):
  370. """
  371. Tests the AddField operation on TextField/BinaryField.
  372. """
  373. project_state = self.set_up_test_model("test_adbinfl")
  374. new_apps = project_state.render()
  375. Pony = new_apps.get_model("test_adbinfl", "Pony")
  376. pony = Pony.objects.create(weight=42)
  377. new_state = self.apply_operations("test_adbinfl", project_state, [
  378. migrations.AddField(
  379. "Pony",
  380. "blob",
  381. models.BinaryField(default=b"some text"),
  382. ),
  383. migrations.AddField(
  384. "Pony",
  385. "empty",
  386. models.BinaryField(default=b""),
  387. ),
  388. # If not properly quoted digits would be interpreted as an int.
  389. migrations.AddField(
  390. "Pony",
  391. "digits",
  392. models.BinaryField(default=b"42"),
  393. ),
  394. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  395. migrations.AddField(
  396. "Pony",
  397. "quotes",
  398. models.BinaryField(default=b'"\'"'),
  399. ),
  400. ])
  401. new_apps = new_state.render()
  402. Pony = new_apps.get_model("test_adbinfl", "Pony")
  403. pony = Pony.objects.get(pk=pony.pk)
  404. # SQLite returns buffer/memoryview, cast to bytes for checking.
  405. self.assertEqual(bytes(pony.blob), b"some text")
  406. self.assertEqual(bytes(pony.empty), b"")
  407. self.assertEqual(bytes(pony.digits), b"42")
  408. self.assertEqual(bytes(pony.quotes), b'"\'"')
  409. def test_column_name_quoting(self):
  410. """
  411. Column names that are SQL keywords shouldn't cause problems when used
  412. in migrations (#22168).
  413. """
  414. project_state = self.set_up_test_model("test_regr22168")
  415. operation = migrations.AddField(
  416. "Pony",
  417. "order",
  418. models.IntegerField(default=0),
  419. )
  420. new_state = project_state.clone()
  421. operation.state_forwards("test_regr22168", new_state)
  422. with connection.schema_editor() as editor:
  423. operation.database_forwards("test_regr22168", editor, project_state, new_state)
  424. self.assertColumnExists("test_regr22168_pony", "order")
  425. def test_add_field_preserve_default(self):
  426. """
  427. Tests the AddField operation's state alteration
  428. when preserve_default = False.
  429. """
  430. project_state = self.set_up_test_model("test_adflpd")
  431. # Test the state alteration
  432. operation = migrations.AddField(
  433. "Pony",
  434. "height",
  435. models.FloatField(null=True, default=4),
  436. preserve_default=False,
  437. )
  438. new_state = project_state.clone()
  439. operation.state_forwards("test_adflpd", new_state)
  440. self.assertEqual(len(new_state.models["test_adflpd", "pony"].fields), 4)
  441. field = [
  442. f for n, f in new_state.models["test_adflpd", "pony"].fields
  443. if n == "height"
  444. ][0]
  445. self.assertEqual(field.default, NOT_PROVIDED)
  446. # Test the database alteration
  447. project_state.render().get_model("test_adflpd", "pony").objects.create(
  448. weight=4,
  449. )
  450. self.assertColumnNotExists("test_adflpd_pony", "height")
  451. with connection.schema_editor() as editor:
  452. operation.database_forwards("test_adflpd", editor, project_state, new_state)
  453. self.assertColumnExists("test_adflpd_pony", "height")
  454. def test_add_field_m2m(self):
  455. """
  456. Tests the AddField operation with a ManyToManyField.
  457. """
  458. project_state = self.set_up_test_model("test_adflmm", second_model=True)
  459. # Test the state alteration
  460. operation = migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
  461. new_state = project_state.clone()
  462. operation.state_forwards("test_adflmm", new_state)
  463. self.assertEqual(len(new_state.models["test_adflmm", "pony"].fields), 4)
  464. # Test the database alteration
  465. self.assertTableNotExists("test_adflmm_pony_stables")
  466. with connection.schema_editor() as editor:
  467. operation.database_forwards("test_adflmm", editor, project_state, new_state)
  468. self.assertTableExists("test_adflmm_pony_stables")
  469. self.assertColumnNotExists("test_adflmm_pony", "stables")
  470. # Make sure the M2M field actually works
  471. with atomic():
  472. new_apps = new_state.render()
  473. Pony = new_apps.get_model("test_adflmm", "Pony")
  474. p = Pony.objects.create(pink=False, weight=4.55)
  475. p.stables.create()
  476. self.assertEqual(p.stables.count(), 1)
  477. p.stables.all().delete()
  478. # And test reversal
  479. with connection.schema_editor() as editor:
  480. operation.database_backwards("test_adflmm", editor, new_state, project_state)
  481. self.assertTableNotExists("test_adflmm_pony_stables")
  482. def test_alter_field_m2m(self):
  483. project_state = self.set_up_test_model("test_alflmm", second_model=True)
  484. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  485. migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
  486. ])
  487. new_apps = project_state.render()
  488. Pony = new_apps.get_model("test_alflmm", "Pony")
  489. self.assertFalse(Pony._meta.get_field('stables').blank)
  490. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  491. migrations.AlterField("Pony", "stables", models.ManyToManyField(to="Stable", related_name="ponies", blank=True))
  492. ])
  493. new_apps = project_state.render()
  494. Pony = new_apps.get_model("test_alflmm", "Pony")
  495. self.assertTrue(Pony._meta.get_field('stables').blank)
  496. def test_repoint_field_m2m(self):
  497. project_state = self.set_up_test_model("test_alflmm", second_model=True, third_model=True)
  498. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  499. migrations.AddField("Pony", "places", models.ManyToManyField("Stable", related_name="ponies"))
  500. ])
  501. new_apps = project_state.render()
  502. Pony = new_apps.get_model("test_alflmm", "Pony")
  503. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  504. migrations.AlterField("Pony", "places", models.ManyToManyField(to="Van", related_name="ponies"))
  505. ])
  506. # Ensure the new field actually works
  507. new_apps = project_state.render()
  508. Pony = new_apps.get_model("test_alflmm", "Pony")
  509. p = Pony.objects.create(pink=False, weight=4.55)
  510. p.places.create()
  511. self.assertEqual(p.places.count(), 1)
  512. p.places.all().delete()
  513. def test_remove_field_m2m(self):
  514. project_state = self.set_up_test_model("test_rmflmm", second_model=True)
  515. project_state = self.apply_operations("test_rmflmm", project_state, operations=[
  516. migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
  517. ])
  518. self.assertTableExists("test_rmflmm_pony_stables")
  519. operations = [migrations.RemoveField("Pony", "stables")]
  520. self.apply_operations("test_rmflmm", project_state, operations=operations)
  521. self.assertTableNotExists("test_rmflmm_pony_stables")
  522. # And test reversal
  523. self.unapply_operations("test_rmflmm", project_state, operations=operations)
  524. self.assertTableExists("test_rmflmm_pony_stables")
  525. def test_remove_field_m2m_with_through(self):
  526. project_state = self.set_up_test_model("test_rmflmmwt", second_model=True)
  527. self.assertTableNotExists("test_rmflmmwt_ponystables")
  528. project_state = self.apply_operations("test_rmflmmwt", project_state, operations=[
  529. migrations.CreateModel("PonyStables", fields=[
  530. ("pony", models.ForeignKey('test_rmflmmwt.Pony')),
  531. ("stable", models.ForeignKey('test_rmflmmwt.Stable')),
  532. ]),
  533. migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies", through='test_rmflmmwt.PonyStables'))
  534. ])
  535. self.assertTableExists("test_rmflmmwt_ponystables")
  536. operations = [migrations.RemoveField("Pony", "stables")]
  537. self.apply_operations("test_rmflmmwt", project_state, operations=operations)
  538. def test_remove_field(self):
  539. """
  540. Tests the RemoveField operation.
  541. """
  542. project_state = self.set_up_test_model("test_rmfl")
  543. # Test the state alteration
  544. operation = migrations.RemoveField("Pony", "pink")
  545. new_state = project_state.clone()
  546. operation.state_forwards("test_rmfl", new_state)
  547. self.assertEqual(len(new_state.models["test_rmfl", "pony"].fields), 2)
  548. # Test the database alteration
  549. self.assertColumnExists("test_rmfl_pony", "pink")
  550. with connection.schema_editor() as editor:
  551. operation.database_forwards("test_rmfl", editor, project_state, new_state)
  552. self.assertColumnNotExists("test_rmfl_pony", "pink")
  553. # And test reversal
  554. with connection.schema_editor() as editor:
  555. operation.database_backwards("test_rmfl", editor, new_state, project_state)
  556. self.assertColumnExists("test_rmfl_pony", "pink")
  557. def test_remove_fk(self):
  558. """
  559. Tests the RemoveField operation on a foreign key.
  560. """
  561. project_state = self.set_up_test_model("test_rfk", related_model=True)
  562. self.assertColumnExists("test_rfk_rider", "pony_id")
  563. operation = migrations.RemoveField("Rider", "pony")
  564. new_state = project_state.clone()
  565. operation.state_forwards("test_rfk", new_state)
  566. with connection.schema_editor() as editor:
  567. operation.database_forwards("test_rfk", editor, project_state, new_state)
  568. self.assertColumnNotExists("test_rfk_rider", "pony_id")
  569. with connection.schema_editor() as editor:
  570. operation.database_backwards("test_rfk", editor, new_state, project_state)
  571. self.assertColumnExists("test_rfk_rider", "pony_id")
  572. def test_alter_model_table(self):
  573. """
  574. Tests the AlterModelTable operation.
  575. """
  576. project_state = self.set_up_test_model("test_almota")
  577. # Test the state alteration
  578. operation = migrations.AlterModelTable("Pony", "test_almota_pony_2")
  579. new_state = project_state.clone()
  580. operation.state_forwards("test_almota", new_state)
  581. self.assertEqual(new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony_2")
  582. # Test the database alteration
  583. self.assertTableExists("test_almota_pony")
  584. self.assertTableNotExists("test_almota_pony_2")
  585. with connection.schema_editor() as editor:
  586. operation.database_forwards("test_almota", editor, project_state, new_state)
  587. self.assertTableNotExists("test_almota_pony")
  588. self.assertTableExists("test_almota_pony_2")
  589. # And test reversal
  590. with connection.schema_editor() as editor:
  591. operation.database_backwards("test_almota", editor, new_state, project_state)
  592. self.assertTableExists("test_almota_pony")
  593. self.assertTableNotExists("test_almota_pony_2")
  594. def test_alter_field(self):
  595. """
  596. Tests the AlterField operation.
  597. """
  598. project_state = self.set_up_test_model("test_alfl")
  599. # Test the state alteration
  600. operation = migrations.AlterField("Pony", "pink", models.IntegerField(null=True))
  601. new_state = project_state.clone()
  602. operation.state_forwards("test_alfl", new_state)
  603. self.assertEqual(project_state.models["test_alfl", "pony"].get_field_by_name("pink").null, False)
  604. self.assertEqual(new_state.models["test_alfl", "pony"].get_field_by_name("pink").null, True)
  605. # Test the database alteration
  606. self.assertColumnNotNull("test_alfl_pony", "pink")
  607. with connection.schema_editor() as editor:
  608. operation.database_forwards("test_alfl", editor, project_state, new_state)
  609. self.assertColumnNull("test_alfl_pony", "pink")
  610. # And test reversal
  611. with connection.schema_editor() as editor:
  612. operation.database_backwards("test_alfl", editor, new_state, project_state)
  613. self.assertColumnNotNull("test_alfl_pony", "pink")
  614. def test_alter_field_pk(self):
  615. """
  616. Tests the AlterField operation on primary keys (for things like PostgreSQL's SERIAL weirdness)
  617. """
  618. project_state = self.set_up_test_model("test_alflpk")
  619. # Test the state alteration
  620. operation = migrations.AlterField("Pony", "id", models.IntegerField(primary_key=True))
  621. new_state = project_state.clone()
  622. operation.state_forwards("test_alflpk", new_state)
  623. self.assertIsInstance(project_state.models["test_alflpk", "pony"].get_field_by_name("id"), models.AutoField)
  624. self.assertIsInstance(new_state.models["test_alflpk", "pony"].get_field_by_name("id"), models.IntegerField)
  625. # Test the database alteration
  626. with connection.schema_editor() as editor:
  627. operation.database_forwards("test_alflpk", editor, project_state, new_state)
  628. # And test reversal
  629. with connection.schema_editor() as editor:
  630. operation.database_backwards("test_alflpk", editor, new_state, project_state)
  631. @unittest.skipUnless(connection.features.supports_foreign_keys, "No FK support")
  632. def test_alter_field_pk_fk(self):
  633. """
  634. Tests the AlterField operation on primary keys changes any FKs pointing to it.
  635. """
  636. project_state = self.set_up_test_model("test_alflpkfk", related_model=True)
  637. # Test the state alteration
  638. operation = migrations.AlterField("Pony", "id", models.FloatField(primary_key=True))
  639. new_state = project_state.clone()
  640. operation.state_forwards("test_alflpkfk", new_state)
  641. self.assertIsInstance(project_state.models["test_alflpkfk", "pony"].get_field_by_name("id"), models.AutoField)
  642. self.assertIsInstance(new_state.models["test_alflpkfk", "pony"].get_field_by_name("id"), models.FloatField)
  643. def assertIdTypeEqualsFkType():
  644. with connection.cursor() as cursor:
  645. id_type = [c.type_code for c in connection.introspection.get_table_description(cursor, "test_alflpkfk_pony") if c.name == "id"][0]
  646. fk_type = [c.type_code for c in connection.introspection.get_table_description(cursor, "test_alflpkfk_rider") if c.name == "pony_id"][0]
  647. self.assertEqual(id_type, fk_type)
  648. assertIdTypeEqualsFkType()
  649. # Test the database alteration
  650. with connection.schema_editor() as editor:
  651. operation.database_forwards("test_alflpkfk", editor, project_state, new_state)
  652. assertIdTypeEqualsFkType()
  653. # And test reversal
  654. with connection.schema_editor() as editor:
  655. operation.database_backwards("test_alflpkfk", editor, new_state, project_state)
  656. assertIdTypeEqualsFkType()
  657. def test_rename_field(self):
  658. """
  659. Tests the RenameField operation.
  660. """
  661. project_state = self.set_up_test_model("test_rnfl")
  662. # Test the state alteration
  663. operation = migrations.RenameField("Pony", "pink", "blue")
  664. new_state = project_state.clone()
  665. operation.state_forwards("test_rnfl", new_state)
  666. self.assertIn("blue", [n for n, f in new_state.models["test_rnfl", "pony"].fields])
  667. self.assertNotIn("pink", [n for n, f in new_state.models["test_rnfl", "pony"].fields])
  668. # Test the database alteration
  669. self.assertColumnExists("test_rnfl_pony", "pink")
  670. self.assertColumnNotExists("test_rnfl_pony", "blue")
  671. with connection.schema_editor() as editor:
  672. operation.database_forwards("test_rnfl", editor, project_state, new_state)
  673. self.assertColumnExists("test_rnfl_pony", "blue")
  674. self.assertColumnNotExists("test_rnfl_pony", "pink")
  675. # And test reversal
  676. with connection.schema_editor() as editor:
  677. operation.database_backwards("test_rnfl", editor, new_state, project_state)
  678. self.assertColumnExists("test_rnfl_pony", "pink")
  679. self.assertColumnNotExists("test_rnfl_pony", "blue")
  680. def test_alter_unique_together(self):
  681. """
  682. Tests the AlterUniqueTogether operation.
  683. """
  684. project_state = self.set_up_test_model("test_alunto")
  685. # Test the state alteration
  686. operation = migrations.AlterUniqueTogether("Pony", [("pink", "weight")])
  687. new_state = project_state.clone()
  688. operation.state_forwards("test_alunto", new_state)
  689. self.assertEqual(len(project_state.models["test_alunto", "pony"].options.get("unique_together", set())), 0)
  690. self.assertEqual(len(new_state.models["test_alunto", "pony"].options.get("unique_together", set())), 1)
  691. # Make sure we can insert duplicate rows
  692. with connection.cursor() as cursor:
  693. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  694. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  695. cursor.execute("DELETE FROM test_alunto_pony")
  696. # Test the database alteration
  697. with connection.schema_editor() as editor:
  698. operation.database_forwards("test_alunto", editor, project_state, new_state)
  699. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  700. with self.assertRaises(IntegrityError):
  701. with atomic():
  702. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  703. cursor.execute("DELETE FROM test_alunto_pony")
  704. # And test reversal
  705. with connection.schema_editor() as editor:
  706. operation.database_backwards("test_alunto", editor, new_state, project_state)
  707. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  708. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  709. cursor.execute("DELETE FROM test_alunto_pony")
  710. # Test flat unique_together
  711. operation = migrations.AlterUniqueTogether("Pony", ("pink", "weight"))
  712. operation.state_forwards("test_alunto", new_state)
  713. self.assertEqual(len(new_state.models["test_alunto", "pony"].options.get("unique_together", set())), 1)
  714. def test_alter_index_together(self):
  715. """
  716. Tests the AlterIndexTogether operation.
  717. """
  718. project_state = self.set_up_test_model("test_alinto")
  719. # Test the state alteration
  720. operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")])
  721. new_state = project_state.clone()
  722. operation.state_forwards("test_alinto", new_state)
  723. self.assertEqual(len(project_state.models["test_alinto", "pony"].options.get("index_together", set())), 0)
  724. self.assertEqual(len(new_state.models["test_alinto", "pony"].options.get("index_together", set())), 1)
  725. # Make sure there's no matching index
  726. self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"])
  727. # Test the database alteration
  728. with connection.schema_editor() as editor:
  729. operation.database_forwards("test_alinto", editor, project_state, new_state)
  730. self.assertIndexExists("test_alinto_pony", ["pink", "weight"])
  731. # And test reversal
  732. with connection.schema_editor() as editor:
  733. operation.database_backwards("test_alinto", editor, new_state, project_state)
  734. self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"])
  735. @unittest.skipIf(sqlparse is None and connection.features.requires_sqlparse_for_splitting, "Missing sqlparse")
  736. def test_run_sql(self):
  737. """
  738. Tests the RunSQL operation.
  739. """
  740. project_state = self.set_up_test_model("test_runsql")
  741. # Create the operation
  742. operation = migrations.RunSQL(
  743. # Use a multi-line string with a commment to test splitting on SQLite and MySQL respectively
  744. "CREATE TABLE i_love_ponies (id int, special_thing int);\n"
  745. "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 42); -- this is magic!\n"
  746. "INSERT INTO i_love_ponies (id, special_thing) VALUES (2, 51);\n",
  747. "DROP TABLE i_love_ponies",
  748. state_operations=[migrations.CreateModel("SomethingElse", [("id", models.AutoField(primary_key=True))])],
  749. )
  750. # Test the state alteration
  751. new_state = project_state.clone()
  752. operation.state_forwards("test_runsql", new_state)
  753. self.assertEqual(len(new_state.models["test_runsql", "somethingelse"].fields), 1)
  754. # Make sure there's no table
  755. self.assertTableNotExists("i_love_ponies")
  756. # Test the database alteration
  757. with connection.schema_editor() as editor:
  758. operation.database_forwards("test_runsql", editor, project_state, new_state)
  759. self.assertTableExists("i_love_ponies")
  760. # Make sure all the SQL was processed
  761. with connection.cursor() as cursor:
  762. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  763. self.assertEqual(cursor.fetchall()[0][0], 2)
  764. # And test reversal
  765. self.assertTrue(operation.reversible)
  766. with connection.schema_editor() as editor:
  767. operation.database_backwards("test_runsql", editor, new_state, project_state)
  768. self.assertTableNotExists("i_love_ponies")
  769. def test_run_python(self):
  770. """
  771. Tests the RunPython operation
  772. """
  773. project_state = self.set_up_test_model("test_runpython", mti_model=True)
  774. # Create the operation
  775. def inner_method(models, schema_editor):
  776. Pony = models.get_model("test_runpython", "Pony")
  777. Pony.objects.create(pink=1, weight=3.55)
  778. Pony.objects.create(weight=5)
  779. def inner_method_reverse(models, schema_editor):
  780. Pony = models.get_model("test_runpython", "Pony")
  781. Pony.objects.filter(pink=1, weight=3.55).delete()
  782. Pony.objects.filter(weight=5).delete()
  783. operation = migrations.RunPython(inner_method, reverse_code=inner_method_reverse)
  784. # Test the state alteration does nothing
  785. new_state = project_state.clone()
  786. operation.state_forwards("test_runpython", new_state)
  787. self.assertEqual(new_state, project_state)
  788. # Test the database alteration
  789. self.assertEqual(project_state.render().get_model("test_runpython", "Pony").objects.count(), 0)
  790. with connection.schema_editor() as editor:
  791. operation.database_forwards("test_runpython", editor, project_state, new_state)
  792. self.assertEqual(project_state.render().get_model("test_runpython", "Pony").objects.count(), 2)
  793. # Now test reversal
  794. self.assertTrue(operation.reversible)
  795. with connection.schema_editor() as editor:
  796. operation.database_backwards("test_runpython", editor, project_state, new_state)
  797. self.assertEqual(project_state.render().get_model("test_runpython", "Pony").objects.count(), 0)
  798. # Now test we can't use a string
  799. with self.assertRaises(ValueError):
  800. operation = migrations.RunPython("print 'ahahaha'")
  801. # Also test reversal fails, with an operation identical to above but without reverse_code set
  802. no_reverse_operation = migrations.RunPython(inner_method)
  803. self.assertFalse(no_reverse_operation.reversible)
  804. with connection.schema_editor() as editor:
  805. no_reverse_operation.database_forwards("test_runpython", editor, project_state, new_state)
  806. with self.assertRaises(NotImplementedError):
  807. no_reverse_operation.database_backwards("test_runpython", editor, new_state, project_state)
  808. self.assertEqual(project_state.render().get_model("test_runpython", "Pony").objects.count(), 2)
  809. def create_ponies(models, schema_editor):
  810. Pony = models.get_model("test_runpython", "Pony")
  811. pony1 = Pony.objects.create(pink=1, weight=3.55)
  812. self.assertIsNot(pony1.pk, None)
  813. pony2 = Pony.objects.create(weight=5)
  814. self.assertIsNot(pony2.pk, None)
  815. self.assertNotEqual(pony1.pk, pony2.pk)
  816. operation = migrations.RunPython(create_ponies)
  817. with connection.schema_editor() as editor:
  818. operation.database_forwards("test_runpython", editor, project_state, new_state)
  819. self.assertEqual(project_state.render().get_model("test_runpython", "Pony").objects.count(), 4)
  820. def create_shetlandponies(models, schema_editor):
  821. ShetlandPony = models.get_model("test_runpython", "ShetlandPony")
  822. pony1 = ShetlandPony.objects.create(weight=4.0)
  823. self.assertIsNot(pony1.pk, None)
  824. pony2 = ShetlandPony.objects.create(weight=5.0)
  825. self.assertIsNot(pony2.pk, None)
  826. self.assertNotEqual(pony1.pk, pony2.pk)
  827. operation = migrations.RunPython(create_shetlandponies)
  828. with connection.schema_editor() as editor:
  829. operation.database_forwards("test_runpython", editor, project_state, new_state)
  830. self.assertEqual(project_state.render().get_model("test_runpython", "Pony").objects.count(), 6)
  831. self.assertEqual(project_state.render().get_model("test_runpython", "ShetlandPony").objects.count(), 2)
  832. def test_run_python_atomic(self):
  833. """
  834. Tests the RunPython operation correctly handles the "atomic" keyword
  835. """
  836. project_state = self.set_up_test_model("test_runpythonatomic", mti_model=True)
  837. def inner_method(models, schema_editor):
  838. Pony = models.get_model("test_runpythonatomic", "Pony")
  839. Pony.objects.create(pink=1, weight=3.55)
  840. raise ValueError("Adrian hates ponies.")
  841. atomic_migration = Migration("test", "test_runpythonatomic")
  842. atomic_migration.operations = [migrations.RunPython(inner_method)]
  843. non_atomic_migration = Migration("test", "test_runpythonatomic")
  844. non_atomic_migration.operations = [migrations.RunPython(inner_method, atomic=False)]
  845. # If we're a fully-transactional database, both versions should rollback
  846. if connection.features.can_rollback_ddl:
  847. self.assertEqual(project_state.render().get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  848. with self.assertRaises(ValueError):
  849. with connection.schema_editor() as editor:
  850. atomic_migration.apply(project_state, editor)
  851. self.assertEqual(project_state.render().get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  852. with self.assertRaises(ValueError):
  853. with connection.schema_editor() as editor:
  854. non_atomic_migration.apply(project_state, editor)
  855. self.assertEqual(project_state.render().get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  856. # Otherwise, the non-atomic operation should leave a row there
  857. else:
  858. self.assertEqual(project_state.render().get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  859. with self.assertRaises(ValueError):
  860. with connection.schema_editor() as editor:
  861. atomic_migration.apply(project_state, editor)
  862. self.assertEqual(project_state.render().get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  863. with self.assertRaises(ValueError):
  864. with connection.schema_editor() as editor:
  865. non_atomic_migration.apply(project_state, editor)
  866. self.assertEqual(project_state.render().get_model("test_runpythonatomic", "Pony").objects.count(), 1)
  867. class MigrateNothingRouter(object):
  868. """
  869. A router that sends all writes to the other database.
  870. """
  871. def allow_migrate(self, db, model):
  872. return False
  873. class MultiDBOperationTests(MigrationTestBase):
  874. multi_db = True
  875. def setUp(self):
  876. # Make the 'other' database appear to be a replica of the 'default'
  877. self.old_routers = router.routers
  878. router.routers = [MigrateNothingRouter()]
  879. def tearDown(self):
  880. # Restore the 'other' database as an independent database
  881. router.routers = self.old_routers
  882. def test_create_model(self):
  883. """
  884. Tests that CreateModel honours multi-db settings.
  885. """
  886. operation = migrations.CreateModel(
  887. "Pony",
  888. [
  889. ("id", models.AutoField(primary_key=True)),
  890. ("pink", models.IntegerField(default=1)),
  891. ],
  892. )
  893. # Test the state alteration
  894. project_state = ProjectState()
  895. new_state = project_state.clone()
  896. operation.state_forwards("test_crmo", new_state)
  897. # Test the database alteration
  898. self.assertTableNotExists("test_crmo_pony")
  899. with connection.schema_editor() as editor:
  900. operation.database_forwards("test_crmo", editor, project_state, new_state)
  901. self.assertTableNotExists("test_crmo_pony")
  902. # And test reversal
  903. with connection.schema_editor() as editor:
  904. operation.database_backwards("test_crmo", editor, new_state, project_state)
  905. self.assertTableNotExists("test_crmo_pony")