test_operations.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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")
  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. # Test the database alteration
  240. self.assertTableExists("test_rnmo_pony")
  241. self.assertTableNotExists("test_rnmo_horse")
  242. with connection.schema_editor() as editor:
  243. operation.database_forwards("test_rnmo", editor, project_state, new_state)
  244. self.assertTableNotExists("test_rnmo_pony")
  245. self.assertTableExists("test_rnmo_horse")
  246. # And test reversal
  247. with connection.schema_editor() as editor:
  248. operation.database_backwards("test_rnmo", editor, new_state, project_state)
  249. self.assertTableExists("test_dlmo_pony")
  250. self.assertTableNotExists("test_rnmo_horse")
  251. # See #22248 - this will fail until that's fixed.
  252. #
  253. # def test_rename_model_with_related(self):
  254. # """
  255. # Tests the real-world combo of a RenameModel operation with AlterField
  256. # for a related field.
  257. # """
  258. # project_state = self.set_up_test_model(
  259. # "test_rnmowr", related_model=True)
  260. # # Test the state alterations
  261. # model_operation = migrations.RenameModel("Pony", "Horse")
  262. # new_state = project_state.clone()
  263. # model_operation.state_forwards("test_rnmowr", new_state)
  264. # self.assertNotIn(("test_rnmowr", "pony"), new_state.models)
  265. # self.assertIn(("test_rnmowr", "horse"), new_state.models)
  266. # self.assertEqual(
  267. # "Pony",
  268. # project_state.render().get_model("test_rnmowr", "rider")
  269. # ._meta.get_field_by_name("pony")[0].rel.to._meta.object_name)
  270. # field_operation = migrations.AlterField(
  271. # "Rider", "pony", models.ForeignKey("Horse"))
  272. # field_operation.state_forwards("test_rnmowr", new_state)
  273. # self.assertEqual(
  274. # "Horse",
  275. # new_state.render().get_model("test_rnmowr", "rider")
  276. # ._meta.get_field_by_name("pony")[0].rel.to._meta.object_name)
  277. # # Test the database alterations
  278. # self.assertTableExists("test_rnmowr_pony")
  279. # self.assertTableNotExists("test_rnmowr_horse")
  280. # with connection.schema_editor() as editor:
  281. # model_operation.database_forwards("test_rnmowr", editor, project_state, new_state)
  282. # field_operation.database_forwards("test_rnmowr", editor, project_state, new_state)
  283. # self.assertTableNotExists("test_rnmowr_pony")
  284. # self.assertTableExists("test_rnmowr_horse")
  285. # # And test reversal
  286. # with connection.schema_editor() as editor:
  287. # field_operation.database_backwards("test_rnmowr", editor, new_state, project_state)
  288. # model_operation.database_backwards("test_rnmowr", editor, new_state, project_state)
  289. # self.assertTableExists("test_rnmowr_pony")
  290. # self.assertTableNotExists("test_rnmowr_horse")
  291. def test_add_field(self):
  292. """
  293. Tests the AddField operation.
  294. """
  295. project_state = self.set_up_test_model("test_adfl")
  296. # Test the state alteration
  297. operation = migrations.AddField(
  298. "Pony",
  299. "height",
  300. models.FloatField(null=True, default=5),
  301. )
  302. new_state = project_state.clone()
  303. operation.state_forwards("test_adfl", new_state)
  304. self.assertEqual(len(new_state.models["test_adfl", "pony"].fields), 4)
  305. field = [
  306. f for n, f in new_state.models["test_adfl", "pony"].fields
  307. if n == "height"
  308. ][0]
  309. self.assertEqual(field.default, 5)
  310. # Test the database alteration
  311. self.assertColumnNotExists("test_adfl_pony", "height")
  312. with connection.schema_editor() as editor:
  313. operation.database_forwards("test_adfl", editor, project_state, new_state)
  314. self.assertColumnExists("test_adfl_pony", "height")
  315. # And test reversal
  316. with connection.schema_editor() as editor:
  317. operation.database_backwards("test_adfl", editor, new_state, project_state)
  318. self.assertColumnNotExists("test_adfl_pony", "height")
  319. def test_add_charfield(self):
  320. """
  321. Tests the AddField operation on TextField.
  322. """
  323. project_state = self.set_up_test_model("test_adchfl")
  324. new_apps = project_state.render()
  325. Pony = new_apps.get_model("test_adchfl", "Pony")
  326. pony = Pony.objects.create(weight=42)
  327. new_state = self.apply_operations("test_adchfl", project_state, [
  328. migrations.AddField(
  329. "Pony",
  330. "text",
  331. models.CharField(max_length=10, default="some text"),
  332. ),
  333. migrations.AddField(
  334. "Pony",
  335. "empty",
  336. models.CharField(max_length=10, default=""),
  337. ),
  338. # If not properly quoted digits would be interpreted as an int.
  339. migrations.AddField(
  340. "Pony",
  341. "digits",
  342. models.CharField(max_length=10, default="42"),
  343. ),
  344. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  345. migrations.AddField(
  346. "Pony",
  347. "quotes",
  348. models.CharField(max_length=10, default='"\'"'),
  349. ),
  350. ])
  351. new_apps = new_state.render()
  352. Pony = new_apps.get_model("test_adchfl", "Pony")
  353. pony = Pony.objects.get(pk=pony.pk)
  354. self.assertEqual(pony.text, "some text")
  355. self.assertEqual(pony.empty, "")
  356. self.assertEqual(pony.digits, "42")
  357. self.assertEqual(pony.quotes, '"\'"')
  358. def test_add_textfield(self):
  359. """
  360. Tests the AddField operation on TextField.
  361. """
  362. project_state = self.set_up_test_model("test_adtxtfl")
  363. new_apps = project_state.render()
  364. Pony = new_apps.get_model("test_adtxtfl", "Pony")
  365. pony = Pony.objects.create(weight=42)
  366. new_state = self.apply_operations("test_adtxtfl", project_state, [
  367. migrations.AddField(
  368. "Pony",
  369. "text",
  370. models.TextField(default="some text"),
  371. ),
  372. migrations.AddField(
  373. "Pony",
  374. "empty",
  375. models.TextField(default=""),
  376. ),
  377. # If not properly quoted digits would be interpreted as an int.
  378. migrations.AddField(
  379. "Pony",
  380. "digits",
  381. models.TextField(default="42"),
  382. ),
  383. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  384. migrations.AddField(
  385. "Pony",
  386. "quotes",
  387. models.TextField(default='"\'"'),
  388. ),
  389. ])
  390. new_apps = new_state.render()
  391. Pony = new_apps.get_model("test_adtxtfl", "Pony")
  392. pony = Pony.objects.get(pk=pony.pk)
  393. self.assertEqual(pony.text, "some text")
  394. self.assertEqual(pony.empty, "")
  395. self.assertEqual(pony.digits, "42")
  396. self.assertEqual(pony.quotes, '"\'"')
  397. @test.skipUnlessDBFeature('supports_binary_field')
  398. def test_add_binaryfield(self):
  399. """
  400. Tests the AddField operation on TextField/BinaryField.
  401. """
  402. project_state = self.set_up_test_model("test_adbinfl")
  403. new_apps = project_state.render()
  404. Pony = new_apps.get_model("test_adbinfl", "Pony")
  405. pony = Pony.objects.create(weight=42)
  406. new_state = self.apply_operations("test_adbinfl", project_state, [
  407. migrations.AddField(
  408. "Pony",
  409. "blob",
  410. models.BinaryField(default=b"some text"),
  411. ),
  412. migrations.AddField(
  413. "Pony",
  414. "empty",
  415. models.BinaryField(default=b""),
  416. ),
  417. # If not properly quoted digits would be interpreted as an int.
  418. migrations.AddField(
  419. "Pony",
  420. "digits",
  421. models.BinaryField(default=b"42"),
  422. ),
  423. # Manual quoting is fragile and could trip on quotes. Refs #xyz.
  424. migrations.AddField(
  425. "Pony",
  426. "quotes",
  427. models.BinaryField(default=b'"\'"'),
  428. ),
  429. ])
  430. new_apps = new_state.render()
  431. Pony = new_apps.get_model("test_adbinfl", "Pony")
  432. pony = Pony.objects.get(pk=pony.pk)
  433. # SQLite returns buffer/memoryview, cast to bytes for checking.
  434. self.assertEqual(bytes(pony.blob), b"some text")
  435. self.assertEqual(bytes(pony.empty), b"")
  436. self.assertEqual(bytes(pony.digits), b"42")
  437. self.assertEqual(bytes(pony.quotes), b'"\'"')
  438. def test_column_name_quoting(self):
  439. """
  440. Column names that are SQL keywords shouldn't cause problems when used
  441. in migrations (#22168).
  442. """
  443. project_state = self.set_up_test_model("test_regr22168")
  444. operation = migrations.AddField(
  445. "Pony",
  446. "order",
  447. models.IntegerField(default=0),
  448. )
  449. new_state = project_state.clone()
  450. operation.state_forwards("test_regr22168", new_state)
  451. with connection.schema_editor() as editor:
  452. operation.database_forwards("test_regr22168", editor, project_state, new_state)
  453. self.assertColumnExists("test_regr22168_pony", "order")
  454. def test_add_field_preserve_default(self):
  455. """
  456. Tests the AddField operation's state alteration
  457. when preserve_default = False.
  458. """
  459. project_state = self.set_up_test_model("test_adflpd")
  460. # Test the state alteration
  461. operation = migrations.AddField(
  462. "Pony",
  463. "height",
  464. models.FloatField(null=True, default=4),
  465. preserve_default=False,
  466. )
  467. new_state = project_state.clone()
  468. operation.state_forwards("test_adflpd", new_state)
  469. self.assertEqual(len(new_state.models["test_adflpd", "pony"].fields), 4)
  470. field = [
  471. f for n, f in new_state.models["test_adflpd", "pony"].fields
  472. if n == "height"
  473. ][0]
  474. self.assertEqual(field.default, NOT_PROVIDED)
  475. # Test the database alteration
  476. project_state.render().get_model("test_adflpd", "pony").objects.create(
  477. weight=4,
  478. )
  479. self.assertColumnNotExists("test_adflpd_pony", "height")
  480. with connection.schema_editor() as editor:
  481. operation.database_forwards("test_adflpd", editor, project_state, new_state)
  482. self.assertColumnExists("test_adflpd_pony", "height")
  483. def test_add_field_m2m(self):
  484. """
  485. Tests the AddField operation with a ManyToManyField.
  486. """
  487. project_state = self.set_up_test_model("test_adflmm", second_model=True)
  488. # Test the state alteration
  489. operation = migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
  490. new_state = project_state.clone()
  491. operation.state_forwards("test_adflmm", new_state)
  492. self.assertEqual(len(new_state.models["test_adflmm", "pony"].fields), 4)
  493. # Test the database alteration
  494. self.assertTableNotExists("test_adflmm_pony_stables")
  495. with connection.schema_editor() as editor:
  496. operation.database_forwards("test_adflmm", editor, project_state, new_state)
  497. self.assertTableExists("test_adflmm_pony_stables")
  498. self.assertColumnNotExists("test_adflmm_pony", "stables")
  499. # Make sure the M2M field actually works
  500. with atomic():
  501. new_apps = new_state.render()
  502. Pony = new_apps.get_model("test_adflmm", "Pony")
  503. p = Pony.objects.create(pink=False, weight=4.55)
  504. p.stables.create()
  505. self.assertEqual(p.stables.count(), 1)
  506. p.stables.all().delete()
  507. # And test reversal
  508. with connection.schema_editor() as editor:
  509. operation.database_backwards("test_adflmm", editor, new_state, project_state)
  510. self.assertTableNotExists("test_adflmm_pony_stables")
  511. def test_alter_field_m2m(self):
  512. project_state = self.set_up_test_model("test_alflmm", second_model=True)
  513. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  514. migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
  515. ])
  516. new_apps = project_state.render()
  517. Pony = new_apps.get_model("test_alflmm", "Pony")
  518. self.assertFalse(Pony._meta.get_field('stables').blank)
  519. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  520. migrations.AlterField("Pony", "stables", models.ManyToManyField(to="Stable", related_name="ponies", blank=True))
  521. ])
  522. new_apps = project_state.render()
  523. Pony = new_apps.get_model("test_alflmm", "Pony")
  524. self.assertTrue(Pony._meta.get_field('stables').blank)
  525. def test_repoint_field_m2m(self):
  526. project_state = self.set_up_test_model("test_alflmm", second_model=True, third_model=True)
  527. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  528. migrations.AddField("Pony", "places", models.ManyToManyField("Stable", related_name="ponies"))
  529. ])
  530. new_apps = project_state.render()
  531. Pony = new_apps.get_model("test_alflmm", "Pony")
  532. project_state = self.apply_operations("test_alflmm", project_state, operations=[
  533. migrations.AlterField("Pony", "places", models.ManyToManyField(to="Van", related_name="ponies"))
  534. ])
  535. # Ensure the new field actually works
  536. new_apps = project_state.render()
  537. Pony = new_apps.get_model("test_alflmm", "Pony")
  538. p = Pony.objects.create(pink=False, weight=4.55)
  539. p.places.create()
  540. self.assertEqual(p.places.count(), 1)
  541. p.places.all().delete()
  542. def test_remove_field_m2m(self):
  543. project_state = self.set_up_test_model("test_rmflmm", second_model=True)
  544. project_state = self.apply_operations("test_rmflmm", project_state, operations=[
  545. migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
  546. ])
  547. self.assertTableExists("test_rmflmm_pony_stables")
  548. operations = [migrations.RemoveField("Pony", "stables")]
  549. self.apply_operations("test_rmflmm", project_state, operations=operations)
  550. self.assertTableNotExists("test_rmflmm_pony_stables")
  551. # And test reversal
  552. self.unapply_operations("test_rmflmm", project_state, operations=operations)
  553. self.assertTableExists("test_rmflmm_pony_stables")
  554. def test_remove_field_m2m_with_through(self):
  555. project_state = self.set_up_test_model("test_rmflmmwt", second_model=True)
  556. self.assertTableNotExists("test_rmflmmwt_ponystables")
  557. project_state = self.apply_operations("test_rmflmmwt", project_state, operations=[
  558. migrations.CreateModel("PonyStables", fields=[
  559. ("pony", models.ForeignKey('test_rmflmmwt.Pony')),
  560. ("stable", models.ForeignKey('test_rmflmmwt.Stable')),
  561. ]),
  562. migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies", through='test_rmflmmwt.PonyStables'))
  563. ])
  564. self.assertTableExists("test_rmflmmwt_ponystables")
  565. operations = [migrations.RemoveField("Pony", "stables")]
  566. self.apply_operations("test_rmflmmwt", project_state, operations=operations)
  567. def test_remove_field(self):
  568. """
  569. Tests the RemoveField operation.
  570. """
  571. project_state = self.set_up_test_model("test_rmfl")
  572. # Test the state alteration
  573. operation = migrations.RemoveField("Pony", "pink")
  574. new_state = project_state.clone()
  575. operation.state_forwards("test_rmfl", new_state)
  576. self.assertEqual(len(new_state.models["test_rmfl", "pony"].fields), 2)
  577. # Test the database alteration
  578. self.assertColumnExists("test_rmfl_pony", "pink")
  579. with connection.schema_editor() as editor:
  580. operation.database_forwards("test_rmfl", editor, project_state, new_state)
  581. self.assertColumnNotExists("test_rmfl_pony", "pink")
  582. # And test reversal
  583. with connection.schema_editor() as editor:
  584. operation.database_backwards("test_rmfl", editor, new_state, project_state)
  585. self.assertColumnExists("test_rmfl_pony", "pink")
  586. def test_remove_fk(self):
  587. """
  588. Tests the RemoveField operation on a foreign key.
  589. """
  590. project_state = self.set_up_test_model("test_rfk", related_model=True)
  591. self.assertColumnExists("test_rfk_rider", "pony_id")
  592. operation = migrations.RemoveField("Rider", "pony")
  593. new_state = project_state.clone()
  594. operation.state_forwards("test_rfk", new_state)
  595. with connection.schema_editor() as editor:
  596. operation.database_forwards("test_rfk", editor, project_state, new_state)
  597. self.assertColumnNotExists("test_rfk_rider", "pony_id")
  598. with connection.schema_editor() as editor:
  599. operation.database_backwards("test_rfk", editor, new_state, project_state)
  600. self.assertColumnExists("test_rfk_rider", "pony_id")
  601. def test_alter_model_table(self):
  602. """
  603. Tests the AlterModelTable operation.
  604. """
  605. project_state = self.set_up_test_model("test_almota")
  606. # Test the state alteration
  607. operation = migrations.AlterModelTable("Pony", "test_almota_pony_2")
  608. new_state = project_state.clone()
  609. operation.state_forwards("test_almota", new_state)
  610. self.assertEqual(new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony_2")
  611. # Test the database alteration
  612. self.assertTableExists("test_almota_pony")
  613. self.assertTableNotExists("test_almota_pony_2")
  614. with connection.schema_editor() as editor:
  615. operation.database_forwards("test_almota", editor, project_state, new_state)
  616. self.assertTableNotExists("test_almota_pony")
  617. self.assertTableExists("test_almota_pony_2")
  618. # And test reversal
  619. with connection.schema_editor() as editor:
  620. operation.database_backwards("test_almota", editor, new_state, project_state)
  621. self.assertTableExists("test_almota_pony")
  622. self.assertTableNotExists("test_almota_pony_2")
  623. def test_alter_field(self):
  624. """
  625. Tests the AlterField operation.
  626. """
  627. project_state = self.set_up_test_model("test_alfl")
  628. # Test the state alteration
  629. operation = migrations.AlterField("Pony", "pink", models.IntegerField(null=True))
  630. new_state = project_state.clone()
  631. operation.state_forwards("test_alfl", new_state)
  632. self.assertEqual(project_state.models["test_alfl", "pony"].get_field_by_name("pink").null, False)
  633. self.assertEqual(new_state.models["test_alfl", "pony"].get_field_by_name("pink").null, True)
  634. # Test the database alteration
  635. self.assertColumnNotNull("test_alfl_pony", "pink")
  636. with connection.schema_editor() as editor:
  637. operation.database_forwards("test_alfl", editor, project_state, new_state)
  638. self.assertColumnNull("test_alfl_pony", "pink")
  639. # And test reversal
  640. with connection.schema_editor() as editor:
  641. operation.database_backwards("test_alfl", editor, new_state, project_state)
  642. self.assertColumnNotNull("test_alfl_pony", "pink")
  643. def test_alter_field_pk(self):
  644. """
  645. Tests the AlterField operation on primary keys (for things like PostgreSQL's SERIAL weirdness)
  646. """
  647. project_state = self.set_up_test_model("test_alflpk")
  648. # Test the state alteration
  649. operation = migrations.AlterField("Pony", "id", models.IntegerField(primary_key=True))
  650. new_state = project_state.clone()
  651. operation.state_forwards("test_alflpk", new_state)
  652. self.assertIsInstance(project_state.models["test_alflpk", "pony"].get_field_by_name("id"), models.AutoField)
  653. self.assertIsInstance(new_state.models["test_alflpk", "pony"].get_field_by_name("id"), models.IntegerField)
  654. # Test the database alteration
  655. with connection.schema_editor() as editor:
  656. operation.database_forwards("test_alflpk", editor, project_state, new_state)
  657. # And test reversal
  658. with connection.schema_editor() as editor:
  659. operation.database_backwards("test_alflpk", editor, new_state, project_state)
  660. @unittest.skipUnless(connection.features.supports_foreign_keys, "No FK support")
  661. def test_alter_field_pk_fk(self):
  662. """
  663. Tests the AlterField operation on primary keys changes any FKs pointing to it.
  664. """
  665. project_state = self.set_up_test_model("test_alflpkfk", related_model=True)
  666. # Test the state alteration
  667. operation = migrations.AlterField("Pony", "id", models.FloatField(primary_key=True))
  668. new_state = project_state.clone()
  669. operation.state_forwards("test_alflpkfk", new_state)
  670. self.assertIsInstance(project_state.models["test_alflpkfk", "pony"].get_field_by_name("id"), models.AutoField)
  671. self.assertIsInstance(new_state.models["test_alflpkfk", "pony"].get_field_by_name("id"), models.FloatField)
  672. def assertIdTypeEqualsFkType():
  673. with connection.cursor() as cursor:
  674. id_type = [c.type_code for c in connection.introspection.get_table_description(cursor, "test_alflpkfk_pony") if c.name == "id"][0]
  675. fk_type = [c.type_code for c in connection.introspection.get_table_description(cursor, "test_alflpkfk_rider") if c.name == "pony_id"][0]
  676. self.assertEqual(id_type, fk_type)
  677. assertIdTypeEqualsFkType()
  678. # Test the database alteration
  679. with connection.schema_editor() as editor:
  680. operation.database_forwards("test_alflpkfk", editor, project_state, new_state)
  681. assertIdTypeEqualsFkType()
  682. # And test reversal
  683. with connection.schema_editor() as editor:
  684. operation.database_backwards("test_alflpkfk", editor, new_state, project_state)
  685. assertIdTypeEqualsFkType()
  686. def test_rename_field(self):
  687. """
  688. Tests the RenameField operation.
  689. """
  690. project_state = self.set_up_test_model("test_rnfl")
  691. # Test the state alteration
  692. operation = migrations.RenameField("Pony", "pink", "blue")
  693. new_state = project_state.clone()
  694. operation.state_forwards("test_rnfl", new_state)
  695. self.assertIn("blue", [n for n, f in new_state.models["test_rnfl", "pony"].fields])
  696. self.assertNotIn("pink", [n for n, f in new_state.models["test_rnfl", "pony"].fields])
  697. # Test the database alteration
  698. self.assertColumnExists("test_rnfl_pony", "pink")
  699. self.assertColumnNotExists("test_rnfl_pony", "blue")
  700. with connection.schema_editor() as editor:
  701. operation.database_forwards("test_rnfl", editor, project_state, new_state)
  702. self.assertColumnExists("test_rnfl_pony", "blue")
  703. self.assertColumnNotExists("test_rnfl_pony", "pink")
  704. # And test reversal
  705. with connection.schema_editor() as editor:
  706. operation.database_backwards("test_rnfl", editor, new_state, project_state)
  707. self.assertColumnExists("test_rnfl_pony", "pink")
  708. self.assertColumnNotExists("test_rnfl_pony", "blue")
  709. def test_alter_unique_together(self):
  710. """
  711. Tests the AlterUniqueTogether operation.
  712. """
  713. project_state = self.set_up_test_model("test_alunto")
  714. # Test the state alteration
  715. operation = migrations.AlterUniqueTogether("Pony", [("pink", "weight")])
  716. new_state = project_state.clone()
  717. operation.state_forwards("test_alunto", new_state)
  718. self.assertEqual(len(project_state.models["test_alunto", "pony"].options.get("unique_together", set())), 0)
  719. self.assertEqual(len(new_state.models["test_alunto", "pony"].options.get("unique_together", set())), 1)
  720. # Make sure we can insert duplicate rows
  721. with connection.cursor() as cursor:
  722. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  723. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  724. cursor.execute("DELETE FROM test_alunto_pony")
  725. # Test the database alteration
  726. with connection.schema_editor() as editor:
  727. operation.database_forwards("test_alunto", editor, project_state, new_state)
  728. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  729. with self.assertRaises(IntegrityError):
  730. with atomic():
  731. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  732. cursor.execute("DELETE FROM test_alunto_pony")
  733. # And test reversal
  734. with connection.schema_editor() as editor:
  735. operation.database_backwards("test_alunto", editor, new_state, project_state)
  736. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  737. cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
  738. cursor.execute("DELETE FROM test_alunto_pony")
  739. # Test flat unique_together
  740. operation = migrations.AlterUniqueTogether("Pony", ("pink", "weight"))
  741. operation.state_forwards("test_alunto", new_state)
  742. self.assertEqual(len(new_state.models["test_alunto", "pony"].options.get("unique_together", set())), 1)
  743. def test_alter_index_together(self):
  744. """
  745. Tests the AlterIndexTogether operation.
  746. """
  747. project_state = self.set_up_test_model("test_alinto")
  748. # Test the state alteration
  749. operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")])
  750. new_state = project_state.clone()
  751. operation.state_forwards("test_alinto", new_state)
  752. self.assertEqual(len(project_state.models["test_alinto", "pony"].options.get("index_together", set())), 0)
  753. self.assertEqual(len(new_state.models["test_alinto", "pony"].options.get("index_together", set())), 1)
  754. # Make sure there's no matching index
  755. self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"])
  756. # Test the database alteration
  757. with connection.schema_editor() as editor:
  758. operation.database_forwards("test_alinto", editor, project_state, new_state)
  759. self.assertIndexExists("test_alinto_pony", ["pink", "weight"])
  760. # And test reversal
  761. with connection.schema_editor() as editor:
  762. operation.database_backwards("test_alinto", editor, new_state, project_state)
  763. self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"])
  764. @unittest.skipIf(sqlparse is None and connection.features.requires_sqlparse_for_splitting, "Missing sqlparse")
  765. def test_run_sql(self):
  766. """
  767. Tests the RunSQL operation.
  768. """
  769. project_state = self.set_up_test_model("test_runsql")
  770. # Create the operation
  771. operation = migrations.RunSQL(
  772. # Use a multi-line string with a commment to test splitting on SQLite and MySQL respectively
  773. "CREATE TABLE i_love_ponies (id int, special_thing int);\n"
  774. "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 42); -- this is magic!\n"
  775. "INSERT INTO i_love_ponies (id, special_thing) VALUES (2, 51);\n",
  776. "DROP TABLE i_love_ponies",
  777. state_operations=[migrations.CreateModel("SomethingElse", [("id", models.AutoField(primary_key=True))])],
  778. )
  779. # Test the state alteration
  780. new_state = project_state.clone()
  781. operation.state_forwards("test_runsql", new_state)
  782. self.assertEqual(len(new_state.models["test_runsql", "somethingelse"].fields), 1)
  783. # Make sure there's no table
  784. self.assertTableNotExists("i_love_ponies")
  785. # Test the database alteration
  786. with connection.schema_editor() as editor:
  787. operation.database_forwards("test_runsql", editor, project_state, new_state)
  788. self.assertTableExists("i_love_ponies")
  789. # Make sure all the SQL was processed
  790. with connection.cursor() as cursor:
  791. cursor.execute("SELECT COUNT(*) FROM i_love_ponies")
  792. self.assertEqual(cursor.fetchall()[0][0], 2)
  793. # And test reversal
  794. self.assertTrue(operation.reversible)
  795. with connection.schema_editor() as editor:
  796. operation.database_backwards("test_runsql", editor, new_state, project_state)
  797. self.assertTableNotExists("i_love_ponies")
  798. def test_run_python(self):
  799. """
  800. Tests the RunPython operation
  801. """
  802. project_state = self.set_up_test_model("test_runpython", mti_model=True)
  803. # Create the operation
  804. def inner_method(models, schema_editor):
  805. Pony = models.get_model("test_runpython", "Pony")
  806. Pony.objects.create(pink=1, weight=3.55)
  807. Pony.objects.create(weight=5)
  808. def inner_method_reverse(models, schema_editor):
  809. Pony = models.get_model("test_runpython", "Pony")
  810. Pony.objects.filter(pink=1, weight=3.55).delete()
  811. Pony.objects.filter(weight=5).delete()
  812. operation = migrations.RunPython(inner_method, reverse_code=inner_method_reverse)
  813. # Test the state alteration does nothing
  814. new_state = project_state.clone()
  815. operation.state_forwards("test_runpython", new_state)
  816. self.assertEqual(new_state, project_state)
  817. # Test the database alteration
  818. self.assertEqual(project_state.render().get_model("test_runpython", "Pony").objects.count(), 0)
  819. with connection.schema_editor() as editor:
  820. operation.database_forwards("test_runpython", editor, project_state, new_state)
  821. self.assertEqual(project_state.render().get_model("test_runpython", "Pony").objects.count(), 2)
  822. # Now test reversal
  823. self.assertTrue(operation.reversible)
  824. with connection.schema_editor() as editor:
  825. operation.database_backwards("test_runpython", editor, project_state, new_state)
  826. self.assertEqual(project_state.render().get_model("test_runpython", "Pony").objects.count(), 0)
  827. # Now test we can't use a string
  828. with self.assertRaises(ValueError):
  829. operation = migrations.RunPython("print 'ahahaha'")
  830. # Also test reversal fails, with an operation identical to above but without reverse_code set
  831. no_reverse_operation = migrations.RunPython(inner_method)
  832. self.assertFalse(no_reverse_operation.reversible)
  833. with connection.schema_editor() as editor:
  834. no_reverse_operation.database_forwards("test_runpython", editor, project_state, new_state)
  835. with self.assertRaises(NotImplementedError):
  836. no_reverse_operation.database_backwards("test_runpython", editor, new_state, project_state)
  837. self.assertEqual(project_state.render().get_model("test_runpython", "Pony").objects.count(), 2)
  838. def create_ponies(models, schema_editor):
  839. Pony = models.get_model("test_runpython", "Pony")
  840. pony1 = Pony.objects.create(pink=1, weight=3.55)
  841. self.assertIsNot(pony1.pk, None)
  842. pony2 = Pony.objects.create(weight=5)
  843. self.assertIsNot(pony2.pk, None)
  844. self.assertNotEqual(pony1.pk, pony2.pk)
  845. operation = migrations.RunPython(create_ponies)
  846. with connection.schema_editor() as editor:
  847. operation.database_forwards("test_runpython", editor, project_state, new_state)
  848. self.assertEqual(project_state.render().get_model("test_runpython", "Pony").objects.count(), 4)
  849. def create_shetlandponies(models, schema_editor):
  850. ShetlandPony = models.get_model("test_runpython", "ShetlandPony")
  851. pony1 = ShetlandPony.objects.create(weight=4.0)
  852. self.assertIsNot(pony1.pk, None)
  853. pony2 = ShetlandPony.objects.create(weight=5.0)
  854. self.assertIsNot(pony2.pk, None)
  855. self.assertNotEqual(pony1.pk, pony2.pk)
  856. operation = migrations.RunPython(create_shetlandponies)
  857. with connection.schema_editor() as editor:
  858. operation.database_forwards("test_runpython", editor, project_state, new_state)
  859. self.assertEqual(project_state.render().get_model("test_runpython", "Pony").objects.count(), 6)
  860. self.assertEqual(project_state.render().get_model("test_runpython", "ShetlandPony").objects.count(), 2)
  861. def test_run_python_atomic(self):
  862. """
  863. Tests the RunPython operation correctly handles the "atomic" keyword
  864. """
  865. project_state = self.set_up_test_model("test_runpythonatomic", mti_model=True)
  866. def inner_method(models, schema_editor):
  867. Pony = models.get_model("test_runpythonatomic", "Pony")
  868. Pony.objects.create(pink=1, weight=3.55)
  869. raise ValueError("Adrian hates ponies.")
  870. atomic_migration = Migration("test", "test_runpythonatomic")
  871. atomic_migration.operations = [migrations.RunPython(inner_method)]
  872. non_atomic_migration = Migration("test", "test_runpythonatomic")
  873. non_atomic_migration.operations = [migrations.RunPython(inner_method, atomic=False)]
  874. # If we're a fully-transactional database, both versions should rollback
  875. if connection.features.can_rollback_ddl:
  876. self.assertEqual(project_state.render().get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  877. with self.assertRaises(ValueError):
  878. with connection.schema_editor() as editor:
  879. atomic_migration.apply(project_state, editor)
  880. self.assertEqual(project_state.render().get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  881. with self.assertRaises(ValueError):
  882. with connection.schema_editor() as editor:
  883. non_atomic_migration.apply(project_state, editor)
  884. self.assertEqual(project_state.render().get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  885. # Otherwise, the non-atomic operation should leave a row there
  886. else:
  887. self.assertEqual(project_state.render().get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  888. with self.assertRaises(ValueError):
  889. with connection.schema_editor() as editor:
  890. atomic_migration.apply(project_state, editor)
  891. self.assertEqual(project_state.render().get_model("test_runpythonatomic", "Pony").objects.count(), 0)
  892. with self.assertRaises(ValueError):
  893. with connection.schema_editor() as editor:
  894. non_atomic_migration.apply(project_state, editor)
  895. self.assertEqual(project_state.render().get_model("test_runpythonatomic", "Pony").objects.count(), 1)
  896. class MigrateNothingRouter(object):
  897. """
  898. A router that sends all writes to the other database.
  899. """
  900. def allow_migrate(self, db, model):
  901. return False
  902. class MultiDBOperationTests(MigrationTestBase):
  903. multi_db = True
  904. def setUp(self):
  905. # Make the 'other' database appear to be a replica of the 'default'
  906. self.old_routers = router.routers
  907. router.routers = [MigrateNothingRouter()]
  908. def tearDown(self):
  909. # Restore the 'other' database as an independent database
  910. router.routers = self.old_routers
  911. def test_create_model(self):
  912. """
  913. Tests that CreateModel honours multi-db settings.
  914. """
  915. operation = migrations.CreateModel(
  916. "Pony",
  917. [
  918. ("id", models.AutoField(primary_key=True)),
  919. ("pink", models.IntegerField(default=1)),
  920. ],
  921. )
  922. # Test the state alteration
  923. project_state = ProjectState()
  924. new_state = project_state.clone()
  925. operation.state_forwards("test_crmo", new_state)
  926. # Test the database alteration
  927. self.assertTableNotExists("test_crmo_pony")
  928. with connection.schema_editor() as editor:
  929. operation.database_forwards("test_crmo", editor, project_state, new_state)
  930. self.assertTableNotExists("test_crmo_pony")
  931. # And test reversal
  932. with connection.schema_editor() as editor:
  933. operation.database_backwards("test_crmo", editor, new_state, project_state)
  934. self.assertTableNotExists("test_crmo_pony")