tests.py 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361
  1. import datetime
  2. import itertools
  3. import unittest
  4. from copy import copy
  5. from unittest import mock
  6. from django.db import (
  7. DatabaseError, IntegrityError, OperationalError, connection,
  8. )
  9. from django.db.models import Model
  10. from django.db.models.deletion import CASCADE, PROTECT
  11. from django.db.models.fields import (
  12. AutoField, BigAutoField, BigIntegerField, BinaryField, BooleanField,
  13. CharField, DateField, DateTimeField, IntegerField, PositiveIntegerField,
  14. SlugField, TextField, TimeField,
  15. )
  16. from django.db.models.fields.related import (
  17. ForeignKey, ForeignObject, ManyToManyField, OneToOneField,
  18. )
  19. from django.db.models.indexes import Index
  20. from django.db.transaction import TransactionManagementError, atomic
  21. from django.test import (
  22. TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature,
  23. )
  24. from django.test.utils import CaptureQueriesContext
  25. from django.utils import timezone
  26. from .fields import (
  27. CustomManyToManyField, InheritedManyToManyField, MediumBlobField,
  28. )
  29. from .models import (
  30. Author, AuthorCharFieldWithIndex, AuthorTextFieldWithIndex,
  31. AuthorWithDefaultHeight, AuthorWithEvenLongerName, AuthorWithIndexedName,
  32. Book, BookForeignObj, BookWeak, BookWithLongName, BookWithO2O,
  33. BookWithoutAuthor, BookWithSlug, IntegerPK, Node, Note, NoteRename, Tag,
  34. TagIndexed, TagM2MTest, TagUniqueRename, Thing, UniqueTest, new_apps,
  35. )
  36. class SchemaTests(TransactionTestCase):
  37. """
  38. Tests for the schema-alteration code.
  39. Be aware that these tests are more liable than most to false results,
  40. as sometimes the code to check if a test has worked is almost as complex
  41. as the code it is testing.
  42. """
  43. available_apps = []
  44. models = [
  45. Author, AuthorCharFieldWithIndex, AuthorTextFieldWithIndex,
  46. AuthorWithDefaultHeight, AuthorWithEvenLongerName, Book, BookWeak,
  47. BookWithLongName, BookWithO2O, BookWithSlug, IntegerPK, Node, Note,
  48. Tag, TagIndexed, TagM2MTest, TagUniqueRename, Thing, UniqueTest,
  49. ]
  50. # Utility functions
  51. def setUp(self):
  52. # local_models should contain test dependent model classes that will be
  53. # automatically removed from the app cache on test tear down.
  54. self.local_models = []
  55. def tearDown(self):
  56. # Delete any tables made for our models
  57. self.delete_tables()
  58. new_apps.clear_cache()
  59. for model in new_apps.get_models():
  60. model._meta._expire_cache()
  61. if 'schema' in new_apps.all_models:
  62. for model in self.local_models:
  63. for many_to_many in model._meta.many_to_many:
  64. through = many_to_many.remote_field.through
  65. if through and through._meta.auto_created:
  66. del new_apps.all_models['schema'][through._meta.model_name]
  67. del new_apps.all_models['schema'][model._meta.model_name]
  68. def delete_tables(self):
  69. "Deletes all model tables for our models for a clean test environment"
  70. converter = connection.introspection.table_name_converter
  71. with connection.schema_editor() as editor:
  72. connection.disable_constraint_checking()
  73. table_names = connection.introspection.table_names()
  74. for model in itertools.chain(SchemaTests.models, self.local_models):
  75. tbl = converter(model._meta.db_table)
  76. if tbl in table_names:
  77. editor.delete_model(model)
  78. table_names.remove(tbl)
  79. connection.enable_constraint_checking()
  80. def column_classes(self, model):
  81. with connection.cursor() as cursor:
  82. columns = {
  83. d[0]: (connection.introspection.get_field_type(d[1], d), d)
  84. for d in connection.introspection.get_table_description(
  85. cursor,
  86. model._meta.db_table,
  87. )
  88. }
  89. # SQLite has a different format for field_type
  90. for name, (type, desc) in columns.items():
  91. if isinstance(type, tuple):
  92. columns[name] = (type[0], desc)
  93. # SQLite also doesn't error properly
  94. if not columns:
  95. raise DatabaseError("Table does not exist (empty pragma)")
  96. return columns
  97. def get_primary_key(self, table):
  98. with connection.cursor() as cursor:
  99. return connection.introspection.get_primary_key_column(cursor, table)
  100. def get_indexes(self, table):
  101. """
  102. Get the indexes on the table using a new cursor.
  103. """
  104. with connection.cursor() as cursor:
  105. return [
  106. c['columns'][0]
  107. for c in connection.introspection.get_constraints(cursor, table).values()
  108. if c['index'] and len(c['columns']) == 1
  109. ]
  110. def get_constraints(self, table):
  111. """
  112. Get the constraints on a table using a new cursor.
  113. """
  114. with connection.cursor() as cursor:
  115. return connection.introspection.get_constraints(cursor, table)
  116. def get_constraints_for_column(self, model, column_name):
  117. constraints = self.get_constraints(model._meta.db_table)
  118. constraints_for_column = []
  119. for name, details in constraints.items():
  120. if details['columns'] == [column_name]:
  121. constraints_for_column.append(name)
  122. return sorted(constraints_for_column)
  123. def check_added_field_default(self, schema_editor, model, field, field_name, expected_default,
  124. cast_function=None):
  125. with connection.cursor() as cursor:
  126. schema_editor.add_field(model, field)
  127. cursor.execute("SELECT {} FROM {};".format(field_name, model._meta.db_table))
  128. database_default = cursor.fetchall()[0][0]
  129. if cast_function and not type(database_default) == type(expected_default):
  130. database_default = cast_function(database_default)
  131. self.assertEqual(database_default, expected_default)
  132. def get_constraints_count(self, table, column, fk_to):
  133. """
  134. Return a dict with keys 'fks', 'uniques, and 'indexes' indicating the
  135. number of foreign keys, unique constraints, and indexes on
  136. `table`.`column`. The `fk_to` argument is a 2-tuple specifying the
  137. expected foreign key relationship's (table, column).
  138. """
  139. with connection.cursor() as cursor:
  140. constraints = connection.introspection.get_constraints(cursor, table)
  141. counts = {'fks': 0, 'uniques': 0, 'indexes': 0}
  142. for c in constraints.values():
  143. if c['columns'] == [column]:
  144. if c['foreign_key'] == fk_to:
  145. counts['fks'] += 1
  146. if c['unique']:
  147. counts['uniques'] += 1
  148. elif c['index']:
  149. counts['indexes'] += 1
  150. return counts
  151. def assertIndexOrder(self, table, index, order):
  152. constraints = self.get_constraints(table)
  153. self.assertIn(index, constraints)
  154. index_orders = constraints[index]['orders']
  155. self.assertTrue(all(val == expected for val, expected in zip(index_orders, order)))
  156. def assertForeignKeyExists(self, model, column, expected_fk_table):
  157. """
  158. Fail if the FK constraint on `model.Meta.db_table`.`column` to
  159. `expected_fk_table`.id doesn't exist.
  160. """
  161. constraints = self.get_constraints(model._meta.db_table)
  162. constraint_fk = None
  163. for name, details in constraints.items():
  164. if details['columns'] == [column] and details['foreign_key']:
  165. constraint_fk = details['foreign_key']
  166. break
  167. self.assertEqual(constraint_fk, (expected_fk_table, 'id'))
  168. def assertForeignKeyNotExists(self, model, column, expected_fk_table):
  169. with self.assertRaises(AssertionError):
  170. self.assertForeignKeyExists(model, column, expected_fk_table)
  171. # Tests
  172. def test_creation_deletion(self):
  173. """
  174. Tries creating a model's table, and then deleting it.
  175. """
  176. # Create the table
  177. with connection.schema_editor() as editor:
  178. editor.create_model(Author)
  179. # The table is there
  180. list(Author.objects.all())
  181. # Clean up that table
  182. with connection.schema_editor() as editor:
  183. editor.delete_model(Author)
  184. # The table is gone
  185. with self.assertRaises(DatabaseError):
  186. list(Author.objects.all())
  187. @skipUnlessDBFeature('supports_foreign_keys')
  188. def test_fk(self):
  189. "Creating tables out of FK order, then repointing, works"
  190. # Create the table
  191. with connection.schema_editor() as editor:
  192. editor.create_model(Book)
  193. editor.create_model(Author)
  194. editor.create_model(Tag)
  195. # Initial tables are there
  196. list(Author.objects.all())
  197. list(Book.objects.all())
  198. # Make sure the FK constraint is present
  199. with self.assertRaises(IntegrityError):
  200. Book.objects.create(
  201. author_id=1,
  202. title="Much Ado About Foreign Keys",
  203. pub_date=datetime.datetime.now(),
  204. )
  205. # Repoint the FK constraint
  206. old_field = Book._meta.get_field("author")
  207. new_field = ForeignKey(Tag, CASCADE)
  208. new_field.set_attributes_from_name("author")
  209. with connection.schema_editor() as editor:
  210. editor.alter_field(Book, old_field, new_field, strict=True)
  211. self.assertForeignKeyExists(Book, 'author_id', 'schema_tag')
  212. @skipUnlessDBFeature('supports_foreign_keys')
  213. def test_char_field_with_db_index_to_fk(self):
  214. # Create the table
  215. with connection.schema_editor() as editor:
  216. editor.create_model(Author)
  217. editor.create_model(AuthorCharFieldWithIndex)
  218. # Change CharField to FK
  219. old_field = AuthorCharFieldWithIndex._meta.get_field('char_field')
  220. new_field = ForeignKey(Author, CASCADE, blank=True)
  221. new_field.set_attributes_from_name('char_field')
  222. with connection.schema_editor() as editor:
  223. editor.alter_field(AuthorCharFieldWithIndex, old_field, new_field, strict=True)
  224. self.assertForeignKeyExists(AuthorCharFieldWithIndex, 'char_field_id', 'schema_author')
  225. @skipUnlessDBFeature('supports_foreign_keys')
  226. @skipUnlessDBFeature('supports_index_on_text_field')
  227. def test_text_field_with_db_index_to_fk(self):
  228. # Create the table
  229. with connection.schema_editor() as editor:
  230. editor.create_model(Author)
  231. editor.create_model(AuthorTextFieldWithIndex)
  232. # Change TextField to FK
  233. old_field = AuthorTextFieldWithIndex._meta.get_field('text_field')
  234. new_field = ForeignKey(Author, CASCADE, blank=True)
  235. new_field.set_attributes_from_name('text_field')
  236. with connection.schema_editor() as editor:
  237. editor.alter_field(AuthorTextFieldWithIndex, old_field, new_field, strict=True)
  238. self.assertForeignKeyExists(AuthorTextFieldWithIndex, 'text_field_id', 'schema_author')
  239. @skipUnlessDBFeature('supports_foreign_keys')
  240. def test_fk_to_proxy(self):
  241. "Creating a FK to a proxy model creates database constraints."
  242. class AuthorProxy(Author):
  243. class Meta:
  244. app_label = 'schema'
  245. apps = new_apps
  246. proxy = True
  247. class AuthorRef(Model):
  248. author = ForeignKey(AuthorProxy, on_delete=CASCADE)
  249. class Meta:
  250. app_label = 'schema'
  251. apps = new_apps
  252. self.local_models = [AuthorProxy, AuthorRef]
  253. # Create the table
  254. with connection.schema_editor() as editor:
  255. editor.create_model(Author)
  256. editor.create_model(AuthorRef)
  257. self.assertForeignKeyExists(AuthorRef, 'author_id', 'schema_author')
  258. @skipUnlessDBFeature('supports_foreign_keys')
  259. def test_fk_db_constraint(self):
  260. "The db_constraint parameter is respected"
  261. # Create the table
  262. with connection.schema_editor() as editor:
  263. editor.create_model(Tag)
  264. editor.create_model(Author)
  265. editor.create_model(BookWeak)
  266. # Initial tables are there
  267. list(Author.objects.all())
  268. list(Tag.objects.all())
  269. list(BookWeak.objects.all())
  270. self.assertForeignKeyNotExists(BookWeak, 'author_id', 'schema_author')
  271. # Make a db_constraint=False FK
  272. new_field = ForeignKey(Tag, CASCADE, db_constraint=False)
  273. new_field.set_attributes_from_name("tag")
  274. with connection.schema_editor() as editor:
  275. editor.add_field(Author, new_field)
  276. self.assertForeignKeyNotExists(Author, 'tag_id', 'schema_tag')
  277. # Alter to one with a constraint
  278. new_field2 = ForeignKey(Tag, CASCADE)
  279. new_field2.set_attributes_from_name("tag")
  280. with connection.schema_editor() as editor:
  281. editor.alter_field(Author, new_field, new_field2, strict=True)
  282. self.assertForeignKeyExists(Author, 'tag_id', 'schema_tag')
  283. # Alter to one without a constraint again
  284. new_field2 = ForeignKey(Tag, CASCADE)
  285. new_field2.set_attributes_from_name("tag")
  286. with connection.schema_editor() as editor:
  287. editor.alter_field(Author, new_field2, new_field, strict=True)
  288. self.assertForeignKeyNotExists(Author, 'tag_id', 'schema_tag')
  289. def _test_m2m_db_constraint(self, M2MFieldClass):
  290. class LocalAuthorWithM2M(Model):
  291. name = CharField(max_length=255)
  292. class Meta:
  293. app_label = 'schema'
  294. apps = new_apps
  295. self.local_models = [LocalAuthorWithM2M]
  296. # Create the table
  297. with connection.schema_editor() as editor:
  298. editor.create_model(Tag)
  299. editor.create_model(LocalAuthorWithM2M)
  300. # Initial tables are there
  301. list(LocalAuthorWithM2M.objects.all())
  302. list(Tag.objects.all())
  303. # Make a db_constraint=False FK
  304. new_field = M2MFieldClass(Tag, related_name="authors", db_constraint=False)
  305. new_field.contribute_to_class(LocalAuthorWithM2M, "tags")
  306. # Add the field
  307. with connection.schema_editor() as editor:
  308. editor.add_field(LocalAuthorWithM2M, new_field)
  309. self.assertForeignKeyNotExists(new_field.remote_field.through, 'tag_id', 'schema_tag')
  310. @skipUnlessDBFeature('supports_foreign_keys')
  311. def test_m2m_db_constraint(self):
  312. self._test_m2m_db_constraint(ManyToManyField)
  313. @skipUnlessDBFeature('supports_foreign_keys')
  314. def test_m2m_db_constraint_custom(self):
  315. self._test_m2m_db_constraint(CustomManyToManyField)
  316. @skipUnlessDBFeature('supports_foreign_keys')
  317. def test_m2m_db_constraint_inherited(self):
  318. self._test_m2m_db_constraint(InheritedManyToManyField)
  319. def test_add_field(self):
  320. """
  321. Tests adding fields to models
  322. """
  323. # Create the table
  324. with connection.schema_editor() as editor:
  325. editor.create_model(Author)
  326. # Ensure there's no age field
  327. columns = self.column_classes(Author)
  328. self.assertNotIn("age", columns)
  329. # Add the new field
  330. new_field = IntegerField(null=True)
  331. new_field.set_attributes_from_name("age")
  332. with CaptureQueriesContext(connection) as ctx, connection.schema_editor() as editor:
  333. editor.add_field(Author, new_field)
  334. drop_default_sql = editor.sql_alter_column_no_default % {
  335. 'column': editor.quote_name(new_field.name),
  336. }
  337. self.assertFalse(any(drop_default_sql in query['sql'] for query in ctx.captured_queries))
  338. # Ensure the field is right afterwards
  339. columns = self.column_classes(Author)
  340. self.assertEqual(columns['age'][0], "IntegerField")
  341. self.assertEqual(columns['age'][1][6], True)
  342. def test_add_field_temp_default(self):
  343. """
  344. Tests adding fields to models with a temporary default
  345. """
  346. # Create the table
  347. with connection.schema_editor() as editor:
  348. editor.create_model(Author)
  349. # Ensure there's no age field
  350. columns = self.column_classes(Author)
  351. self.assertNotIn("age", columns)
  352. # Add some rows of data
  353. Author.objects.create(name="Andrew", height=30)
  354. Author.objects.create(name="Andrea")
  355. # Add a not-null field
  356. new_field = CharField(max_length=30, default="Godwin")
  357. new_field.set_attributes_from_name("surname")
  358. with connection.schema_editor() as editor:
  359. editor.add_field(Author, new_field)
  360. # Ensure the field is right afterwards
  361. columns = self.column_classes(Author)
  362. self.assertEqual(columns['surname'][0], "CharField")
  363. self.assertEqual(columns['surname'][1][6],
  364. connection.features.interprets_empty_strings_as_nulls)
  365. def test_add_field_temp_default_boolean(self):
  366. """
  367. Tests adding fields to models with a temporary default where
  368. the default is False. (#21783)
  369. """
  370. # Create the table
  371. with connection.schema_editor() as editor:
  372. editor.create_model(Author)
  373. # Ensure there's no age field
  374. columns = self.column_classes(Author)
  375. self.assertNotIn("age", columns)
  376. # Add some rows of data
  377. Author.objects.create(name="Andrew", height=30)
  378. Author.objects.create(name="Andrea")
  379. # Add a not-null field
  380. new_field = BooleanField(default=False)
  381. new_field.set_attributes_from_name("awesome")
  382. with connection.schema_editor() as editor:
  383. editor.add_field(Author, new_field)
  384. # Ensure the field is right afterwards
  385. columns = self.column_classes(Author)
  386. # BooleanField are stored as TINYINT(1) on MySQL.
  387. field_type = columns['awesome'][0]
  388. self.assertEqual(
  389. field_type,
  390. connection.features.introspected_boolean_field_type(new_field)
  391. )
  392. def test_add_field_default_transform(self):
  393. """
  394. Tests adding fields to models with a default that is not directly
  395. valid in the database (#22581)
  396. """
  397. class TestTransformField(IntegerField):
  398. # Weird field that saves the count of items in its value
  399. def get_default(self):
  400. return self.default
  401. def get_prep_value(self, value):
  402. if value is None:
  403. return 0
  404. return len(value)
  405. # Create the table
  406. with connection.schema_editor() as editor:
  407. editor.create_model(Author)
  408. # Add some rows of data
  409. Author.objects.create(name="Andrew", height=30)
  410. Author.objects.create(name="Andrea")
  411. # Add the field with a default it needs to cast (to string in this case)
  412. new_field = TestTransformField(default={1: 2})
  413. new_field.set_attributes_from_name("thing")
  414. with connection.schema_editor() as editor:
  415. editor.add_field(Author, new_field)
  416. # Ensure the field is there
  417. columns = self.column_classes(Author)
  418. field_type, field_info = columns['thing']
  419. self.assertEqual(field_type, 'IntegerField')
  420. # Make sure the values were transformed correctly
  421. self.assertEqual(Author.objects.extra(where=["thing = 1"]).count(), 2)
  422. def test_add_field_binary(self):
  423. """
  424. Tests binary fields get a sane default (#22851)
  425. """
  426. # Create the table
  427. with connection.schema_editor() as editor:
  428. editor.create_model(Author)
  429. # Add the new field
  430. new_field = BinaryField(blank=True)
  431. new_field.set_attributes_from_name("bits")
  432. with connection.schema_editor() as editor:
  433. editor.add_field(Author, new_field)
  434. # Ensure the field is right afterwards
  435. columns = self.column_classes(Author)
  436. # MySQL annoyingly uses the same backend, so it'll come back as one of
  437. # these two types.
  438. self.assertIn(columns['bits'][0], ("BinaryField", "TextField"))
  439. @unittest.skipUnless(connection.vendor == 'mysql', "MySQL specific")
  440. def test_add_binaryfield_mediumblob(self):
  441. """
  442. Test adding a custom-sized binary field on MySQL (#24846).
  443. """
  444. # Create the table
  445. with connection.schema_editor() as editor:
  446. editor.create_model(Author)
  447. # Add the new field with default
  448. new_field = MediumBlobField(blank=True, default=b'123')
  449. new_field.set_attributes_from_name('bits')
  450. with connection.schema_editor() as editor:
  451. editor.add_field(Author, new_field)
  452. columns = self.column_classes(Author)
  453. # Introspection treats BLOBs as TextFields
  454. self.assertEqual(columns['bits'][0], "TextField")
  455. def test_alter(self):
  456. """
  457. Tests simple altering of fields
  458. """
  459. # Create the table
  460. with connection.schema_editor() as editor:
  461. editor.create_model(Author)
  462. # Ensure the field is right to begin with
  463. columns = self.column_classes(Author)
  464. self.assertEqual(columns['name'][0], "CharField")
  465. self.assertEqual(bool(columns['name'][1][6]), bool(connection.features.interprets_empty_strings_as_nulls))
  466. # Alter the name field to a TextField
  467. old_field = Author._meta.get_field("name")
  468. new_field = TextField(null=True)
  469. new_field.set_attributes_from_name("name")
  470. with connection.schema_editor() as editor:
  471. editor.alter_field(Author, old_field, new_field, strict=True)
  472. # Ensure the field is right afterwards
  473. columns = self.column_classes(Author)
  474. self.assertEqual(columns['name'][0], "TextField")
  475. self.assertEqual(columns['name'][1][6], True)
  476. # Change nullability again
  477. new_field2 = TextField(null=False)
  478. new_field2.set_attributes_from_name("name")
  479. with connection.schema_editor() as editor:
  480. editor.alter_field(Author, new_field, new_field2, strict=True)
  481. # Ensure the field is right afterwards
  482. columns = self.column_classes(Author)
  483. self.assertEqual(columns['name'][0], "TextField")
  484. self.assertEqual(bool(columns['name'][1][6]), bool(connection.features.interprets_empty_strings_as_nulls))
  485. def test_alter_auto_field_to_integer_field(self):
  486. # Create the table
  487. with connection.schema_editor() as editor:
  488. editor.create_model(Author)
  489. # Change AutoField to IntegerField
  490. old_field = Author._meta.get_field('id')
  491. new_field = IntegerField(primary_key=True)
  492. new_field.set_attributes_from_name('id')
  493. new_field.model = Author
  494. with connection.schema_editor() as editor:
  495. editor.alter_field(Author, old_field, new_field, strict=True)
  496. def test_alter_auto_field_to_char_field(self):
  497. # Create the table
  498. with connection.schema_editor() as editor:
  499. editor.create_model(Author)
  500. # Change AutoField to CharField
  501. old_field = Author._meta.get_field('id')
  502. new_field = CharField(primary_key=True, max_length=50)
  503. new_field.set_attributes_from_name('id')
  504. new_field.model = Author
  505. with connection.schema_editor() as editor:
  506. editor.alter_field(Author, old_field, new_field, strict=True)
  507. def test_alter_text_field(self):
  508. # Regression for "BLOB/TEXT column 'info' can't have a default value")
  509. # on MySQL.
  510. # Create the table
  511. with connection.schema_editor() as editor:
  512. editor.create_model(Note)
  513. old_field = Note._meta.get_field("info")
  514. new_field = TextField(blank=True)
  515. new_field.set_attributes_from_name("info")
  516. with connection.schema_editor() as editor:
  517. editor.alter_field(Note, old_field, new_field, strict=True)
  518. @skipUnlessDBFeature('can_defer_constraint_checks', 'can_rollback_ddl')
  519. def test_alter_fk_checks_deferred_constraints(self):
  520. """
  521. #25492 - Altering a foreign key's structure and data in the same
  522. transaction.
  523. """
  524. with connection.schema_editor() as editor:
  525. editor.create_model(Node)
  526. old_field = Node._meta.get_field('parent')
  527. new_field = ForeignKey(Node, CASCADE)
  528. new_field.set_attributes_from_name('parent')
  529. parent = Node.objects.create()
  530. with connection.schema_editor() as editor:
  531. # Update the parent FK to create a deferred constraint check.
  532. Node.objects.update(parent=parent)
  533. editor.alter_field(Node, old_field, new_field, strict=True)
  534. def test_alter_text_field_to_date_field(self):
  535. """
  536. #25002 - Test conversion of text field to date field.
  537. """
  538. with connection.schema_editor() as editor:
  539. editor.create_model(Note)
  540. Note.objects.create(info='1988-05-05')
  541. old_field = Note._meta.get_field('info')
  542. new_field = DateField(blank=True)
  543. new_field.set_attributes_from_name('info')
  544. with connection.schema_editor() as editor:
  545. editor.alter_field(Note, old_field, new_field, strict=True)
  546. # Make sure the field isn't nullable
  547. columns = self.column_classes(Note)
  548. self.assertFalse(columns['info'][1][6])
  549. def test_alter_text_field_to_datetime_field(self):
  550. """
  551. #25002 - Test conversion of text field to datetime field.
  552. """
  553. with connection.schema_editor() as editor:
  554. editor.create_model(Note)
  555. Note.objects.create(info='1988-05-05 3:16:17.4567')
  556. old_field = Note._meta.get_field('info')
  557. new_field = DateTimeField(blank=True)
  558. new_field.set_attributes_from_name('info')
  559. with connection.schema_editor() as editor:
  560. editor.alter_field(Note, old_field, new_field, strict=True)
  561. # Make sure the field isn't nullable
  562. columns = self.column_classes(Note)
  563. self.assertFalse(columns['info'][1][6])
  564. def test_alter_text_field_to_time_field(self):
  565. """
  566. #25002 - Test conversion of text field to time field.
  567. """
  568. with connection.schema_editor() as editor:
  569. editor.create_model(Note)
  570. Note.objects.create(info='3:16:17.4567')
  571. old_field = Note._meta.get_field('info')
  572. new_field = TimeField(blank=True)
  573. new_field.set_attributes_from_name('info')
  574. with connection.schema_editor() as editor:
  575. editor.alter_field(Note, old_field, new_field, strict=True)
  576. # Make sure the field isn't nullable
  577. columns = self.column_classes(Note)
  578. self.assertFalse(columns['info'][1][6])
  579. @skipIfDBFeature('interprets_empty_strings_as_nulls')
  580. def test_alter_textual_field_keep_null_status(self):
  581. """
  582. Changing a field type shouldn't affect the not null status.
  583. """
  584. with connection.schema_editor() as editor:
  585. editor.create_model(Note)
  586. with self.assertRaises(IntegrityError):
  587. Note.objects.create(info=None)
  588. old_field = Note._meta.get_field("info")
  589. new_field = CharField(max_length=50)
  590. new_field.set_attributes_from_name("info")
  591. with connection.schema_editor() as editor:
  592. editor.alter_field(Note, old_field, new_field, strict=True)
  593. with self.assertRaises(IntegrityError):
  594. Note.objects.create(info=None)
  595. def test_alter_numeric_field_keep_null_status(self):
  596. """
  597. Changing a field type shouldn't affect the not null status.
  598. """
  599. with connection.schema_editor() as editor:
  600. editor.create_model(UniqueTest)
  601. with self.assertRaises(IntegrityError):
  602. UniqueTest.objects.create(year=None, slug='aaa')
  603. old_field = UniqueTest._meta.get_field("year")
  604. new_field = BigIntegerField()
  605. new_field.set_attributes_from_name("year")
  606. with connection.schema_editor() as editor:
  607. editor.alter_field(UniqueTest, old_field, new_field, strict=True)
  608. with self.assertRaises(IntegrityError):
  609. UniqueTest.objects.create(year=None, slug='bbb')
  610. def test_alter_null_to_not_null(self):
  611. """
  612. #23609 - Tests handling of default values when altering from NULL to NOT NULL.
  613. """
  614. # Create the table
  615. with connection.schema_editor() as editor:
  616. editor.create_model(Author)
  617. # Ensure the field is right to begin with
  618. columns = self.column_classes(Author)
  619. self.assertTrue(columns['height'][1][6])
  620. # Create some test data
  621. Author.objects.create(name='Not null author', height=12)
  622. Author.objects.create(name='Null author')
  623. # Verify null value
  624. self.assertEqual(Author.objects.get(name='Not null author').height, 12)
  625. self.assertIsNone(Author.objects.get(name='Null author').height)
  626. # Alter the height field to NOT NULL with default
  627. old_field = Author._meta.get_field("height")
  628. new_field = PositiveIntegerField(default=42)
  629. new_field.set_attributes_from_name("height")
  630. with connection.schema_editor() as editor:
  631. editor.alter_field(Author, old_field, new_field, strict=True)
  632. # Ensure the field is right afterwards
  633. columns = self.column_classes(Author)
  634. self.assertFalse(columns['height'][1][6])
  635. # Verify default value
  636. self.assertEqual(Author.objects.get(name='Not null author').height, 12)
  637. self.assertEqual(Author.objects.get(name='Null author').height, 42)
  638. def test_alter_charfield_to_null(self):
  639. """
  640. #24307 - Should skip an alter statement on databases with
  641. interprets_empty_strings_as_null when changing a CharField to null.
  642. """
  643. # Create the table
  644. with connection.schema_editor() as editor:
  645. editor.create_model(Author)
  646. # Change the CharField to null
  647. old_field = Author._meta.get_field('name')
  648. new_field = copy(old_field)
  649. new_field.null = True
  650. with connection.schema_editor() as editor:
  651. editor.alter_field(Author, old_field, new_field, strict=True)
  652. def test_alter_textfield_to_null(self):
  653. """
  654. #24307 - Should skip an alter statement on databases with
  655. interprets_empty_strings_as_null when changing a TextField to null.
  656. """
  657. # Create the table
  658. with connection.schema_editor() as editor:
  659. editor.create_model(Note)
  660. # Change the TextField to null
  661. old_field = Note._meta.get_field('info')
  662. new_field = copy(old_field)
  663. new_field.null = True
  664. with connection.schema_editor() as editor:
  665. editor.alter_field(Note, old_field, new_field, strict=True)
  666. @skipUnlessDBFeature('supports_combined_alters')
  667. def test_alter_null_to_not_null_keeping_default(self):
  668. """
  669. #23738 - Can change a nullable field with default to non-nullable
  670. with the same default.
  671. """
  672. # Create the table
  673. with connection.schema_editor() as editor:
  674. editor.create_model(AuthorWithDefaultHeight)
  675. # Ensure the field is right to begin with
  676. columns = self.column_classes(AuthorWithDefaultHeight)
  677. self.assertTrue(columns['height'][1][6])
  678. # Alter the height field to NOT NULL keeping the previous default
  679. old_field = AuthorWithDefaultHeight._meta.get_field("height")
  680. new_field = PositiveIntegerField(default=42)
  681. new_field.set_attributes_from_name("height")
  682. with connection.schema_editor() as editor:
  683. editor.alter_field(AuthorWithDefaultHeight, old_field, new_field, strict=True)
  684. # Ensure the field is right afterwards
  685. columns = self.column_classes(AuthorWithDefaultHeight)
  686. self.assertFalse(columns['height'][1][6])
  687. @skipUnlessDBFeature('supports_foreign_keys')
  688. def test_alter_fk(self):
  689. """
  690. Tests altering of FKs
  691. """
  692. # Create the table
  693. with connection.schema_editor() as editor:
  694. editor.create_model(Author)
  695. editor.create_model(Book)
  696. # Ensure the field is right to begin with
  697. columns = self.column_classes(Book)
  698. self.assertEqual(columns['author_id'][0], "IntegerField")
  699. self.assertForeignKeyExists(Book, 'author_id', 'schema_author')
  700. # Alter the FK
  701. old_field = Book._meta.get_field("author")
  702. new_field = ForeignKey(Author, CASCADE, editable=False)
  703. new_field.set_attributes_from_name("author")
  704. with connection.schema_editor() as editor:
  705. editor.alter_field(Book, old_field, new_field, strict=True)
  706. # Ensure the field is right afterwards
  707. columns = self.column_classes(Book)
  708. self.assertEqual(columns['author_id'][0], "IntegerField")
  709. self.assertForeignKeyExists(Book, 'author_id', 'schema_author')
  710. @skipUnlessDBFeature('supports_foreign_keys')
  711. def test_alter_to_fk(self):
  712. """
  713. #24447 - Tests adding a FK constraint for an existing column
  714. """
  715. class LocalBook(Model):
  716. author = IntegerField()
  717. title = CharField(max_length=100, db_index=True)
  718. pub_date = DateTimeField()
  719. class Meta:
  720. app_label = 'schema'
  721. apps = new_apps
  722. self.local_models = [LocalBook]
  723. # Create the tables
  724. with connection.schema_editor() as editor:
  725. editor.create_model(Author)
  726. editor.create_model(LocalBook)
  727. # Ensure no FK constraint exists
  728. constraints = self.get_constraints(LocalBook._meta.db_table)
  729. for name, details in constraints.items():
  730. if details['foreign_key']:
  731. self.fail('Found an unexpected FK constraint to %s' % details['columns'])
  732. old_field = LocalBook._meta.get_field("author")
  733. new_field = ForeignKey(Author, CASCADE)
  734. new_field.set_attributes_from_name("author")
  735. with connection.schema_editor() as editor:
  736. editor.alter_field(LocalBook, old_field, new_field, strict=True)
  737. self.assertForeignKeyExists(LocalBook, 'author_id', 'schema_author')
  738. @skipUnlessDBFeature('supports_foreign_keys')
  739. def test_alter_o2o_to_fk(self):
  740. """
  741. #24163 - Tests altering of OneToOneField to ForeignKey
  742. """
  743. # Create the table
  744. with connection.schema_editor() as editor:
  745. editor.create_model(Author)
  746. editor.create_model(BookWithO2O)
  747. # Ensure the field is right to begin with
  748. columns = self.column_classes(BookWithO2O)
  749. self.assertEqual(columns['author_id'][0], "IntegerField")
  750. # Ensure the field is unique
  751. author = Author.objects.create(name="Joe")
  752. BookWithO2O.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now())
  753. with self.assertRaises(IntegrityError):
  754. BookWithO2O.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now())
  755. BookWithO2O.objects.all().delete()
  756. self.assertForeignKeyExists(BookWithO2O, 'author_id', 'schema_author')
  757. # Alter the OneToOneField to ForeignKey
  758. old_field = BookWithO2O._meta.get_field("author")
  759. new_field = ForeignKey(Author, CASCADE)
  760. new_field.set_attributes_from_name("author")
  761. with connection.schema_editor() as editor:
  762. editor.alter_field(BookWithO2O, old_field, new_field, strict=True)
  763. # Ensure the field is right afterwards
  764. columns = self.column_classes(Book)
  765. self.assertEqual(columns['author_id'][0], "IntegerField")
  766. # Ensure the field is not unique anymore
  767. Book.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now())
  768. Book.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now())
  769. self.assertForeignKeyExists(Book, 'author_id', 'schema_author')
  770. @skipUnlessDBFeature('supports_foreign_keys')
  771. def test_alter_fk_to_o2o(self):
  772. """
  773. #24163 - Tests altering of ForeignKey to OneToOneField
  774. """
  775. # Create the table
  776. with connection.schema_editor() as editor:
  777. editor.create_model(Author)
  778. editor.create_model(Book)
  779. # Ensure the field is right to begin with
  780. columns = self.column_classes(Book)
  781. self.assertEqual(columns['author_id'][0], "IntegerField")
  782. # Ensure the field is not unique
  783. author = Author.objects.create(name="Joe")
  784. Book.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now())
  785. Book.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now())
  786. Book.objects.all().delete()
  787. self.assertForeignKeyExists(Book, 'author_id', 'schema_author')
  788. # Alter the ForeignKey to OneToOneField
  789. old_field = Book._meta.get_field("author")
  790. new_field = OneToOneField(Author, CASCADE)
  791. new_field.set_attributes_from_name("author")
  792. with connection.schema_editor() as editor:
  793. editor.alter_field(Book, old_field, new_field, strict=True)
  794. # Ensure the field is right afterwards
  795. columns = self.column_classes(BookWithO2O)
  796. self.assertEqual(columns['author_id'][0], "IntegerField")
  797. # Ensure the field is unique now
  798. BookWithO2O.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now())
  799. with self.assertRaises(IntegrityError):
  800. BookWithO2O.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now())
  801. self.assertForeignKeyExists(BookWithO2O, 'author_id', 'schema_author')
  802. def test_alter_field_fk_to_o2o(self):
  803. with connection.schema_editor() as editor:
  804. editor.create_model(Author)
  805. editor.create_model(Book)
  806. expected_fks = 1 if connection.features.supports_foreign_keys else 0
  807. # Check the index is right to begin with.
  808. counts = self.get_constraints_count(
  809. Book._meta.db_table,
  810. Book._meta.get_field('author').column,
  811. (Author._meta.db_table, Author._meta.pk.column),
  812. )
  813. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 0, 'indexes': 1})
  814. old_field = Book._meta.get_field('author')
  815. new_field = OneToOneField(Author, CASCADE)
  816. new_field.set_attributes_from_name('author')
  817. with connection.schema_editor() as editor:
  818. editor.alter_field(Book, old_field, new_field, strict=True)
  819. counts = self.get_constraints_count(
  820. Book._meta.db_table,
  821. Book._meta.get_field('author').column,
  822. (Author._meta.db_table, Author._meta.pk.column),
  823. )
  824. # The index on ForeignKey is replaced with a unique constraint for OneToOneField.
  825. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 1, 'indexes': 0})
  826. def test_alter_field_fk_keeps_index(self):
  827. with connection.schema_editor() as editor:
  828. editor.create_model(Author)
  829. editor.create_model(Book)
  830. expected_fks = 1 if connection.features.supports_foreign_keys else 0
  831. # Check the index is right to begin with.
  832. counts = self.get_constraints_count(
  833. Book._meta.db_table,
  834. Book._meta.get_field('author').column,
  835. (Author._meta.db_table, Author._meta.pk.column),
  836. )
  837. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 0, 'indexes': 1})
  838. old_field = Book._meta.get_field('author')
  839. # on_delete changed from CASCADE.
  840. new_field = ForeignKey(Author, PROTECT)
  841. new_field.set_attributes_from_name('author')
  842. with connection.schema_editor() as editor:
  843. editor.alter_field(Book, old_field, new_field, strict=True)
  844. counts = self.get_constraints_count(
  845. Book._meta.db_table,
  846. Book._meta.get_field('author').column,
  847. (Author._meta.db_table, Author._meta.pk.column),
  848. )
  849. # The index remains.
  850. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 0, 'indexes': 1})
  851. def test_alter_field_o2o_to_fk(self):
  852. with connection.schema_editor() as editor:
  853. editor.create_model(Author)
  854. editor.create_model(BookWithO2O)
  855. expected_fks = 1 if connection.features.supports_foreign_keys else 0
  856. # Check the unique constraint is right to begin with.
  857. counts = self.get_constraints_count(
  858. BookWithO2O._meta.db_table,
  859. BookWithO2O._meta.get_field('author').column,
  860. (Author._meta.db_table, Author._meta.pk.column),
  861. )
  862. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 1, 'indexes': 0})
  863. old_field = BookWithO2O._meta.get_field('author')
  864. new_field = ForeignKey(Author, CASCADE)
  865. new_field.set_attributes_from_name('author')
  866. with connection.schema_editor() as editor:
  867. editor.alter_field(BookWithO2O, old_field, new_field, strict=True)
  868. counts = self.get_constraints_count(
  869. BookWithO2O._meta.db_table,
  870. BookWithO2O._meta.get_field('author').column,
  871. (Author._meta.db_table, Author._meta.pk.column),
  872. )
  873. # The unique constraint on OneToOneField is replaced with an index for ForeignKey.
  874. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 0, 'indexes': 1})
  875. def test_alter_field_o2o_keeps_unique(self):
  876. with connection.schema_editor() as editor:
  877. editor.create_model(Author)
  878. editor.create_model(BookWithO2O)
  879. expected_fks = 1 if connection.features.supports_foreign_keys else 0
  880. # Check the unique constraint is right to begin with.
  881. counts = self.get_constraints_count(
  882. BookWithO2O._meta.db_table,
  883. BookWithO2O._meta.get_field('author').column,
  884. (Author._meta.db_table, Author._meta.pk.column),
  885. )
  886. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 1, 'indexes': 0})
  887. old_field = BookWithO2O._meta.get_field('author')
  888. # on_delete changed from CASCADE.
  889. new_field = OneToOneField(Author, PROTECT)
  890. new_field.set_attributes_from_name('author')
  891. with connection.schema_editor() as editor:
  892. editor.alter_field(BookWithO2O, old_field, new_field, strict=True)
  893. counts = self.get_constraints_count(
  894. BookWithO2O._meta.db_table,
  895. BookWithO2O._meta.get_field('author').column,
  896. (Author._meta.db_table, Author._meta.pk.column),
  897. )
  898. # The unique constraint remains.
  899. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 1, 'indexes': 0})
  900. def test_alter_db_table_case(self):
  901. # Create the table
  902. with connection.schema_editor() as editor:
  903. editor.create_model(Author)
  904. # Alter the case of the table
  905. old_table_name = Author._meta.db_table
  906. with connection.schema_editor() as editor:
  907. editor.alter_db_table(Author, old_table_name, old_table_name.upper())
  908. def test_alter_implicit_id_to_explicit(self):
  909. """
  910. Should be able to convert an implicit "id" field to an explicit "id"
  911. primary key field.
  912. """
  913. with connection.schema_editor() as editor:
  914. editor.create_model(Author)
  915. old_field = Author._meta.get_field("id")
  916. new_field = AutoField(primary_key=True)
  917. new_field.set_attributes_from_name("id")
  918. new_field.model = Author
  919. with connection.schema_editor() as editor:
  920. editor.alter_field(Author, old_field, new_field, strict=True)
  921. # This will fail if DROP DEFAULT is inadvertently executed on this
  922. # field which drops the id sequence, at least on PostgreSQL.
  923. Author.objects.create(name='Foo')
  924. Author.objects.create(name='Bar')
  925. def test_alter_int_pk_to_autofield_pk(self):
  926. """
  927. Should be able to rename an IntegerField(primary_key=True) to
  928. AutoField(primary_key=True).
  929. """
  930. with connection.schema_editor() as editor:
  931. editor.create_model(IntegerPK)
  932. old_field = IntegerPK._meta.get_field('i')
  933. new_field = AutoField(primary_key=True)
  934. new_field.model = IntegerPK
  935. new_field.set_attributes_from_name('i')
  936. with connection.schema_editor() as editor:
  937. editor.alter_field(IntegerPK, old_field, new_field, strict=True)
  938. def test_alter_int_pk_to_bigautofield_pk(self):
  939. """
  940. Should be able to rename an IntegerField(primary_key=True) to
  941. BigAutoField(primary_key=True).
  942. """
  943. with connection.schema_editor() as editor:
  944. editor.create_model(IntegerPK)
  945. old_field = IntegerPK._meta.get_field('i')
  946. new_field = BigAutoField(primary_key=True)
  947. new_field.model = IntegerPK
  948. new_field.set_attributes_from_name('i')
  949. with connection.schema_editor() as editor:
  950. editor.alter_field(IntegerPK, old_field, new_field, strict=True)
  951. def test_alter_int_pk_to_int_unique(self):
  952. """
  953. Should be able to rename an IntegerField(primary_key=True) to
  954. IntegerField(unique=True).
  955. """
  956. class IntegerUnique(Model):
  957. i = IntegerField(unique=True)
  958. j = IntegerField(primary_key=True)
  959. class Meta:
  960. app_label = 'schema'
  961. apps = new_apps
  962. db_table = 'INTEGERPK'
  963. with connection.schema_editor() as editor:
  964. editor.create_model(IntegerPK)
  965. # model requires a new PK
  966. old_field = IntegerPK._meta.get_field('j')
  967. new_field = IntegerField(primary_key=True)
  968. new_field.model = IntegerPK
  969. new_field.set_attributes_from_name('j')
  970. with connection.schema_editor() as editor:
  971. editor.alter_field(IntegerPK, old_field, new_field, strict=True)
  972. old_field = IntegerPK._meta.get_field('i')
  973. new_field = IntegerField(unique=True)
  974. new_field.model = IntegerPK
  975. new_field.set_attributes_from_name('i')
  976. with connection.schema_editor() as editor:
  977. editor.alter_field(IntegerPK, old_field, new_field, strict=True)
  978. # Ensure unique constraint works.
  979. IntegerUnique.objects.create(i=1, j=1)
  980. with self.assertRaises(IntegrityError):
  981. IntegerUnique.objects.create(i=1, j=2)
  982. def test_rename(self):
  983. """
  984. Tests simple altering of fields
  985. """
  986. # Create the table
  987. with connection.schema_editor() as editor:
  988. editor.create_model(Author)
  989. # Ensure the field is right to begin with
  990. columns = self.column_classes(Author)
  991. self.assertEqual(columns['name'][0], "CharField")
  992. self.assertNotIn("display_name", columns)
  993. # Alter the name field's name
  994. old_field = Author._meta.get_field("name")
  995. new_field = CharField(max_length=254)
  996. new_field.set_attributes_from_name("display_name")
  997. with connection.schema_editor() as editor:
  998. editor.alter_field(Author, old_field, new_field, strict=True)
  999. # Ensure the field is right afterwards
  1000. columns = self.column_classes(Author)
  1001. self.assertEqual(columns['display_name'][0], "CharField")
  1002. self.assertNotIn("name", columns)
  1003. @skipIfDBFeature('interprets_empty_strings_as_nulls')
  1004. def test_rename_keep_null_status(self):
  1005. """
  1006. Renaming a field shouldn't affect the not null status.
  1007. """
  1008. with connection.schema_editor() as editor:
  1009. editor.create_model(Note)
  1010. with self.assertRaises(IntegrityError):
  1011. Note.objects.create(info=None)
  1012. old_field = Note._meta.get_field("info")
  1013. new_field = TextField()
  1014. new_field.set_attributes_from_name("detail_info")
  1015. with connection.schema_editor() as editor:
  1016. editor.alter_field(Note, old_field, new_field, strict=True)
  1017. columns = self.column_classes(Note)
  1018. self.assertEqual(columns['detail_info'][0], "TextField")
  1019. self.assertNotIn("info", columns)
  1020. with self.assertRaises(IntegrityError):
  1021. NoteRename.objects.create(detail_info=None)
  1022. def _test_m2m_create(self, M2MFieldClass):
  1023. """
  1024. Tests M2M fields on models during creation
  1025. """
  1026. class LocalBookWithM2M(Model):
  1027. author = ForeignKey(Author, CASCADE)
  1028. title = CharField(max_length=100, db_index=True)
  1029. pub_date = DateTimeField()
  1030. tags = M2MFieldClass("TagM2MTest", related_name="books")
  1031. class Meta:
  1032. app_label = 'schema'
  1033. apps = new_apps
  1034. self.local_models = [LocalBookWithM2M]
  1035. # Create the tables
  1036. with connection.schema_editor() as editor:
  1037. editor.create_model(Author)
  1038. editor.create_model(TagM2MTest)
  1039. editor.create_model(LocalBookWithM2M)
  1040. # Ensure there is now an m2m table there
  1041. columns = self.column_classes(LocalBookWithM2M._meta.get_field("tags").remote_field.through)
  1042. self.assertEqual(columns['tagm2mtest_id'][0], "IntegerField")
  1043. def test_m2m_create(self):
  1044. self._test_m2m_create(ManyToManyField)
  1045. def test_m2m_create_custom(self):
  1046. self._test_m2m_create(CustomManyToManyField)
  1047. def test_m2m_create_inherited(self):
  1048. self._test_m2m_create(InheritedManyToManyField)
  1049. def _test_m2m_create_through(self, M2MFieldClass):
  1050. """
  1051. Tests M2M fields on models during creation with through models
  1052. """
  1053. class LocalTagThrough(Model):
  1054. book = ForeignKey("schema.LocalBookWithM2MThrough", CASCADE)
  1055. tag = ForeignKey("schema.TagM2MTest", CASCADE)
  1056. class Meta:
  1057. app_label = 'schema'
  1058. apps = new_apps
  1059. class LocalBookWithM2MThrough(Model):
  1060. tags = M2MFieldClass("TagM2MTest", related_name="books", through=LocalTagThrough)
  1061. class Meta:
  1062. app_label = 'schema'
  1063. apps = new_apps
  1064. self.local_models = [LocalTagThrough, LocalBookWithM2MThrough]
  1065. # Create the tables
  1066. with connection.schema_editor() as editor:
  1067. editor.create_model(LocalTagThrough)
  1068. editor.create_model(TagM2MTest)
  1069. editor.create_model(LocalBookWithM2MThrough)
  1070. # Ensure there is now an m2m table there
  1071. columns = self.column_classes(LocalTagThrough)
  1072. self.assertEqual(columns['book_id'][0], "IntegerField")
  1073. self.assertEqual(columns['tag_id'][0], "IntegerField")
  1074. def test_m2m_create_through(self):
  1075. self._test_m2m_create_through(ManyToManyField)
  1076. def test_m2m_create_through_custom(self):
  1077. self._test_m2m_create_through(CustomManyToManyField)
  1078. def test_m2m_create_through_inherited(self):
  1079. self._test_m2m_create_through(InheritedManyToManyField)
  1080. def _test_m2m(self, M2MFieldClass):
  1081. """
  1082. Tests adding/removing M2M fields on models
  1083. """
  1084. class LocalAuthorWithM2M(Model):
  1085. name = CharField(max_length=255)
  1086. class Meta:
  1087. app_label = 'schema'
  1088. apps = new_apps
  1089. self.local_models = [LocalAuthorWithM2M]
  1090. # Create the tables
  1091. with connection.schema_editor() as editor:
  1092. editor.create_model(LocalAuthorWithM2M)
  1093. editor.create_model(TagM2MTest)
  1094. # Create an M2M field
  1095. new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors")
  1096. new_field.contribute_to_class(LocalAuthorWithM2M, "tags")
  1097. # Ensure there's no m2m table there
  1098. with self.assertRaises(DatabaseError):
  1099. self.column_classes(new_field.remote_field.through)
  1100. # Add the field
  1101. with connection.schema_editor() as editor:
  1102. editor.add_field(LocalAuthorWithM2M, new_field)
  1103. # Ensure there is now an m2m table there
  1104. columns = self.column_classes(new_field.remote_field.through)
  1105. self.assertEqual(columns['tagm2mtest_id'][0], "IntegerField")
  1106. # "Alter" the field. This should not rename the DB table to itself.
  1107. with connection.schema_editor() as editor:
  1108. editor.alter_field(LocalAuthorWithM2M, new_field, new_field, strict=True)
  1109. # Remove the M2M table again
  1110. with connection.schema_editor() as editor:
  1111. editor.remove_field(LocalAuthorWithM2M, new_field)
  1112. # Ensure there's no m2m table there
  1113. with self.assertRaises(DatabaseError):
  1114. self.column_classes(new_field.remote_field.through)
  1115. # Make sure the model state is coherent with the table one now that
  1116. # we've removed the tags field.
  1117. opts = LocalAuthorWithM2M._meta
  1118. opts.local_many_to_many.remove(new_field)
  1119. del new_apps.all_models['schema'][new_field.remote_field.through._meta.model_name]
  1120. opts._expire_cache()
  1121. def test_m2m(self):
  1122. self._test_m2m(ManyToManyField)
  1123. def test_m2m_custom(self):
  1124. self._test_m2m(CustomManyToManyField)
  1125. def test_m2m_inherited(self):
  1126. self._test_m2m(InheritedManyToManyField)
  1127. def _test_m2m_through_alter(self, M2MFieldClass):
  1128. """
  1129. Tests altering M2Ms with explicit through models (should no-op)
  1130. """
  1131. class LocalAuthorTag(Model):
  1132. author = ForeignKey("schema.LocalAuthorWithM2MThrough", CASCADE)
  1133. tag = ForeignKey("schema.TagM2MTest", CASCADE)
  1134. class Meta:
  1135. app_label = 'schema'
  1136. apps = new_apps
  1137. class LocalAuthorWithM2MThrough(Model):
  1138. name = CharField(max_length=255)
  1139. tags = M2MFieldClass("schema.TagM2MTest", related_name="authors", through=LocalAuthorTag)
  1140. class Meta:
  1141. app_label = 'schema'
  1142. apps = new_apps
  1143. self.local_models = [LocalAuthorTag, LocalAuthorWithM2MThrough]
  1144. # Create the tables
  1145. with connection.schema_editor() as editor:
  1146. editor.create_model(LocalAuthorTag)
  1147. editor.create_model(LocalAuthorWithM2MThrough)
  1148. editor.create_model(TagM2MTest)
  1149. # Ensure the m2m table is there
  1150. self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3)
  1151. # "Alter" the field's blankness. This should not actually do anything.
  1152. old_field = LocalAuthorWithM2MThrough._meta.get_field("tags")
  1153. new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors", through=LocalAuthorTag)
  1154. new_field.contribute_to_class(LocalAuthorWithM2MThrough, "tags")
  1155. with connection.schema_editor() as editor:
  1156. editor.alter_field(LocalAuthorWithM2MThrough, old_field, new_field, strict=True)
  1157. # Ensure the m2m table is still there
  1158. self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3)
  1159. def test_m2m_through_alter(self):
  1160. self._test_m2m_through_alter(ManyToManyField)
  1161. def test_m2m_through_alter_custom(self):
  1162. self._test_m2m_through_alter(CustomManyToManyField)
  1163. def test_m2m_through_alter_inherited(self):
  1164. self._test_m2m_through_alter(InheritedManyToManyField)
  1165. def _test_m2m_repoint(self, M2MFieldClass):
  1166. """
  1167. Tests repointing M2M fields
  1168. """
  1169. class LocalBookWithM2M(Model):
  1170. author = ForeignKey(Author, CASCADE)
  1171. title = CharField(max_length=100, db_index=True)
  1172. pub_date = DateTimeField()
  1173. tags = M2MFieldClass("TagM2MTest", related_name="books")
  1174. class Meta:
  1175. app_label = 'schema'
  1176. apps = new_apps
  1177. self.local_models = [LocalBookWithM2M]
  1178. # Create the tables
  1179. with connection.schema_editor() as editor:
  1180. editor.create_model(Author)
  1181. editor.create_model(LocalBookWithM2M)
  1182. editor.create_model(TagM2MTest)
  1183. editor.create_model(UniqueTest)
  1184. # Ensure the M2M exists and points to TagM2MTest
  1185. if connection.features.supports_foreign_keys:
  1186. self.assertForeignKeyExists(
  1187. LocalBookWithM2M._meta.get_field("tags").remote_field.through,
  1188. 'tagm2mtest_id',
  1189. 'schema_tagm2mtest',
  1190. )
  1191. # Repoint the M2M
  1192. old_field = LocalBookWithM2M._meta.get_field("tags")
  1193. new_field = M2MFieldClass(UniqueTest)
  1194. new_field.contribute_to_class(LocalBookWithM2M, "uniques")
  1195. with connection.schema_editor() as editor:
  1196. editor.alter_field(LocalBookWithM2M, old_field, new_field, strict=True)
  1197. # Ensure old M2M is gone
  1198. with self.assertRaises(DatabaseError):
  1199. self.column_classes(LocalBookWithM2M._meta.get_field("tags").remote_field.through)
  1200. # This model looks like the new model and is used for teardown.
  1201. opts = LocalBookWithM2M._meta
  1202. opts.local_many_to_many.remove(old_field)
  1203. # Ensure the new M2M exists and points to UniqueTest
  1204. if connection.features.supports_foreign_keys:
  1205. self.assertForeignKeyExists(new_field.remote_field.through, 'uniquetest_id', 'schema_uniquetest')
  1206. def test_m2m_repoint(self):
  1207. self._test_m2m_repoint(ManyToManyField)
  1208. def test_m2m_repoint_custom(self):
  1209. self._test_m2m_repoint(CustomManyToManyField)
  1210. def test_m2m_repoint_inherited(self):
  1211. self._test_m2m_repoint(InheritedManyToManyField)
  1212. @skipUnlessDBFeature('supports_column_check_constraints')
  1213. def test_check_constraints(self):
  1214. """
  1215. Tests creating/deleting CHECK constraints
  1216. """
  1217. # Create the tables
  1218. with connection.schema_editor() as editor:
  1219. editor.create_model(Author)
  1220. # Ensure the constraint exists
  1221. constraints = self.get_constraints(Author._meta.db_table)
  1222. for name, details in constraints.items():
  1223. if details['columns'] == ["height"] and details['check']:
  1224. break
  1225. else:
  1226. self.fail("No check constraint for height found")
  1227. # Alter the column to remove it
  1228. old_field = Author._meta.get_field("height")
  1229. new_field = IntegerField(null=True, blank=True)
  1230. new_field.set_attributes_from_name("height")
  1231. with connection.schema_editor() as editor:
  1232. editor.alter_field(Author, old_field, new_field, strict=True)
  1233. constraints = self.get_constraints(Author._meta.db_table)
  1234. for name, details in constraints.items():
  1235. if details['columns'] == ["height"] and details['check']:
  1236. self.fail("Check constraint for height found")
  1237. # Alter the column to re-add it
  1238. new_field2 = Author._meta.get_field("height")
  1239. with connection.schema_editor() as editor:
  1240. editor.alter_field(Author, new_field, new_field2, strict=True)
  1241. constraints = self.get_constraints(Author._meta.db_table)
  1242. for name, details in constraints.items():
  1243. if details['columns'] == ["height"] and details['check']:
  1244. break
  1245. else:
  1246. self.fail("No check constraint for height found")
  1247. def test_unique(self):
  1248. """
  1249. Tests removing and adding unique constraints to a single column.
  1250. """
  1251. # Create the table
  1252. with connection.schema_editor() as editor:
  1253. editor.create_model(Tag)
  1254. # Ensure the field is unique to begin with
  1255. Tag.objects.create(title="foo", slug="foo")
  1256. with self.assertRaises(IntegrityError):
  1257. Tag.objects.create(title="bar", slug="foo")
  1258. Tag.objects.all().delete()
  1259. # Alter the slug field to be non-unique
  1260. old_field = Tag._meta.get_field("slug")
  1261. new_field = SlugField(unique=False)
  1262. new_field.set_attributes_from_name("slug")
  1263. with connection.schema_editor() as editor:
  1264. editor.alter_field(Tag, old_field, new_field, strict=True)
  1265. # Ensure the field is no longer unique
  1266. Tag.objects.create(title="foo", slug="foo")
  1267. Tag.objects.create(title="bar", slug="foo")
  1268. Tag.objects.all().delete()
  1269. # Alter the slug field to be unique
  1270. new_field2 = SlugField(unique=True)
  1271. new_field2.set_attributes_from_name("slug")
  1272. with connection.schema_editor() as editor:
  1273. editor.alter_field(Tag, new_field, new_field2, strict=True)
  1274. # Ensure the field is unique again
  1275. Tag.objects.create(title="foo", slug="foo")
  1276. with self.assertRaises(IntegrityError):
  1277. Tag.objects.create(title="bar", slug="foo")
  1278. Tag.objects.all().delete()
  1279. # Rename the field
  1280. new_field3 = SlugField(unique=True)
  1281. new_field3.set_attributes_from_name("slug2")
  1282. with connection.schema_editor() as editor:
  1283. editor.alter_field(Tag, new_field2, new_field3, strict=True)
  1284. # Ensure the field is still unique
  1285. TagUniqueRename.objects.create(title="foo", slug2="foo")
  1286. with self.assertRaises(IntegrityError):
  1287. TagUniqueRename.objects.create(title="bar", slug2="foo")
  1288. Tag.objects.all().delete()
  1289. def test_unique_together(self):
  1290. """
  1291. Tests removing and adding unique_together constraints on a model.
  1292. """
  1293. # Create the table
  1294. with connection.schema_editor() as editor:
  1295. editor.create_model(UniqueTest)
  1296. # Ensure the fields are unique to begin with
  1297. UniqueTest.objects.create(year=2012, slug="foo")
  1298. UniqueTest.objects.create(year=2011, slug="foo")
  1299. UniqueTest.objects.create(year=2011, slug="bar")
  1300. with self.assertRaises(IntegrityError):
  1301. UniqueTest.objects.create(year=2012, slug="foo")
  1302. UniqueTest.objects.all().delete()
  1303. # Alter the model to its non-unique-together companion
  1304. with connection.schema_editor() as editor:
  1305. editor.alter_unique_together(UniqueTest, UniqueTest._meta.unique_together, [])
  1306. # Ensure the fields are no longer unique
  1307. UniqueTest.objects.create(year=2012, slug="foo")
  1308. UniqueTest.objects.create(year=2012, slug="foo")
  1309. UniqueTest.objects.all().delete()
  1310. # Alter it back
  1311. new_field2 = SlugField(unique=True)
  1312. new_field2.set_attributes_from_name("slug")
  1313. with connection.schema_editor() as editor:
  1314. editor.alter_unique_together(UniqueTest, [], UniqueTest._meta.unique_together)
  1315. # Ensure the fields are unique again
  1316. UniqueTest.objects.create(year=2012, slug="foo")
  1317. with self.assertRaises(IntegrityError):
  1318. UniqueTest.objects.create(year=2012, slug="foo")
  1319. UniqueTest.objects.all().delete()
  1320. def test_unique_together_with_fk(self):
  1321. """
  1322. Tests removing and adding unique_together constraints that include
  1323. a foreign key.
  1324. """
  1325. # Create the table
  1326. with connection.schema_editor() as editor:
  1327. editor.create_model(Author)
  1328. editor.create_model(Book)
  1329. # Ensure the fields are unique to begin with
  1330. self.assertEqual(Book._meta.unique_together, ())
  1331. # Add the unique_together constraint
  1332. with connection.schema_editor() as editor:
  1333. editor.alter_unique_together(Book, [], [['author', 'title']])
  1334. # Alter it back
  1335. with connection.schema_editor() as editor:
  1336. editor.alter_unique_together(Book, [['author', 'title']], [])
  1337. def test_unique_together_with_fk_with_existing_index(self):
  1338. """
  1339. Tests removing and adding unique_together constraints that include
  1340. a foreign key, where the foreign key is added after the model is
  1341. created.
  1342. """
  1343. # Create the tables
  1344. with connection.schema_editor() as editor:
  1345. editor.create_model(Author)
  1346. editor.create_model(BookWithoutAuthor)
  1347. new_field = ForeignKey(Author, CASCADE)
  1348. new_field.set_attributes_from_name('author')
  1349. editor.add_field(BookWithoutAuthor, new_field)
  1350. # Ensure the fields aren't unique to begin with
  1351. self.assertEqual(Book._meta.unique_together, ())
  1352. # Add the unique_together constraint
  1353. with connection.schema_editor() as editor:
  1354. editor.alter_unique_together(Book, [], [['author', 'title']])
  1355. # Alter it back
  1356. with connection.schema_editor() as editor:
  1357. editor.alter_unique_together(Book, [['author', 'title']], [])
  1358. def test_index_together(self):
  1359. """
  1360. Tests removing and adding index_together constraints on a model.
  1361. """
  1362. # Create the table
  1363. with connection.schema_editor() as editor:
  1364. editor.create_model(Tag)
  1365. # Ensure there's no index on the year/slug columns first
  1366. self.assertEqual(
  1367. False,
  1368. any(
  1369. c["index"]
  1370. for c in self.get_constraints("schema_tag").values()
  1371. if c['columns'] == ["slug", "title"]
  1372. ),
  1373. )
  1374. # Alter the model to add an index
  1375. with connection.schema_editor() as editor:
  1376. editor.alter_index_together(Tag, [], [("slug", "title")])
  1377. # Ensure there is now an index
  1378. self.assertEqual(
  1379. True,
  1380. any(
  1381. c["index"]
  1382. for c in self.get_constraints("schema_tag").values()
  1383. if c['columns'] == ["slug", "title"]
  1384. ),
  1385. )
  1386. # Alter it back
  1387. new_field2 = SlugField(unique=True)
  1388. new_field2.set_attributes_from_name("slug")
  1389. with connection.schema_editor() as editor:
  1390. editor.alter_index_together(Tag, [("slug", "title")], [])
  1391. # Ensure there's no index
  1392. self.assertEqual(
  1393. False,
  1394. any(
  1395. c["index"]
  1396. for c in self.get_constraints("schema_tag").values()
  1397. if c['columns'] == ["slug", "title"]
  1398. ),
  1399. )
  1400. def test_index_together_with_fk(self):
  1401. """
  1402. Tests removing and adding index_together constraints that include
  1403. a foreign key.
  1404. """
  1405. # Create the table
  1406. with connection.schema_editor() as editor:
  1407. editor.create_model(Author)
  1408. editor.create_model(Book)
  1409. # Ensure the fields are unique to begin with
  1410. self.assertEqual(Book._meta.index_together, ())
  1411. # Add the unique_together constraint
  1412. with connection.schema_editor() as editor:
  1413. editor.alter_index_together(Book, [], [['author', 'title']])
  1414. # Alter it back
  1415. with connection.schema_editor() as editor:
  1416. editor.alter_index_together(Book, [['author', 'title']], [])
  1417. def test_create_index_together(self):
  1418. """
  1419. Tests creating models with index_together already defined
  1420. """
  1421. # Create the table
  1422. with connection.schema_editor() as editor:
  1423. editor.create_model(TagIndexed)
  1424. # Ensure there is an index
  1425. self.assertEqual(
  1426. True,
  1427. any(
  1428. c["index"]
  1429. for c in self.get_constraints("schema_tagindexed").values()
  1430. if c['columns'] == ["slug", "title"]
  1431. ),
  1432. )
  1433. def test_db_table(self):
  1434. """
  1435. Tests renaming of the table
  1436. """
  1437. # Create the table
  1438. with connection.schema_editor() as editor:
  1439. editor.create_model(Author)
  1440. # Ensure the table is there to begin with
  1441. columns = self.column_classes(Author)
  1442. self.assertEqual(columns['name'][0], "CharField")
  1443. # Alter the table
  1444. with connection.schema_editor() as editor:
  1445. editor.alter_db_table(Author, "schema_author", "schema_otherauthor")
  1446. # Ensure the table is there afterwards
  1447. Author._meta.db_table = "schema_otherauthor"
  1448. columns = self.column_classes(Author)
  1449. self.assertEqual(columns['name'][0], "CharField")
  1450. # Alter the table again
  1451. with connection.schema_editor() as editor:
  1452. editor.alter_db_table(Author, "schema_otherauthor", "schema_author")
  1453. # Ensure the table is still there
  1454. Author._meta.db_table = "schema_author"
  1455. columns = self.column_classes(Author)
  1456. self.assertEqual(columns['name'][0], "CharField")
  1457. def test_add_remove_index(self):
  1458. """
  1459. Tests index addition and removal
  1460. """
  1461. # Create the table
  1462. with connection.schema_editor() as editor:
  1463. editor.create_model(Author)
  1464. # Ensure the table is there and has no index
  1465. self.assertNotIn('title', self.get_indexes(Author._meta.db_table))
  1466. # Add the index
  1467. index = Index(fields=['name'], name='author_title_idx')
  1468. with connection.schema_editor() as editor:
  1469. editor.add_index(Author, index)
  1470. self.assertIn('name', self.get_indexes(Author._meta.db_table))
  1471. # Drop the index
  1472. with connection.schema_editor() as editor:
  1473. editor.remove_index(Author, index)
  1474. self.assertNotIn('name', self.get_indexes(Author._meta.db_table))
  1475. def test_remove_db_index_doesnt_remove_custom_indexes(self):
  1476. """
  1477. Changing db_index to False doesn't remove indexes from Meta.indexes.
  1478. """
  1479. with connection.schema_editor() as editor:
  1480. editor.create_model(AuthorWithIndexedName)
  1481. # Ensure the table has its index
  1482. self.assertIn('name', self.get_indexes(AuthorWithIndexedName._meta.db_table))
  1483. # Add the custom index
  1484. index = Index(fields=['-name'], name='author_name_idx')
  1485. author_index_name = index.name
  1486. with connection.schema_editor() as editor:
  1487. db_index_name = editor._create_index_name(
  1488. model=AuthorWithIndexedName,
  1489. column_names=('name',),
  1490. )
  1491. if connection.features.uppercases_column_names:
  1492. author_index_name = author_index_name.upper()
  1493. db_index_name = db_index_name.upper()
  1494. try:
  1495. AuthorWithIndexedName._meta.indexes = [index]
  1496. with connection.schema_editor() as editor:
  1497. editor.add_index(AuthorWithIndexedName, index)
  1498. old_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table)
  1499. self.assertIn(author_index_name, old_constraints)
  1500. self.assertIn(db_index_name, old_constraints)
  1501. # Change name field to db_index=False
  1502. old_field = AuthorWithIndexedName._meta.get_field('name')
  1503. new_field = CharField(max_length=255)
  1504. new_field.set_attributes_from_name('name')
  1505. with connection.schema_editor() as editor:
  1506. editor.alter_field(AuthorWithIndexedName, old_field, new_field, strict=True)
  1507. new_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table)
  1508. self.assertNotIn(db_index_name, new_constraints)
  1509. # The index from Meta.indexes is still in the database.
  1510. self.assertIn(author_index_name, new_constraints)
  1511. # Drop the index
  1512. with connection.schema_editor() as editor:
  1513. editor.remove_index(AuthorWithIndexedName, index)
  1514. finally:
  1515. AuthorWithIndexedName._meta.indexes = []
  1516. def test_order_index(self):
  1517. """
  1518. Indexes defined with ordering (ASC/DESC) defined on column
  1519. """
  1520. with connection.schema_editor() as editor:
  1521. editor.create_model(Author)
  1522. # The table doesn't have an index
  1523. self.assertNotIn('title', self.get_indexes(Author._meta.db_table))
  1524. index_name = 'author_name_idx'
  1525. # Add the index
  1526. index = Index(fields=['name', '-weight'], name=index_name)
  1527. with connection.schema_editor() as editor:
  1528. editor.add_index(Author, index)
  1529. if connection.features.supports_index_column_ordering:
  1530. if connection.features.uppercases_column_names:
  1531. index_name = index_name.upper()
  1532. self.assertIndexOrder(Author._meta.db_table, index_name, ['ASC', 'DESC'])
  1533. # Drop the index
  1534. with connection.schema_editor() as editor:
  1535. editor.remove_index(Author, index)
  1536. def test_indexes(self):
  1537. """
  1538. Tests creation/altering of indexes
  1539. """
  1540. # Create the table
  1541. with connection.schema_editor() as editor:
  1542. editor.create_model(Author)
  1543. editor.create_model(Book)
  1544. # Ensure the table is there and has the right index
  1545. self.assertIn(
  1546. "title",
  1547. self.get_indexes(Book._meta.db_table),
  1548. )
  1549. # Alter to remove the index
  1550. old_field = Book._meta.get_field("title")
  1551. new_field = CharField(max_length=100, db_index=False)
  1552. new_field.set_attributes_from_name("title")
  1553. with connection.schema_editor() as editor:
  1554. editor.alter_field(Book, old_field, new_field, strict=True)
  1555. # Ensure the table is there and has no index
  1556. self.assertNotIn(
  1557. "title",
  1558. self.get_indexes(Book._meta.db_table),
  1559. )
  1560. # Alter to re-add the index
  1561. new_field2 = Book._meta.get_field("title")
  1562. with connection.schema_editor() as editor:
  1563. editor.alter_field(Book, new_field, new_field2, strict=True)
  1564. # Ensure the table is there and has the index again
  1565. self.assertIn(
  1566. "title",
  1567. self.get_indexes(Book._meta.db_table),
  1568. )
  1569. # Add a unique column, verify that creates an implicit index
  1570. new_field3 = BookWithSlug._meta.get_field("slug")
  1571. with connection.schema_editor() as editor:
  1572. editor.add_field(Book, new_field3)
  1573. self.assertIn(
  1574. "slug",
  1575. self.get_indexes(Book._meta.db_table),
  1576. )
  1577. # Remove the unique, check the index goes with it
  1578. new_field4 = CharField(max_length=20, unique=False)
  1579. new_field4.set_attributes_from_name("slug")
  1580. with connection.schema_editor() as editor:
  1581. editor.alter_field(BookWithSlug, new_field3, new_field4, strict=True)
  1582. self.assertNotIn(
  1583. "slug",
  1584. self.get_indexes(Book._meta.db_table),
  1585. )
  1586. def test_text_field_with_db_index(self):
  1587. with connection.schema_editor() as editor:
  1588. editor.create_model(AuthorTextFieldWithIndex)
  1589. # The text_field index is present if the database supports it.
  1590. assertion = self.assertIn if connection.features.supports_index_on_text_field else self.assertNotIn
  1591. assertion('text_field', self.get_indexes(AuthorTextFieldWithIndex._meta.db_table))
  1592. def test_primary_key(self):
  1593. """
  1594. Tests altering of the primary key
  1595. """
  1596. # Create the table
  1597. with connection.schema_editor() as editor:
  1598. editor.create_model(Tag)
  1599. # Ensure the table is there and has the right PK
  1600. self.assertEqual(self.get_primary_key(Tag._meta.db_table), 'id')
  1601. # Alter to change the PK
  1602. id_field = Tag._meta.get_field("id")
  1603. old_field = Tag._meta.get_field("slug")
  1604. new_field = SlugField(primary_key=True)
  1605. new_field.set_attributes_from_name("slug")
  1606. new_field.model = Tag
  1607. with connection.schema_editor() as editor:
  1608. editor.remove_field(Tag, id_field)
  1609. editor.alter_field(Tag, old_field, new_field)
  1610. # Ensure the PK changed
  1611. self.assertNotIn(
  1612. 'id',
  1613. self.get_indexes(Tag._meta.db_table),
  1614. )
  1615. self.assertEqual(self.get_primary_key(Tag._meta.db_table), 'slug')
  1616. def test_context_manager_exit(self):
  1617. """
  1618. Ensures transaction is correctly closed when an error occurs
  1619. inside a SchemaEditor context.
  1620. """
  1621. class SomeError(Exception):
  1622. pass
  1623. try:
  1624. with connection.schema_editor():
  1625. raise SomeError
  1626. except SomeError:
  1627. self.assertFalse(connection.in_atomic_block)
  1628. @skipIfDBFeature('can_rollback_ddl')
  1629. def test_unsupported_transactional_ddl_disallowed(self):
  1630. message = (
  1631. "Executing DDL statements while in a transaction on databases "
  1632. "that can't perform a rollback is prohibited."
  1633. )
  1634. with atomic(), connection.schema_editor() as editor:
  1635. with self.assertRaisesMessage(TransactionManagementError, message):
  1636. editor.execute(editor.sql_create_table % {'table': 'foo', 'definition': ''})
  1637. @skipUnlessDBFeature('supports_foreign_keys')
  1638. def test_foreign_key_index_long_names_regression(self):
  1639. """
  1640. Regression test for #21497.
  1641. Only affects databases that supports foreign keys.
  1642. """
  1643. # Create the table
  1644. with connection.schema_editor() as editor:
  1645. editor.create_model(AuthorWithEvenLongerName)
  1646. editor.create_model(BookWithLongName)
  1647. # Find the properly shortened column name
  1648. column_name = connection.ops.quote_name("author_foreign_key_with_really_long_field_name_id")
  1649. column_name = column_name[1:-1].lower() # unquote, and, for Oracle, un-upcase
  1650. # Ensure the table is there and has an index on the column
  1651. self.assertIn(
  1652. column_name,
  1653. self.get_indexes(BookWithLongName._meta.db_table),
  1654. )
  1655. @skipUnlessDBFeature('supports_foreign_keys')
  1656. def test_add_foreign_key_long_names(self):
  1657. """
  1658. Regression test for #23009.
  1659. Only affects databases that supports foreign keys.
  1660. """
  1661. # Create the initial tables
  1662. with connection.schema_editor() as editor:
  1663. editor.create_model(AuthorWithEvenLongerName)
  1664. editor.create_model(BookWithLongName)
  1665. # Add a second FK, this would fail due to long ref name before the fix
  1666. new_field = ForeignKey(AuthorWithEvenLongerName, CASCADE, related_name="something")
  1667. new_field.set_attributes_from_name("author_other_really_long_named_i_mean_so_long_fk")
  1668. with connection.schema_editor() as editor:
  1669. editor.add_field(BookWithLongName, new_field)
  1670. def test_add_foreign_object(self):
  1671. with connection.schema_editor() as editor:
  1672. editor.create_model(BookForeignObj)
  1673. new_field = ForeignObject(Author, on_delete=CASCADE, from_fields=['author_id'], to_fields=['id'])
  1674. new_field.set_attributes_from_name('author')
  1675. with connection.schema_editor() as editor:
  1676. editor.add_field(BookForeignObj, new_field)
  1677. def test_creation_deletion_reserved_names(self):
  1678. """
  1679. Tries creating a model's table, and then deleting it when it has a
  1680. SQL reserved name.
  1681. """
  1682. # Create the table
  1683. with connection.schema_editor() as editor:
  1684. try:
  1685. editor.create_model(Thing)
  1686. except OperationalError as e:
  1687. self.fail("Errors when applying initial migration for a model "
  1688. "with a table named after an SQL reserved word: %s" % e)
  1689. # The table is there
  1690. list(Thing.objects.all())
  1691. # Clean up that table
  1692. with connection.schema_editor() as editor:
  1693. editor.delete_model(Thing)
  1694. # The table is gone
  1695. with self.assertRaises(DatabaseError):
  1696. list(Thing.objects.all())
  1697. def test_remove_constraints_capital_letters(self):
  1698. """
  1699. #23065 - Constraint names must be quoted if they contain capital letters.
  1700. """
  1701. def get_field(*args, field_class=IntegerField, **kwargs):
  1702. kwargs['db_column'] = "CamelCase"
  1703. field = field_class(*args, **kwargs)
  1704. field.set_attributes_from_name("CamelCase")
  1705. return field
  1706. model = Author
  1707. field = get_field()
  1708. table = model._meta.db_table
  1709. column = field.column
  1710. with connection.schema_editor() as editor:
  1711. editor.create_model(model)
  1712. editor.add_field(model, field)
  1713. constraint_name = "CamelCaseIndex"
  1714. editor.execute(
  1715. editor.sql_create_index % {
  1716. "table": editor.quote_name(table),
  1717. "name": editor.quote_name(constraint_name),
  1718. "using": "",
  1719. "columns": editor.quote_name(column),
  1720. "extra": "",
  1721. }
  1722. )
  1723. if connection.features.uppercases_column_names:
  1724. constraint_name = constraint_name.upper()
  1725. self.assertIn(constraint_name, self.get_constraints(model._meta.db_table))
  1726. editor.alter_field(model, get_field(db_index=True), field, strict=True)
  1727. self.assertNotIn(constraint_name, self.get_constraints(model._meta.db_table))
  1728. constraint_name = "CamelCaseUniqConstraint"
  1729. editor.execute(
  1730. editor.sql_create_unique % {
  1731. "table": editor.quote_name(table),
  1732. "name": editor.quote_name(constraint_name),
  1733. "columns": editor.quote_name(field.column),
  1734. }
  1735. )
  1736. if connection.features.uppercases_column_names:
  1737. constraint_name = constraint_name.upper()
  1738. self.assertIn(constraint_name, self.get_constraints(model._meta.db_table))
  1739. editor.alter_field(model, get_field(unique=True), field, strict=True)
  1740. self.assertNotIn(constraint_name, self.get_constraints(model._meta.db_table))
  1741. if connection.features.supports_foreign_keys:
  1742. constraint_name = "CamelCaseFKConstraint"
  1743. editor.execute(
  1744. editor.sql_create_fk % {
  1745. "table": editor.quote_name(table),
  1746. "name": editor.quote_name(constraint_name),
  1747. "column": editor.quote_name(column),
  1748. "to_table": editor.quote_name(table),
  1749. "to_column": editor.quote_name(model._meta.auto_field.column),
  1750. "deferrable": connection.ops.deferrable_sql(),
  1751. }
  1752. )
  1753. if connection.features.uppercases_column_names:
  1754. constraint_name = constraint_name.upper()
  1755. self.assertIn(constraint_name, self.get_constraints(model._meta.db_table))
  1756. editor.alter_field(model, get_field(Author, CASCADE, field_class=ForeignKey), field, strict=True)
  1757. self.assertNotIn(constraint_name, self.get_constraints(model._meta.db_table))
  1758. def test_add_field_use_effective_default(self):
  1759. """
  1760. #23987 - effective_default() should be used as the field default when
  1761. adding a new field.
  1762. """
  1763. # Create the table
  1764. with connection.schema_editor() as editor:
  1765. editor.create_model(Author)
  1766. # Ensure there's no surname field
  1767. columns = self.column_classes(Author)
  1768. self.assertNotIn("surname", columns)
  1769. # Create a row
  1770. Author.objects.create(name='Anonymous1')
  1771. # Add new CharField to ensure default will be used from effective_default
  1772. new_field = CharField(max_length=15, blank=True)
  1773. new_field.set_attributes_from_name("surname")
  1774. with connection.schema_editor() as editor:
  1775. editor.add_field(Author, new_field)
  1776. # Ensure field was added with the right default
  1777. with connection.cursor() as cursor:
  1778. cursor.execute("SELECT surname FROM schema_author;")
  1779. item = cursor.fetchall()[0]
  1780. self.assertEqual(item[0], None if connection.features.interprets_empty_strings_as_nulls else '')
  1781. def test_add_field_default_dropped(self):
  1782. # Create the table
  1783. with connection.schema_editor() as editor:
  1784. editor.create_model(Author)
  1785. # Ensure there's no surname field
  1786. columns = self.column_classes(Author)
  1787. self.assertNotIn("surname", columns)
  1788. # Create a row
  1789. Author.objects.create(name='Anonymous1')
  1790. # Add new CharField with a default
  1791. new_field = CharField(max_length=15, blank=True, default='surname default')
  1792. new_field.set_attributes_from_name("surname")
  1793. with connection.schema_editor() as editor:
  1794. editor.add_field(Author, new_field)
  1795. # Ensure field was added with the right default
  1796. with connection.cursor() as cursor:
  1797. cursor.execute("SELECT surname FROM schema_author;")
  1798. item = cursor.fetchall()[0]
  1799. self.assertEqual(item[0], 'surname default')
  1800. # And that the default is no longer set in the database.
  1801. field = next(
  1802. f for f in connection.introspection.get_table_description(cursor, "schema_author")
  1803. if f.name == "surname"
  1804. )
  1805. if connection.features.can_introspect_default:
  1806. self.assertIsNone(field.default)
  1807. def test_alter_field_default_dropped(self):
  1808. # Create the table
  1809. with connection.schema_editor() as editor:
  1810. editor.create_model(Author)
  1811. # Create a row
  1812. Author.objects.create(name='Anonymous1')
  1813. self.assertIsNone(Author.objects.get().height)
  1814. old_field = Author._meta.get_field('height')
  1815. # The default from the new field is used in updating existing rows.
  1816. new_field = IntegerField(blank=True, default=42)
  1817. new_field.set_attributes_from_name('height')
  1818. with connection.schema_editor() as editor:
  1819. editor.alter_field(Author, old_field, new_field, strict=True)
  1820. self.assertEqual(Author.objects.get().height, 42)
  1821. # The database default should be removed.
  1822. with connection.cursor() as cursor:
  1823. field = next(
  1824. f for f in connection.introspection.get_table_description(cursor, "schema_author")
  1825. if f.name == "height"
  1826. )
  1827. if connection.features.can_introspect_default:
  1828. self.assertIsNone(field.default)
  1829. @unittest.skipIf(connection.vendor == 'sqlite', 'SQLite naively remakes the table on field alteration.')
  1830. def test_alter_field_default_doesnt_perfom_queries(self):
  1831. """
  1832. No queries are performed if a field default changes and the field's
  1833. not changing from null to non-null.
  1834. """
  1835. with connection.schema_editor() as editor:
  1836. editor.create_model(AuthorWithDefaultHeight)
  1837. old_field = AuthorWithDefaultHeight._meta.get_field('height')
  1838. new_default = old_field.default * 2
  1839. new_field = PositiveIntegerField(null=True, blank=True, default=new_default)
  1840. new_field.set_attributes_from_name('height')
  1841. with connection.schema_editor() as editor, self.assertNumQueries(0):
  1842. editor.alter_field(AuthorWithDefaultHeight, old_field, new_field, strict=True)
  1843. def test_add_textfield_unhashable_default(self):
  1844. # Create the table
  1845. with connection.schema_editor() as editor:
  1846. editor.create_model(Author)
  1847. # Create a row
  1848. Author.objects.create(name='Anonymous1')
  1849. # Create a field that has an unhashable default
  1850. new_field = TextField(default={})
  1851. new_field.set_attributes_from_name("info")
  1852. with connection.schema_editor() as editor:
  1853. editor.add_field(Author, new_field)
  1854. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  1855. def test_add_indexed_charfield(self):
  1856. field = CharField(max_length=255, db_index=True)
  1857. field.set_attributes_from_name('nom_de_plume')
  1858. with connection.schema_editor() as editor:
  1859. editor.create_model(Author)
  1860. editor.add_field(Author, field)
  1861. # Should create two indexes; one for like operator.
  1862. self.assertEqual(
  1863. self.get_constraints_for_column(Author, 'nom_de_plume'),
  1864. ['schema_author_nom_de_plume_7570a851', 'schema_author_nom_de_plume_7570a851_like'],
  1865. )
  1866. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  1867. def test_add_unique_charfield(self):
  1868. field = CharField(max_length=255, unique=True)
  1869. field.set_attributes_from_name('nom_de_plume')
  1870. with connection.schema_editor() as editor:
  1871. editor.create_model(Author)
  1872. editor.add_field(Author, field)
  1873. # Should create two indexes; one for like operator.
  1874. self.assertEqual(
  1875. self.get_constraints_for_column(Author, 'nom_de_plume'),
  1876. ['schema_author_nom_de_plume_7570a851_like', 'schema_author_nom_de_plume_key']
  1877. )
  1878. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  1879. def test_alter_field_add_index_to_charfield(self):
  1880. # Create the table and verify no initial indexes.
  1881. with connection.schema_editor() as editor:
  1882. editor.create_model(Author)
  1883. self.assertEqual(self.get_constraints_for_column(Author, 'name'), [])
  1884. # Alter to add db_index=True and create 2 indexes.
  1885. old_field = Author._meta.get_field('name')
  1886. new_field = CharField(max_length=255, db_index=True)
  1887. new_field.set_attributes_from_name('name')
  1888. with connection.schema_editor() as editor:
  1889. editor.alter_field(Author, old_field, new_field, strict=True)
  1890. self.assertEqual(
  1891. self.get_constraints_for_column(Author, 'name'),
  1892. ['schema_author_name_1fbc5617', 'schema_author_name_1fbc5617_like']
  1893. )
  1894. # Remove db_index=True to drop both indexes.
  1895. with connection.schema_editor() as editor:
  1896. editor.alter_field(Author, new_field, old_field, strict=True)
  1897. self.assertEqual(self.get_constraints_for_column(Author, 'name'), [])
  1898. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  1899. def test_alter_field_add_unique_to_charfield(self):
  1900. # Create the table and verify no initial indexes.
  1901. with connection.schema_editor() as editor:
  1902. editor.create_model(Author)
  1903. self.assertEqual(self.get_constraints_for_column(Author, 'name'), [])
  1904. # Alter to add unique=True and create 2 indexes.
  1905. old_field = Author._meta.get_field('name')
  1906. new_field = CharField(max_length=255, unique=True)
  1907. new_field.set_attributes_from_name('name')
  1908. with connection.schema_editor() as editor:
  1909. editor.alter_field(Author, old_field, new_field, strict=True)
  1910. self.assertEqual(
  1911. self.get_constraints_for_column(Author, 'name'),
  1912. ['schema_author_name_1fbc5617_like', 'schema_author_name_1fbc5617_uniq']
  1913. )
  1914. # Remove unique=True to drop both indexes.
  1915. with connection.schema_editor() as editor:
  1916. editor.alter_field(Author, new_field, old_field, strict=True)
  1917. self.assertEqual(self.get_constraints_for_column(Author, 'name'), [])
  1918. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  1919. def test_alter_field_add_index_to_textfield(self):
  1920. # Create the table and verify no initial indexes.
  1921. with connection.schema_editor() as editor:
  1922. editor.create_model(Note)
  1923. self.assertEqual(self.get_constraints_for_column(Note, 'info'), [])
  1924. # Alter to add db_index=True and create 2 indexes.
  1925. old_field = Note._meta.get_field('info')
  1926. new_field = TextField(db_index=True)
  1927. new_field.set_attributes_from_name('info')
  1928. with connection.schema_editor() as editor:
  1929. editor.alter_field(Note, old_field, new_field, strict=True)
  1930. self.assertEqual(
  1931. self.get_constraints_for_column(Note, 'info'),
  1932. ['schema_note_info_4b0ea695', 'schema_note_info_4b0ea695_like']
  1933. )
  1934. # Remove db_index=True to drop both indexes.
  1935. with connection.schema_editor() as editor:
  1936. editor.alter_field(Note, new_field, old_field, strict=True)
  1937. self.assertEqual(self.get_constraints_for_column(Note, 'info'), [])
  1938. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  1939. def test_alter_field_add_unique_to_charfield_with_db_index(self):
  1940. # Create the table and verify initial indexes.
  1941. with connection.schema_editor() as editor:
  1942. editor.create_model(BookWithoutAuthor)
  1943. self.assertEqual(
  1944. self.get_constraints_for_column(BookWithoutAuthor, 'title'),
  1945. ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like']
  1946. )
  1947. # Alter to add unique=True (should replace the index)
  1948. old_field = BookWithoutAuthor._meta.get_field('title')
  1949. new_field = CharField(max_length=100, db_index=True, unique=True)
  1950. new_field.set_attributes_from_name('title')
  1951. with connection.schema_editor() as editor:
  1952. editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True)
  1953. self.assertEqual(
  1954. self.get_constraints_for_column(BookWithoutAuthor, 'title'),
  1955. ['schema_book_title_2dfb2dff_like', 'schema_book_title_2dfb2dff_uniq']
  1956. )
  1957. # Alter to remove unique=True (should drop unique index)
  1958. new_field2 = CharField(max_length=100, db_index=True)
  1959. new_field2.set_attributes_from_name('title')
  1960. with connection.schema_editor() as editor:
  1961. editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True)
  1962. self.assertEqual(
  1963. self.get_constraints_for_column(BookWithoutAuthor, 'title'),
  1964. ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like']
  1965. )
  1966. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  1967. def test_alter_field_remove_unique_and_db_index_from_charfield(self):
  1968. # Create the table and verify initial indexes.
  1969. with connection.schema_editor() as editor:
  1970. editor.create_model(BookWithoutAuthor)
  1971. self.assertEqual(
  1972. self.get_constraints_for_column(BookWithoutAuthor, 'title'),
  1973. ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like']
  1974. )
  1975. # Alter to add unique=True (should replace the index)
  1976. old_field = BookWithoutAuthor._meta.get_field('title')
  1977. new_field = CharField(max_length=100, db_index=True, unique=True)
  1978. new_field.set_attributes_from_name('title')
  1979. with connection.schema_editor() as editor:
  1980. editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True)
  1981. self.assertEqual(
  1982. self.get_constraints_for_column(BookWithoutAuthor, 'title'),
  1983. ['schema_book_title_2dfb2dff_like', 'schema_book_title_2dfb2dff_uniq']
  1984. )
  1985. # Alter to remove both unique=True and db_index=True (should drop all indexes)
  1986. new_field2 = CharField(max_length=100)
  1987. new_field2.set_attributes_from_name('title')
  1988. with connection.schema_editor() as editor:
  1989. editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True)
  1990. self.assertEqual(self.get_constraints_for_column(BookWithoutAuthor, 'title'), [])
  1991. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  1992. def test_alter_field_swap_unique_and_db_index_with_charfield(self):
  1993. # Create the table and verify initial indexes.
  1994. with connection.schema_editor() as editor:
  1995. editor.create_model(BookWithoutAuthor)
  1996. self.assertEqual(
  1997. self.get_constraints_for_column(BookWithoutAuthor, 'title'),
  1998. ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like']
  1999. )
  2000. # Alter to set unique=True and remove db_index=True (should replace the index)
  2001. old_field = BookWithoutAuthor._meta.get_field('title')
  2002. new_field = CharField(max_length=100, unique=True)
  2003. new_field.set_attributes_from_name('title')
  2004. with connection.schema_editor() as editor:
  2005. editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True)
  2006. self.assertEqual(
  2007. self.get_constraints_for_column(BookWithoutAuthor, 'title'),
  2008. ['schema_book_title_2dfb2dff_like', 'schema_book_title_2dfb2dff_uniq']
  2009. )
  2010. # Alter to set db_index=True and remove unique=True (should restore index)
  2011. new_field2 = CharField(max_length=100, db_index=True)
  2012. new_field2.set_attributes_from_name('title')
  2013. with connection.schema_editor() as editor:
  2014. editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True)
  2015. self.assertEqual(
  2016. self.get_constraints_for_column(BookWithoutAuthor, 'title'),
  2017. ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like']
  2018. )
  2019. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific")
  2020. def test_alter_field_add_db_index_to_charfield_with_unique(self):
  2021. # Create the table and verify initial indexes.
  2022. with connection.schema_editor() as editor:
  2023. editor.create_model(Tag)
  2024. self.assertEqual(
  2025. self.get_constraints_for_column(Tag, 'slug'),
  2026. ['schema_tag_slug_2c418ba3_like', 'schema_tag_slug_key']
  2027. )
  2028. # Alter to add db_index=True
  2029. old_field = Tag._meta.get_field('slug')
  2030. new_field = SlugField(db_index=True, unique=True)
  2031. new_field.set_attributes_from_name('slug')
  2032. with connection.schema_editor() as editor:
  2033. editor.alter_field(Tag, old_field, new_field, strict=True)
  2034. self.assertEqual(
  2035. self.get_constraints_for_column(Tag, 'slug'),
  2036. ['schema_tag_slug_2c418ba3_like', 'schema_tag_slug_key']
  2037. )
  2038. # Alter to remove db_index=True
  2039. new_field2 = SlugField(unique=True)
  2040. new_field2.set_attributes_from_name('slug')
  2041. with connection.schema_editor() as editor:
  2042. editor.alter_field(Tag, new_field, new_field2, strict=True)
  2043. self.assertEqual(
  2044. self.get_constraints_for_column(Tag, 'slug'),
  2045. ['schema_tag_slug_2c418ba3_like', 'schema_tag_slug_key']
  2046. )
  2047. def test_alter_field_add_index_to_integerfield(self):
  2048. # Create the table and verify no initial indexes.
  2049. with connection.schema_editor() as editor:
  2050. editor.create_model(Author)
  2051. self.assertEqual(self.get_constraints_for_column(Author, 'weight'), [])
  2052. # Alter to add db_index=True and create index.
  2053. old_field = Author._meta.get_field('weight')
  2054. new_field = IntegerField(null=True, db_index=True)
  2055. new_field.set_attributes_from_name('weight')
  2056. with connection.schema_editor() as editor:
  2057. editor.alter_field(Author, old_field, new_field, strict=True)
  2058. expected = 'schema_author_weight_587740f9'
  2059. if connection.features.uppercases_column_names:
  2060. expected = expected.upper()
  2061. self.assertEqual(self.get_constraints_for_column(Author, 'weight'), [expected])
  2062. # Remove db_index=True to drop index.
  2063. with connection.schema_editor() as editor:
  2064. editor.alter_field(Author, new_field, old_field, strict=True)
  2065. self.assertEqual(self.get_constraints_for_column(Author, 'weight'), [])
  2066. def test_alter_pk_with_self_referential_field(self):
  2067. """
  2068. Changing the primary key field name of a model with a self-referential
  2069. foreign key (#26384).
  2070. """
  2071. if connection.vendor == 'mysql' and connection.mysql_version < (5, 6, 6):
  2072. self.skipTest('Skip known bug renaming primary keys on older MySQL versions (#24995).')
  2073. with connection.schema_editor() as editor:
  2074. editor.create_model(Node)
  2075. old_field = Node._meta.get_field('node_id')
  2076. new_field = AutoField(primary_key=True)
  2077. new_field.set_attributes_from_name('id')
  2078. with connection.schema_editor() as editor:
  2079. editor.alter_field(Node, old_field, new_field, strict=True)
  2080. @mock.patch('django.db.backends.base.schema.datetime')
  2081. @mock.patch('django.db.backends.base.schema.timezone')
  2082. def test_add_datefield_and_datetimefield_use_effective_default(self, mocked_datetime, mocked_tz):
  2083. """
  2084. effective_default() should be used for DateField, DateTimeField, and
  2085. TimeField if auto_now or auto_add_now is set (#25005).
  2086. """
  2087. now = datetime.datetime(month=1, day=1, year=2000, hour=1, minute=1)
  2088. now_tz = datetime.datetime(month=1, day=1, year=2000, hour=1, minute=1, tzinfo=timezone.utc)
  2089. mocked_datetime.now = mock.MagicMock(return_value=now)
  2090. mocked_tz.now = mock.MagicMock(return_value=now_tz)
  2091. # Create the table
  2092. with connection.schema_editor() as editor:
  2093. editor.create_model(Author)
  2094. # Check auto_now/auto_now_add attributes are not defined
  2095. columns = self.column_classes(Author)
  2096. self.assertNotIn("dob_auto_now", columns)
  2097. self.assertNotIn("dob_auto_now_add", columns)
  2098. self.assertNotIn("dtob_auto_now", columns)
  2099. self.assertNotIn("dtob_auto_now_add", columns)
  2100. self.assertNotIn("tob_auto_now", columns)
  2101. self.assertNotIn("tob_auto_now_add", columns)
  2102. # Create a row
  2103. Author.objects.create(name='Anonymous1')
  2104. # Ensure fields were added with the correct defaults
  2105. dob_auto_now = DateField(auto_now=True)
  2106. dob_auto_now.set_attributes_from_name('dob_auto_now')
  2107. self.check_added_field_default(
  2108. editor, Author, dob_auto_now, 'dob_auto_now', now.date(),
  2109. cast_function=lambda x: x.date(),
  2110. )
  2111. dob_auto_now_add = DateField(auto_now_add=True)
  2112. dob_auto_now_add.set_attributes_from_name('dob_auto_now_add')
  2113. self.check_added_field_default(
  2114. editor, Author, dob_auto_now_add, 'dob_auto_now_add', now.date(),
  2115. cast_function=lambda x: x.date(),
  2116. )
  2117. dtob_auto_now = DateTimeField(auto_now=True)
  2118. dtob_auto_now.set_attributes_from_name('dtob_auto_now')
  2119. self.check_added_field_default(
  2120. editor, Author, dtob_auto_now, 'dtob_auto_now', now,
  2121. )
  2122. dt_tm_of_birth_auto_now_add = DateTimeField(auto_now_add=True)
  2123. dt_tm_of_birth_auto_now_add.set_attributes_from_name('dtob_auto_now_add')
  2124. self.check_added_field_default(
  2125. editor, Author, dt_tm_of_birth_auto_now_add, 'dtob_auto_now_add', now,
  2126. )
  2127. tob_auto_now = TimeField(auto_now=True)
  2128. tob_auto_now.set_attributes_from_name('tob_auto_now')
  2129. self.check_added_field_default(
  2130. editor, Author, tob_auto_now, 'tob_auto_now', now.time(),
  2131. cast_function=lambda x: x.time(),
  2132. )
  2133. tob_auto_now_add = TimeField(auto_now_add=True)
  2134. tob_auto_now_add.set_attributes_from_name('tob_auto_now_add')
  2135. self.check_added_field_default(
  2136. editor, Author, tob_auto_now_add, 'tob_auto_now_add', now.time(),
  2137. cast_function=lambda x: x.time(),
  2138. )
  2139. @unittest.skipUnless(connection.vendor == 'oracle', 'Oracle specific db_table syntax')
  2140. def test_creation_with_db_table_double_quotes(self):
  2141. oracle_user = connection.creation._test_database_user()
  2142. class Student(Model):
  2143. name = CharField(max_length=30)
  2144. class Meta:
  2145. app_label = 'schema'
  2146. apps = new_apps
  2147. db_table = '"%s"."DJANGO_STUDENT_TABLE"' % oracle_user
  2148. class Document(Model):
  2149. name = CharField(max_length=30)
  2150. students = ManyToManyField(Student)
  2151. class Meta:
  2152. app_label = 'schema'
  2153. apps = new_apps
  2154. db_table = '"%s"."DJANGO_DOCUMENT_TABLE"' % oracle_user
  2155. self.local_models = [Student, Document]
  2156. with connection.schema_editor() as editor:
  2157. editor.create_model(Student)
  2158. editor.create_model(Document)
  2159. doc = Document.objects.create(name='Test Name')
  2160. student = Student.objects.create(name='Some man')
  2161. doc.students.add(student)