schema.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. from django.db.backends.base.schema import BaseDatabaseSchemaEditor
  2. from django.db.backends.ddl_references import IndexColumns
  3. from django.db.backends.postgresql.psycopg_any import sql
  4. from django.db.backends.utils import strip_quotes
  5. class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
  6. # Setting all constraints to IMMEDIATE to allow changing data in the same
  7. # transaction.
  8. sql_update_with_default = (
  9. "UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL"
  10. "; SET CONSTRAINTS ALL IMMEDIATE"
  11. )
  12. sql_alter_sequence_type = "ALTER SEQUENCE IF EXISTS %(sequence)s AS %(type)s"
  13. sql_delete_sequence = "DROP SEQUENCE IF EXISTS %(sequence)s CASCADE"
  14. sql_create_index = (
  15. "CREATE INDEX %(name)s ON %(table)s%(using)s "
  16. "(%(columns)s)%(include)s%(extra)s%(condition)s"
  17. )
  18. sql_create_index_concurrently = (
  19. "CREATE INDEX CONCURRENTLY %(name)s ON %(table)s%(using)s "
  20. "(%(columns)s)%(include)s%(extra)s%(condition)s"
  21. )
  22. sql_delete_index = "DROP INDEX IF EXISTS %(name)s"
  23. sql_delete_index_concurrently = "DROP INDEX CONCURRENTLY IF EXISTS %(name)s"
  24. # Setting the constraint to IMMEDIATE to allow changing data in the same
  25. # transaction.
  26. sql_create_column_inline_fk = (
  27. "CONSTRAINT %(name)s REFERENCES %(to_table)s(%(to_column)s)%(on_delete_db)s"
  28. "%(deferrable)s; SET CONSTRAINTS %(namespace)s%(name)s IMMEDIATE"
  29. )
  30. # Setting the constraint to IMMEDIATE runs any deferred checks to allow
  31. # dropping it in the same transaction.
  32. sql_delete_fk = (
  33. "SET CONSTRAINTS %(name)s IMMEDIATE; "
  34. "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
  35. )
  36. sql_delete_procedure = "DROP FUNCTION %(procedure)s(%(param_types)s)"
  37. def execute(self, sql, params=()):
  38. # Merge the query client-side, as PostgreSQL won't do it server-side.
  39. if params is None:
  40. return super().execute(sql, params)
  41. sql = self.connection.ops.compose_sql(str(sql), params)
  42. # Don't let the superclass touch anything.
  43. return super().execute(sql, None)
  44. sql_add_identity = (
  45. "ALTER TABLE %(table)s ALTER COLUMN %(column)s ADD "
  46. "GENERATED BY DEFAULT AS IDENTITY"
  47. )
  48. sql_drop_indentity = (
  49. "ALTER TABLE %(table)s ALTER COLUMN %(column)s DROP IDENTITY IF EXISTS"
  50. )
  51. def quote_value(self, value):
  52. return sql.quote(value, self.connection.connection)
  53. def _field_indexes_sql(self, model, field):
  54. output = super()._field_indexes_sql(model, field)
  55. like_index_statement = self._create_like_index_sql(model, field)
  56. if like_index_statement is not None:
  57. output.append(like_index_statement)
  58. return output
  59. def _field_data_type(self, field):
  60. if field.is_relation:
  61. return field.rel_db_type(self.connection)
  62. return self.connection.data_types.get(
  63. field.get_internal_type(),
  64. field.db_type(self.connection),
  65. )
  66. def _field_base_data_types(self, field):
  67. # Yield base data types for array fields.
  68. if field.base_field.get_internal_type() == "ArrayField":
  69. yield from self._field_base_data_types(field.base_field)
  70. else:
  71. yield self._field_data_type(field.base_field)
  72. def _create_like_index_sql(self, model, field):
  73. """
  74. Return the statement to create an index with varchar operator pattern
  75. when the column type is 'varchar' or 'text', otherwise return None.
  76. """
  77. db_type = field.db_type(connection=self.connection)
  78. if db_type is not None and (field.db_index or field.unique):
  79. # Fields with database column types of `varchar` and `text` need
  80. # a second index that specifies their operator class, which is
  81. # needed when performing correct LIKE queries outside the
  82. # C locale. See #12234.
  83. #
  84. # The same doesn't apply to array fields such as varchar[size]
  85. # and text[size], so skip them.
  86. if "[" in db_type:
  87. return None
  88. # Non-deterministic collations on Postgresql don't support indexes
  89. # for operator classes varchar_pattern_ops/text_pattern_ops.
  90. collation_name = getattr(field, "db_collation", None)
  91. if not collation_name and field.is_relation:
  92. collation_name = getattr(field.target_field, "db_collation", None)
  93. if collation_name and not self._is_collation_deterministic(collation_name):
  94. return None
  95. if db_type.startswith("varchar"):
  96. return self._create_index_sql(
  97. model,
  98. fields=[field],
  99. suffix="_like",
  100. opclasses=["varchar_pattern_ops"],
  101. )
  102. elif db_type.startswith("text"):
  103. return self._create_index_sql(
  104. model,
  105. fields=[field],
  106. suffix="_like",
  107. opclasses=["text_pattern_ops"],
  108. )
  109. return None
  110. def _using_sql(self, new_field, old_field):
  111. if new_field.generated:
  112. return ""
  113. using_sql = " USING %(column)s::%(type)s"
  114. new_internal_type = new_field.get_internal_type()
  115. old_internal_type = old_field.get_internal_type()
  116. if new_internal_type == "ArrayField" and new_internal_type == old_internal_type:
  117. # Compare base data types for array fields.
  118. if list(self._field_base_data_types(old_field)) != list(
  119. self._field_base_data_types(new_field)
  120. ):
  121. return using_sql
  122. elif self._field_data_type(old_field) != self._field_data_type(new_field):
  123. return using_sql
  124. return ""
  125. def _get_sequence_name(self, table, column):
  126. with self.connection.cursor() as cursor:
  127. for sequence in self.connection.introspection.get_sequences(cursor, table):
  128. if sequence["column"] == column:
  129. return sequence["name"]
  130. return None
  131. def _is_changing_type_of_indexed_text_column(self, old_field, old_type, new_type):
  132. return (old_field.db_index or old_field.unique) and (
  133. (old_type.startswith("varchar") and not new_type.startswith("varchar"))
  134. or (old_type.startswith("text") and not new_type.startswith("text"))
  135. or (old_type.startswith("citext") and not new_type.startswith("citext"))
  136. )
  137. def _alter_column_type_sql(
  138. self, model, old_field, new_field, new_type, old_collation, new_collation
  139. ):
  140. # Drop indexes on varchar/text/citext columns that are changing to a
  141. # different type.
  142. old_db_params = old_field.db_parameters(connection=self.connection)
  143. old_type = old_db_params["type"]
  144. if self._is_changing_type_of_indexed_text_column(old_field, old_type, new_type):
  145. index_name = self._create_index_name(
  146. model._meta.db_table, [old_field.column], suffix="_like"
  147. )
  148. self.execute(self._delete_index_sql(model, index_name))
  149. self.sql_alter_column_type = (
  150. "ALTER COLUMN %(column)s TYPE %(type)s%(collation)s"
  151. )
  152. # Cast when data type changed.
  153. if using_sql := self._using_sql(new_field, old_field):
  154. self.sql_alter_column_type += using_sql
  155. new_internal_type = new_field.get_internal_type()
  156. old_internal_type = old_field.get_internal_type()
  157. # Make ALTER TYPE with IDENTITY make sense.
  158. table = strip_quotes(model._meta.db_table)
  159. auto_field_types = {
  160. "AutoField",
  161. "BigAutoField",
  162. "SmallAutoField",
  163. }
  164. old_is_auto = old_internal_type in auto_field_types
  165. new_is_auto = new_internal_type in auto_field_types
  166. if new_is_auto and not old_is_auto:
  167. column = strip_quotes(new_field.column)
  168. return (
  169. (
  170. self.sql_alter_column_type
  171. % {
  172. "column": self.quote_name(column),
  173. "type": new_type,
  174. "collation": "",
  175. },
  176. [],
  177. ),
  178. [
  179. (
  180. self.sql_add_identity
  181. % {
  182. "table": self.quote_name(table),
  183. "column": self.quote_name(column),
  184. },
  185. [],
  186. ),
  187. ],
  188. )
  189. elif old_is_auto and not new_is_auto:
  190. # Drop IDENTITY if exists (pre-Django 4.1 serial columns don't have
  191. # it).
  192. self.execute(
  193. self.sql_drop_indentity
  194. % {
  195. "table": self.quote_name(table),
  196. "column": self.quote_name(strip_quotes(new_field.column)),
  197. }
  198. )
  199. column = strip_quotes(new_field.column)
  200. fragment, _ = super()._alter_column_type_sql(
  201. model, old_field, new_field, new_type, old_collation, new_collation
  202. )
  203. # Drop the sequence if exists (Django 4.1+ identity columns don't
  204. # have it).
  205. other_actions = []
  206. if sequence_name := self._get_sequence_name(table, column):
  207. other_actions = [
  208. (
  209. self.sql_delete_sequence
  210. % {
  211. "sequence": self.quote_name(sequence_name),
  212. },
  213. [],
  214. )
  215. ]
  216. return fragment, other_actions
  217. elif new_is_auto and old_is_auto and old_internal_type != new_internal_type:
  218. fragment, _ = super()._alter_column_type_sql(
  219. model, old_field, new_field, new_type, old_collation, new_collation
  220. )
  221. column = strip_quotes(new_field.column)
  222. db_types = {
  223. "AutoField": "integer",
  224. "BigAutoField": "bigint",
  225. "SmallAutoField": "smallint",
  226. }
  227. # Alter the sequence type if exists (Django 4.1+ identity columns
  228. # don't have it).
  229. other_actions = []
  230. if sequence_name := self._get_sequence_name(table, column):
  231. other_actions = [
  232. (
  233. self.sql_alter_sequence_type
  234. % {
  235. "sequence": self.quote_name(sequence_name),
  236. "type": db_types[new_internal_type],
  237. },
  238. [],
  239. ),
  240. ]
  241. return fragment, other_actions
  242. else:
  243. return super()._alter_column_type_sql(
  244. model, old_field, new_field, new_type, old_collation, new_collation
  245. )
  246. def _alter_field(
  247. self,
  248. model,
  249. old_field,
  250. new_field,
  251. old_type,
  252. new_type,
  253. old_db_params,
  254. new_db_params,
  255. strict=False,
  256. ):
  257. super()._alter_field(
  258. model,
  259. old_field,
  260. new_field,
  261. old_type,
  262. new_type,
  263. old_db_params,
  264. new_db_params,
  265. strict,
  266. )
  267. # Added an index? Create any PostgreSQL-specific indexes.
  268. if (
  269. (not (old_field.db_index or old_field.unique) and new_field.db_index)
  270. or (not old_field.unique and new_field.unique)
  271. or (
  272. self._is_changing_type_of_indexed_text_column(
  273. old_field, old_type, new_type
  274. )
  275. )
  276. ):
  277. like_index_statement = self._create_like_index_sql(model, new_field)
  278. if like_index_statement is not None:
  279. self.execute(like_index_statement)
  280. # Removed an index? Drop any PostgreSQL-specific indexes.
  281. if old_field.unique and not (new_field.db_index or new_field.unique):
  282. index_to_remove = self._create_index_name(
  283. model._meta.db_table, [old_field.column], suffix="_like"
  284. )
  285. self.execute(self._delete_index_sql(model, index_to_remove))
  286. def _index_columns(self, table, columns, col_suffixes, opclasses):
  287. if opclasses:
  288. return IndexColumns(
  289. table,
  290. columns,
  291. self.quote_name,
  292. col_suffixes=col_suffixes,
  293. opclasses=opclasses,
  294. )
  295. return super()._index_columns(table, columns, col_suffixes, opclasses)
  296. def add_index(self, model, index, concurrently=False):
  297. self.execute(
  298. index.create_sql(model, self, concurrently=concurrently), params=None
  299. )
  300. def remove_index(self, model, index, concurrently=False):
  301. self.execute(index.remove_sql(model, self, concurrently=concurrently))
  302. def _delete_index_sql(self, model, name, sql=None, concurrently=False):
  303. sql = sql or (
  304. self.sql_delete_index_concurrently
  305. if concurrently
  306. else self.sql_delete_index
  307. )
  308. return super()._delete_index_sql(model, name, sql)
  309. def _create_index_sql(
  310. self,
  311. model,
  312. *,
  313. fields=None,
  314. name=None,
  315. suffix="",
  316. using="",
  317. db_tablespace=None,
  318. col_suffixes=(),
  319. sql=None,
  320. opclasses=(),
  321. condition=None,
  322. concurrently=False,
  323. include=None,
  324. expressions=None,
  325. ):
  326. sql = sql or (
  327. self.sql_create_index
  328. if not concurrently
  329. else self.sql_create_index_concurrently
  330. )
  331. return super()._create_index_sql(
  332. model,
  333. fields=fields,
  334. name=name,
  335. suffix=suffix,
  336. using=using,
  337. db_tablespace=db_tablespace,
  338. col_suffixes=col_suffixes,
  339. sql=sql,
  340. opclasses=opclasses,
  341. condition=condition,
  342. include=include,
  343. expressions=expressions,
  344. )
  345. def _is_collation_deterministic(self, collation_name):
  346. with self.connection.cursor() as cursor:
  347. cursor.execute(
  348. """
  349. SELECT collisdeterministic
  350. FROM pg_collation
  351. WHERE collname = %s
  352. """,
  353. [collation_name],
  354. )
  355. row = cursor.fetchone()
  356. return row[0] if row else None