tests.py 130 KB

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