introspection.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. from collections import namedtuple
  2. from django.db.backends.base.introspection import BaseDatabaseIntrospection
  3. from django.db.backends.base.introspection import FieldInfo as BaseFieldInfo
  4. from django.db.backends.base.introspection import TableInfo as BaseTableInfo
  5. from django.db.backends.postgresql.base import psycopg_version
  6. from django.db.models import DB_CASCADE, DB_SET_DEFAULT, DB_SET_NULL, DO_NOTHING, Index
  7. FieldInfo = namedtuple("FieldInfo", [*BaseFieldInfo._fields, "is_autofield", "comment"])
  8. TableInfo = namedtuple("TableInfo", [*BaseTableInfo._fields, "comment"])
  9. class DatabaseIntrospection(BaseDatabaseIntrospection):
  10. # Maps type codes to Django Field types.
  11. data_types_reverse = {
  12. 16: "BooleanField",
  13. 17: "BinaryField",
  14. 20: "BigIntegerField",
  15. 21: "SmallIntegerField",
  16. 23: "IntegerField",
  17. 25: "TextField",
  18. 700: "FloatField",
  19. 701: "FloatField",
  20. 869: "GenericIPAddressField",
  21. 1042: "CharField", # blank-padded
  22. 1043: "CharField",
  23. 1082: "DateField",
  24. 1083: "TimeField",
  25. 1114: "DateTimeField",
  26. 1184: "DateTimeField",
  27. 1186: "DurationField",
  28. 1266: "TimeField",
  29. 1700: "DecimalField",
  30. 2950: "UUIDField",
  31. 3802: "JSONField",
  32. }
  33. # A hook for subclasses.
  34. index_default_access_method = "btree"
  35. ignored_tables = []
  36. on_delete_types = {
  37. "a": DO_NOTHING,
  38. "c": DB_CASCADE,
  39. "d": DB_SET_DEFAULT,
  40. "n": DB_SET_NULL,
  41. # DB_RESTRICT - "r" is not supported.
  42. }
  43. def get_field_type(self, data_type, description):
  44. field_type = super().get_field_type(data_type, description)
  45. if description.is_autofield or (
  46. # Required for pre-Django 4.1 serial columns.
  47. description.default
  48. and "nextval" in description.default
  49. ):
  50. if field_type == "IntegerField":
  51. return "AutoField"
  52. elif field_type == "BigIntegerField":
  53. return "BigAutoField"
  54. elif field_type == "SmallIntegerField":
  55. return "SmallAutoField"
  56. return field_type
  57. def get_table_list(self, cursor):
  58. """Return a list of table and view names in the current database."""
  59. cursor.execute("""
  60. SELECT
  61. c.relname,
  62. CASE
  63. WHEN c.relispartition THEN 'p'
  64. WHEN c.relkind IN ('m', 'v') THEN 'v'
  65. ELSE 't'
  66. END,
  67. obj_description(c.oid, 'pg_class')
  68. FROM pg_catalog.pg_class c
  69. LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
  70. WHERE c.relkind IN ('f', 'm', 'p', 'r', 'v')
  71. AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
  72. AND pg_catalog.pg_table_is_visible(c.oid)
  73. """)
  74. return [
  75. TableInfo(*row)
  76. for row in cursor.fetchall()
  77. if row[0] not in self.ignored_tables
  78. ]
  79. def get_table_description(self, cursor, table_name):
  80. """
  81. Return a description of the table with the DB-API cursor.description
  82. interface.
  83. """
  84. # Query the pg_catalog tables as cursor.description does not reliably
  85. # return the nullable property and information_schema.columns does not
  86. # contain details of materialized views.
  87. cursor.execute(
  88. """
  89. SELECT
  90. a.attname AS column_name,
  91. NOT (a.attnotnull OR (t.typtype = 'd' AND t.typnotnull)) AS is_nullable,
  92. pg_get_expr(ad.adbin, ad.adrelid) AS column_default,
  93. CASE WHEN collname = 'default' THEN NULL ELSE collname END AS collation,
  94. a.attidentity != '' AS is_autofield,
  95. col_description(a.attrelid, a.attnum) AS column_comment
  96. FROM pg_attribute a
  97. LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
  98. LEFT JOIN pg_collation co ON a.attcollation = co.oid
  99. JOIN pg_type t ON a.atttypid = t.oid
  100. JOIN pg_class c ON a.attrelid = c.oid
  101. JOIN pg_namespace n ON c.relnamespace = n.oid
  102. WHERE c.relkind IN ('f', 'm', 'p', 'r', 'v')
  103. AND c.relname = %s
  104. AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
  105. AND pg_catalog.pg_table_is_visible(c.oid)
  106. """,
  107. [table_name],
  108. )
  109. field_map = {line[0]: line[1:] for line in cursor.fetchall()}
  110. cursor.execute(
  111. "SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name)
  112. )
  113. # PostgreSQL OIDs may vary depending on the installation, especially
  114. # for datatypes from extensions, e.g. "hstore". In such cases, the
  115. # type_display attribute (psycopg 3.2+) should be used.
  116. type_display_available = psycopg_version() >= (3, 2)
  117. return [
  118. FieldInfo(
  119. line.name,
  120. (
  121. line.type_display
  122. if type_display_available and line.type_display == "hstore"
  123. else line.type_code
  124. ),
  125. # display_size is always None on psycopg2.
  126. line.internal_size if line.display_size is None else line.display_size,
  127. line.internal_size,
  128. # precision and scale are always 2^16 - 1 on psycopg2 for
  129. # DecimalFields with no precision.
  130. None if line.precision == 2**16 - 1 else line.precision,
  131. None if line.scale == 2**16 - 1 else line.scale,
  132. *field_map[line.name],
  133. )
  134. for line in cursor.description
  135. ]
  136. def get_sequences(self, cursor, table_name, table_fields=()):
  137. cursor.execute(
  138. """
  139. SELECT
  140. s.relname AS sequence_name,
  141. a.attname AS colname
  142. FROM
  143. pg_class s
  144. JOIN pg_depend d ON d.objid = s.oid
  145. AND d.classid = 'pg_class'::regclass
  146. AND d.refclassid = 'pg_class'::regclass
  147. JOIN pg_attribute a ON d.refobjid = a.attrelid
  148. AND d.refobjsubid = a.attnum
  149. JOIN pg_class tbl ON tbl.oid = d.refobjid
  150. AND tbl.relname = %s
  151. AND pg_catalog.pg_table_is_visible(tbl.oid)
  152. WHERE
  153. s.relkind = 'S';
  154. """,
  155. [table_name],
  156. )
  157. return [
  158. {"name": row[0], "table": table_name, "column": row[1]}
  159. for row in cursor.fetchall()
  160. ]
  161. def get_relations(self, cursor, table_name):
  162. """
  163. Return a dictionary of
  164. {
  165. field_name: (field_name_other_table, other_table, db_on_delete)
  166. }
  167. representing all foreign keys in the given table.
  168. """
  169. cursor.execute(
  170. """
  171. SELECT a1.attname, c2.relname, a2.attname, con.confdeltype
  172. FROM pg_constraint con
  173. LEFT JOIN pg_class c1 ON con.conrelid = c1.oid
  174. LEFT JOIN pg_class c2 ON con.confrelid = c2.oid
  175. LEFT JOIN
  176. pg_attribute a1 ON c1.oid = a1.attrelid AND a1.attnum = con.conkey[1]
  177. LEFT JOIN
  178. pg_attribute a2 ON c2.oid = a2.attrelid AND a2.attnum = con.confkey[1]
  179. WHERE
  180. c1.relname = %s AND
  181. con.contype = 'f' AND
  182. c1.relnamespace = c2.relnamespace AND
  183. pg_catalog.pg_table_is_visible(c1.oid)
  184. """,
  185. [table_name],
  186. )
  187. return {
  188. row[0]: (row[2], row[1], self.on_delete_types.get(row[3]))
  189. for row in cursor.fetchall()
  190. }
  191. def get_constraints(self, cursor, table_name):
  192. """
  193. Retrieve any constraints or keys (unique, pk, fk, check, index) across
  194. one or more columns. Also retrieve the definition of expression-based
  195. indexes.
  196. """
  197. constraints = {}
  198. # Loop over the key table, collecting things as constraints. The column
  199. # array must return column names in the same order in which they were
  200. # created.
  201. cursor.execute(
  202. """
  203. SELECT
  204. c.conname,
  205. array(
  206. SELECT attname
  207. FROM unnest(c.conkey) WITH ORDINALITY cols(colid, arridx)
  208. JOIN pg_attribute AS ca ON cols.colid = ca.attnum
  209. WHERE ca.attrelid = c.conrelid
  210. ORDER BY cols.arridx
  211. ),
  212. c.contype,
  213. (SELECT fkc.relname || '.' || fka.attname
  214. FROM pg_attribute AS fka
  215. JOIN pg_class AS fkc ON fka.attrelid = fkc.oid
  216. WHERE fka.attrelid = c.confrelid AND fka.attnum = c.confkey[1]),
  217. cl.reloptions
  218. FROM pg_constraint AS c
  219. JOIN pg_class AS cl ON c.conrelid = cl.oid
  220. WHERE cl.relname = %s
  221. AND pg_catalog.pg_table_is_visible(cl.oid)
  222. AND c.contype != 'n'
  223. """,
  224. [table_name],
  225. )
  226. for constraint, columns, kind, used_cols, options in cursor.fetchall():
  227. constraints[constraint] = {
  228. "columns": columns,
  229. "primary_key": kind == "p",
  230. "unique": kind in ["p", "u"],
  231. "foreign_key": tuple(used_cols.split(".", 1)) if kind == "f" else None,
  232. "check": kind == "c",
  233. "index": False,
  234. "definition": None,
  235. "options": options,
  236. }
  237. # Now get indexes
  238. cursor.execute(
  239. """
  240. SELECT
  241. indexname,
  242. array_agg(attname ORDER BY arridx),
  243. indisunique,
  244. indisprimary,
  245. array_agg(ordering ORDER BY arridx),
  246. amname,
  247. exprdef,
  248. s2.attoptions
  249. FROM (
  250. SELECT
  251. c2.relname as indexname, idx.*, attr.attname, am.amname,
  252. CASE
  253. WHEN idx.indexprs IS NOT NULL THEN
  254. pg_get_indexdef(idx.indexrelid)
  255. END AS exprdef,
  256. CASE am.amname
  257. WHEN %s THEN
  258. CASE (option & 1)
  259. WHEN 1 THEN 'DESC' ELSE 'ASC'
  260. END
  261. END as ordering,
  262. c2.reloptions as attoptions
  263. FROM (
  264. SELECT *
  265. FROM
  266. pg_index i,
  267. unnest(i.indkey, i.indoption)
  268. WITH ORDINALITY koi(key, option, arridx)
  269. ) idx
  270. LEFT JOIN pg_class c ON idx.indrelid = c.oid
  271. LEFT JOIN pg_class c2 ON idx.indexrelid = c2.oid
  272. LEFT JOIN pg_am am ON c2.relam = am.oid
  273. LEFT JOIN
  274. pg_attribute attr ON attr.attrelid = c.oid AND attr.attnum = idx.key
  275. WHERE c.relname = %s AND pg_catalog.pg_table_is_visible(c.oid)
  276. ) s2
  277. GROUP BY indexname, indisunique, indisprimary, amname, exprdef, attoptions;
  278. """,
  279. [self.index_default_access_method, table_name],
  280. )
  281. for (
  282. index,
  283. columns,
  284. unique,
  285. primary,
  286. orders,
  287. type_,
  288. definition,
  289. options,
  290. ) in cursor.fetchall():
  291. if index not in constraints:
  292. basic_index = (
  293. type_ == self.index_default_access_method
  294. and
  295. # '_btree' references
  296. # django.contrib.postgres.indexes.BTreeIndex.suffix.
  297. not index.endswith("_btree")
  298. and options is None
  299. )
  300. constraints[index] = {
  301. "columns": columns if columns != [None] else [],
  302. "orders": orders if orders != [None] else [],
  303. "primary_key": primary,
  304. "unique": unique,
  305. "foreign_key": None,
  306. "check": False,
  307. "index": True,
  308. "type": Index.suffix if basic_index else type_,
  309. "definition": definition,
  310. "options": options,
  311. }
  312. return constraints