base.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. """
  2. PostgreSQL database backend for Django.
  3. Requires psycopg2 >= 2.9.9 or psycopg >= 3.1.12
  4. """
  5. import asyncio
  6. import threading
  7. import warnings
  8. from contextlib import contextmanager
  9. from functools import lru_cache
  10. from django.conf import settings
  11. from django.core.exceptions import ImproperlyConfigured
  12. from django.db import DatabaseError as WrappedDatabaseError
  13. from django.db import connections
  14. from django.db.backends.base.base import NO_DB_ALIAS, BaseDatabaseWrapper
  15. from django.db.backends.utils import CursorDebugWrapper as BaseCursorDebugWrapper
  16. from django.utils.asyncio import async_unsafe
  17. from django.utils.functional import cached_property
  18. from django.utils.safestring import SafeString
  19. from django.utils.version import get_version_tuple
  20. try:
  21. try:
  22. import psycopg as Database
  23. except ImportError:
  24. import psycopg2 as Database
  25. except ImportError:
  26. raise ImproperlyConfigured("Error loading psycopg2 or psycopg module")
  27. @lru_cache
  28. def psycopg_version():
  29. version = Database.__version__.split(" ", 1)[0]
  30. return get_version_tuple(version)
  31. if psycopg_version() < (2, 9, 9):
  32. raise ImproperlyConfigured(
  33. f"psycopg2 version 2.9.9 or newer is required; you have {Database.__version__}"
  34. )
  35. if (3,) <= psycopg_version() < (3, 1, 12):
  36. raise ImproperlyConfigured(
  37. f"psycopg version 3.1.12 or newer is required; you have {Database.__version__}"
  38. )
  39. from .psycopg_any import IsolationLevel, is_psycopg3 # NOQA isort:skip
  40. if is_psycopg3:
  41. from psycopg import adapters, sql
  42. from psycopg.pq import Format
  43. from .psycopg_any import get_adapters_template, register_tzloader
  44. TIMESTAMPTZ_OID = adapters.types["timestamptz"].oid
  45. else:
  46. import psycopg2.extensions
  47. import psycopg2.extras
  48. psycopg2.extensions.register_adapter(SafeString, psycopg2.extensions.QuotedString)
  49. psycopg2.extras.register_uuid()
  50. # Register support for inet[] manually so we don't have to handle the
  51. # Inet() object on load all the time.
  52. INETARRAY_OID = 1041
  53. INETARRAY = psycopg2.extensions.new_array_type(
  54. (INETARRAY_OID,),
  55. "INETARRAY",
  56. psycopg2.extensions.UNICODE,
  57. )
  58. psycopg2.extensions.register_type(INETARRAY)
  59. # Some of these import psycopg, so import them after checking if it's
  60. # installed.
  61. from .client import DatabaseClient # NOQA isort:skip
  62. from .creation import DatabaseCreation # NOQA isort:skip
  63. from .features import DatabaseFeatures # NOQA isort:skip
  64. from .introspection import DatabaseIntrospection # NOQA isort:skip
  65. from .operations import DatabaseOperations # NOQA isort:skip
  66. from .schema import DatabaseSchemaEditor # NOQA isort:skip
  67. def _get_varchar_column(data):
  68. if data["max_length"] is None:
  69. return "varchar"
  70. return "varchar(%(max_length)s)" % data
  71. def _get_decimal_column(data):
  72. if data["max_digits"] is None and data["decimal_places"] is None:
  73. return "numeric"
  74. return "numeric(%(max_digits)s, %(decimal_places)s)" % data
  75. class DatabaseWrapper(BaseDatabaseWrapper):
  76. vendor = "postgresql"
  77. display_name = "PostgreSQL"
  78. # This dictionary maps Field objects to their associated PostgreSQL column
  79. # types, as strings. Column-type strings can contain format strings;
  80. # they'll be interpolated against the values of Field.__dict__ before being
  81. # output. If a column type is set to None, it won't be included in the
  82. # output.
  83. data_types = {
  84. "AutoField": "integer",
  85. "BigAutoField": "bigint",
  86. "BinaryField": "bytea",
  87. "BooleanField": "boolean",
  88. "CharField": _get_varchar_column,
  89. "DateField": "date",
  90. "DateTimeField": "timestamp with time zone",
  91. "DecimalField": _get_decimal_column,
  92. "DurationField": "interval",
  93. "FileField": "varchar(%(max_length)s)",
  94. "FilePathField": "varchar(%(max_length)s)",
  95. "FloatField": "double precision",
  96. "IntegerField": "integer",
  97. "BigIntegerField": "bigint",
  98. "IPAddressField": "inet",
  99. "GenericIPAddressField": "inet",
  100. "JSONField": "jsonb",
  101. "PositiveBigIntegerField": "bigint",
  102. "PositiveIntegerField": "integer",
  103. "PositiveSmallIntegerField": "smallint",
  104. "SlugField": "varchar(%(max_length)s)",
  105. "SmallAutoField": "smallint",
  106. "SmallIntegerField": "smallint",
  107. "TextField": "text",
  108. "TimeField": "time",
  109. "UUIDField": "uuid",
  110. }
  111. data_type_check_constraints = {
  112. "PositiveBigIntegerField": '"%(column)s" >= 0',
  113. "PositiveIntegerField": '"%(column)s" >= 0',
  114. "PositiveSmallIntegerField": '"%(column)s" >= 0',
  115. }
  116. data_types_suffix = {
  117. "AutoField": "GENERATED BY DEFAULT AS IDENTITY",
  118. "BigAutoField": "GENERATED BY DEFAULT AS IDENTITY",
  119. "SmallAutoField": "GENERATED BY DEFAULT AS IDENTITY",
  120. }
  121. operators = {
  122. "exact": "= %s",
  123. "iexact": "= UPPER(%s)",
  124. "contains": "LIKE %s",
  125. "icontains": "LIKE UPPER(%s)",
  126. "regex": "~ %s",
  127. "iregex": "~* %s",
  128. "gt": "> %s",
  129. "gte": ">= %s",
  130. "lt": "< %s",
  131. "lte": "<= %s",
  132. "startswith": "LIKE %s",
  133. "endswith": "LIKE %s",
  134. "istartswith": "LIKE UPPER(%s)",
  135. "iendswith": "LIKE UPPER(%s)",
  136. }
  137. # The patterns below are used to generate SQL pattern lookup clauses when
  138. # the right-hand side of the lookup isn't a raw string (it might be an
  139. # expression or the result of a bilateral transformation). In those cases,
  140. # special characters for LIKE operators (e.g. \, *, _) should be escaped on
  141. # database side.
  142. #
  143. # Note: we use str.format() here for readability as '%' is used as a
  144. # wildcard for the LIKE operator.
  145. pattern_esc = (
  146. r"REPLACE(REPLACE(REPLACE({}, E'\\', E'\\\\'), E'%%', E'\\%%'), E'_', E'\\_')"
  147. )
  148. pattern_ops = {
  149. "contains": "LIKE '%%' || {} || '%%'",
  150. "icontains": "LIKE '%%' || UPPER({}) || '%%'",
  151. "startswith": "LIKE {} || '%%'",
  152. "istartswith": "LIKE UPPER({}) || '%%'",
  153. "endswith": "LIKE '%%' || {}",
  154. "iendswith": "LIKE '%%' || UPPER({})",
  155. }
  156. Database = Database
  157. SchemaEditorClass = DatabaseSchemaEditor
  158. # Classes instantiated in __init__().
  159. client_class = DatabaseClient
  160. creation_class = DatabaseCreation
  161. features_class = DatabaseFeatures
  162. introspection_class = DatabaseIntrospection
  163. ops_class = DatabaseOperations
  164. # PostgreSQL backend-specific attributes.
  165. _named_cursor_idx = 0
  166. _connection_pools = {}
  167. @property
  168. def pool(self):
  169. pool_options = self.settings_dict["OPTIONS"].get("pool")
  170. if self.alias == NO_DB_ALIAS or not pool_options:
  171. return None
  172. if self.alias not in self._connection_pools:
  173. if self.settings_dict.get("CONN_MAX_AGE", 0) != 0:
  174. raise ImproperlyConfigured(
  175. "Pooling doesn't support persistent connections."
  176. )
  177. # Set the default options.
  178. if pool_options is True:
  179. pool_options = {}
  180. try:
  181. from psycopg_pool import ConnectionPool
  182. except ImportError as err:
  183. raise ImproperlyConfigured(
  184. "Error loading psycopg_pool module.\nDid you install psycopg[pool]?"
  185. ) from err
  186. connect_kwargs = self.get_connection_params()
  187. # Ensure we run in autocommit, Django properly sets it later on.
  188. connect_kwargs["autocommit"] = True
  189. enable_checks = self.settings_dict["CONN_HEALTH_CHECKS"]
  190. # Copy to avoid mutating the user's settings dict.
  191. pool_options = {**pool_options}
  192. pool_options.setdefault(
  193. "check", ConnectionPool.check_connection if enable_checks else None
  194. )
  195. pool = ConnectionPool(
  196. kwargs=connect_kwargs,
  197. open=False, # Do not open the pool during startup.
  198. configure=self._configure_connection,
  199. **pool_options,
  200. )
  201. # setdefault() ensures that multiple threads don't set this in
  202. # parallel. Since we do not open the pool during its init above,
  203. # this means that at worst during startup multiple threads generate
  204. # pool objects and the first to set it wins.
  205. self._connection_pools.setdefault(self.alias, pool)
  206. return self._connection_pools[self.alias]
  207. def close_pool(self):
  208. if self.pool:
  209. self.pool.close()
  210. del self._connection_pools[self.alias]
  211. def get_database_version(self):
  212. """
  213. Return a tuple of the database's version.
  214. E.g. for pg_version 120004, return (12, 4).
  215. """
  216. return divmod(self.pg_version, 10000)
  217. def get_connection_params(self):
  218. settings_dict = self.settings_dict
  219. # None may be used to connect to the default 'postgres' db
  220. if settings_dict["NAME"] == "" and not settings_dict["OPTIONS"].get("service"):
  221. raise ImproperlyConfigured(
  222. "settings.DATABASES is improperly configured. "
  223. "Please supply the NAME or OPTIONS['service'] value."
  224. )
  225. if len(settings_dict["NAME"] or "") > self.ops.max_name_length():
  226. raise ImproperlyConfigured(
  227. "The database name '%s' (%d characters) is longer than "
  228. "PostgreSQL's limit of %d characters. Supply a shorter NAME "
  229. "in settings.DATABASES."
  230. % (
  231. settings_dict["NAME"],
  232. len(settings_dict["NAME"]),
  233. self.ops.max_name_length(),
  234. )
  235. )
  236. if settings_dict["NAME"]:
  237. conn_params = {
  238. "dbname": settings_dict["NAME"],
  239. **settings_dict["OPTIONS"],
  240. }
  241. elif settings_dict["NAME"] is None:
  242. # Connect to the default 'postgres' db.
  243. settings_dict["OPTIONS"].pop("service", None)
  244. conn_params = {"dbname": "postgres", **settings_dict["OPTIONS"]}
  245. else:
  246. conn_params = {**settings_dict["OPTIONS"]}
  247. conn_params["client_encoding"] = "UTF8"
  248. conn_params.pop("assume_role", None)
  249. conn_params.pop("isolation_level", None)
  250. pool_options = conn_params.pop("pool", None)
  251. if pool_options and not is_psycopg3:
  252. raise ImproperlyConfigured("Database pooling requires psycopg >= 3")
  253. server_side_binding = conn_params.pop("server_side_binding", None)
  254. conn_params.setdefault(
  255. "cursor_factory",
  256. (
  257. ServerBindingCursor
  258. if is_psycopg3 and server_side_binding is True
  259. else Cursor
  260. ),
  261. )
  262. if settings_dict["USER"]:
  263. conn_params["user"] = settings_dict["USER"]
  264. if settings_dict["PASSWORD"]:
  265. conn_params["password"] = settings_dict["PASSWORD"]
  266. if settings_dict["HOST"]:
  267. conn_params["host"] = settings_dict["HOST"]
  268. if settings_dict["PORT"]:
  269. conn_params["port"] = settings_dict["PORT"]
  270. if is_psycopg3:
  271. conn_params["context"] = get_adapters_template(
  272. settings.USE_TZ, self.timezone
  273. )
  274. # Disable prepared statements by default to keep connection poolers
  275. # working. Can be reenabled via OPTIONS in the settings dict.
  276. conn_params["prepare_threshold"] = conn_params.pop(
  277. "prepare_threshold", None
  278. )
  279. return conn_params
  280. @async_unsafe
  281. def get_new_connection(self, conn_params):
  282. # self.isolation_level must be set:
  283. # - after connecting to the database in order to obtain the database's
  284. # default when no value is explicitly specified in options.
  285. # - before calling _set_autocommit() because if autocommit is on, that
  286. # will set connection.isolation_level to ISOLATION_LEVEL_AUTOCOMMIT.
  287. options = self.settings_dict["OPTIONS"]
  288. set_isolation_level = False
  289. try:
  290. isolation_level_value = options["isolation_level"]
  291. except KeyError:
  292. self.isolation_level = IsolationLevel.READ_COMMITTED
  293. else:
  294. # Set the isolation level to the value from OPTIONS.
  295. try:
  296. self.isolation_level = IsolationLevel(isolation_level_value)
  297. set_isolation_level = True
  298. except ValueError:
  299. raise ImproperlyConfigured(
  300. f"Invalid transaction isolation level {isolation_level_value} "
  301. f"specified. Use one of the psycopg.IsolationLevel values."
  302. )
  303. if self.pool:
  304. # If nothing else has opened the pool, open it now.
  305. self.pool.open()
  306. connection = self.pool.getconn()
  307. else:
  308. connection = self.Database.connect(**conn_params)
  309. if set_isolation_level:
  310. connection.isolation_level = self.isolation_level
  311. if not is_psycopg3:
  312. # Register dummy loads() to avoid a round trip from psycopg2's
  313. # decode to json.dumps() to json.loads(), when using a custom
  314. # decoder in JSONField.
  315. psycopg2.extras.register_default_jsonb(
  316. conn_or_curs=connection, loads=lambda x: x
  317. )
  318. return connection
  319. def ensure_timezone(self):
  320. # Close the pool so new connections pick up the correct timezone.
  321. self.close_pool()
  322. if self.connection is None:
  323. return False
  324. return self._configure_timezone(self.connection)
  325. def _configure_timezone(self, connection):
  326. conn_timezone_name = connection.info.parameter_status("TimeZone")
  327. timezone_name = self.timezone_name
  328. if timezone_name and conn_timezone_name != timezone_name:
  329. with connection.cursor() as cursor:
  330. cursor.execute(self.ops.set_time_zone_sql(), [timezone_name])
  331. return True
  332. return False
  333. def _configure_role(self, connection):
  334. if new_role := self.settings_dict["OPTIONS"].get("assume_role"):
  335. with connection.cursor() as cursor:
  336. sql = self.ops.compose_sql("SET ROLE %s", [new_role])
  337. cursor.execute(sql)
  338. return True
  339. return False
  340. def _configure_connection(self, connection):
  341. # This function is called from init_connection_state and from the
  342. # psycopg pool itself after a connection is opened.
  343. # Commit after setting the time zone.
  344. commit_tz = self._configure_timezone(connection)
  345. # Set the role on the connection. This is useful if the credential used
  346. # to login is not the same as the role that owns database resources. As
  347. # can be the case when using temporary or ephemeral credentials.
  348. commit_role = self._configure_role(connection)
  349. return commit_role or commit_tz
  350. def _close(self):
  351. if self.connection is not None:
  352. # `wrap_database_errors` only works for `putconn` as long as there
  353. # is no `reset` function set in the pool because it is deferred
  354. # into a thread and not directly executed.
  355. with self.wrap_database_errors:
  356. if self.pool:
  357. # Ensure the correct pool is returned. This is a workaround
  358. # for tests so a pool can be changed on setting changes
  359. # (e.g. USE_TZ, TIME_ZONE).
  360. self.connection._pool.putconn(self.connection)
  361. # Connection can no longer be used.
  362. self.connection = None
  363. else:
  364. return self.connection.close()
  365. def init_connection_state(self):
  366. super().init_connection_state()
  367. if self.connection is not None and not self.pool:
  368. commit = self._configure_connection(self.connection)
  369. if commit and not self.get_autocommit():
  370. self.connection.commit()
  371. @async_unsafe
  372. def create_cursor(self, name=None):
  373. if name:
  374. if is_psycopg3 and (
  375. self.settings_dict["OPTIONS"].get("server_side_binding") is not True
  376. ):
  377. # psycopg >= 3 forces the usage of server-side bindings for
  378. # named cursors so a specialized class that implements
  379. # server-side cursors while performing client-side bindings
  380. # must be used if `server_side_binding` is disabled (default).
  381. cursor = ServerSideCursor(
  382. self.connection,
  383. name=name,
  384. scrollable=False,
  385. withhold=self.connection.autocommit,
  386. )
  387. else:
  388. # In autocommit mode, the cursor will be used outside of a
  389. # transaction, hence use a holdable cursor.
  390. cursor = self.connection.cursor(
  391. name, scrollable=False, withhold=self.connection.autocommit
  392. )
  393. else:
  394. cursor = self.connection.cursor()
  395. if is_psycopg3:
  396. # Register the cursor timezone only if the connection disagrees, to
  397. # avoid copying the adapter map.
  398. tzloader = self.connection.adapters.get_loader(TIMESTAMPTZ_OID, Format.TEXT)
  399. if self.timezone != tzloader.timezone:
  400. register_tzloader(self.timezone, cursor)
  401. else:
  402. cursor.tzinfo_factory = self.tzinfo_factory if settings.USE_TZ else None
  403. return cursor
  404. def tzinfo_factory(self, offset):
  405. return self.timezone
  406. @async_unsafe
  407. def chunked_cursor(self):
  408. self._named_cursor_idx += 1
  409. # Get the current async task
  410. # Note that right now this is behind @async_unsafe, so this is
  411. # unreachable, but in future we'll start loosening this restriction.
  412. # For now, it's here so that every use of "threading" is
  413. # also async-compatible.
  414. try:
  415. current_task = asyncio.current_task()
  416. except RuntimeError:
  417. current_task = None
  418. # Current task can be none even if the current_task call didn't error
  419. if current_task:
  420. task_ident = str(id(current_task))
  421. else:
  422. task_ident = "sync"
  423. # Use that and the thread ident to get a unique name
  424. return self._cursor(
  425. name="_django_curs_%d_%s_%d"
  426. % (
  427. # Avoid reusing name in other threads / tasks
  428. threading.current_thread().ident,
  429. task_ident,
  430. self._named_cursor_idx,
  431. )
  432. )
  433. def _set_autocommit(self, autocommit):
  434. with self.wrap_database_errors:
  435. self.connection.autocommit = autocommit
  436. def check_constraints(self, table_names=None):
  437. """
  438. Check constraints by setting them to immediate. Return them to deferred
  439. afterward.
  440. """
  441. with self.cursor() as cursor:
  442. cursor.execute("SET CONSTRAINTS ALL IMMEDIATE")
  443. cursor.execute("SET CONSTRAINTS ALL DEFERRED")
  444. def is_usable(self):
  445. if self.connection is None:
  446. return False
  447. try:
  448. # Use a psycopg cursor directly, bypassing Django's utilities.
  449. with self.connection.cursor() as cursor:
  450. cursor.execute("SELECT 1")
  451. except Database.Error:
  452. return False
  453. else:
  454. return True
  455. def close_if_health_check_failed(self):
  456. if self.pool:
  457. # The pool only returns healthy connections.
  458. return
  459. return super().close_if_health_check_failed()
  460. @contextmanager
  461. def _nodb_cursor(self):
  462. cursor = None
  463. try:
  464. with super()._nodb_cursor() as cursor:
  465. yield cursor
  466. except (Database.DatabaseError, WrappedDatabaseError):
  467. if cursor is not None:
  468. raise
  469. warnings.warn(
  470. "Normally Django will use a connection to the 'postgres' database "
  471. "to avoid running initialization queries against the production "
  472. "database when it's not needed (for example, when running tests). "
  473. "Django was unable to create a connection to the 'postgres' database "
  474. "and will use the first PostgreSQL database instead.",
  475. RuntimeWarning,
  476. )
  477. for connection in connections.all():
  478. if (
  479. connection.vendor == "postgresql"
  480. and connection.settings_dict["NAME"] != "postgres"
  481. ):
  482. conn = self.__class__(
  483. {
  484. **self.settings_dict,
  485. "NAME": connection.settings_dict["NAME"],
  486. },
  487. alias=self.alias,
  488. )
  489. try:
  490. with conn.cursor() as cursor:
  491. yield cursor
  492. finally:
  493. conn.close()
  494. break
  495. else:
  496. raise
  497. @cached_property
  498. def pg_version(self):
  499. with self.temporary_connection():
  500. return self.connection.info.server_version
  501. def make_debug_cursor(self, cursor):
  502. return CursorDebugWrapper(cursor, self)
  503. if is_psycopg3:
  504. class CursorMixin:
  505. """
  506. A subclass of psycopg cursor implementing callproc.
  507. """
  508. def callproc(self, name, args=None):
  509. if not isinstance(name, sql.Identifier):
  510. name = sql.Identifier(name)
  511. qparts = [sql.SQL("SELECT * FROM "), name, sql.SQL("(")]
  512. if args:
  513. for item in args:
  514. qparts.append(sql.Literal(item))
  515. qparts.append(sql.SQL(","))
  516. del qparts[-1]
  517. qparts.append(sql.SQL(")"))
  518. stmt = sql.Composed(qparts)
  519. self.execute(stmt)
  520. return args
  521. class ServerBindingCursor(CursorMixin, Database.Cursor):
  522. pass
  523. class Cursor(CursorMixin, Database.ClientCursor):
  524. pass
  525. class ServerSideCursor(
  526. CursorMixin, Database.client_cursor.ClientCursorMixin, Database.ServerCursor
  527. ):
  528. """
  529. psycopg >= 3 forces the usage of server-side bindings when using named
  530. cursors but the ORM doesn't yet support the systematic generation of
  531. prepareable SQL (#20516).
  532. ClientCursorMixin forces the usage of client-side bindings while
  533. ServerCursor implements the logic required to declare and scroll
  534. through named cursors.
  535. Mixing ClientCursorMixin in wouldn't be necessary if Cursor allowed to
  536. specify how parameters should be bound instead, which ServerCursor
  537. would inherit, but that's not the case.
  538. """
  539. class CursorDebugWrapper(BaseCursorDebugWrapper):
  540. def copy(self, statement):
  541. with self.debug_sql(statement):
  542. return self.cursor.copy(statement)
  543. else:
  544. Cursor = psycopg2.extensions.cursor
  545. class CursorDebugWrapper(BaseCursorDebugWrapper):
  546. def copy_expert(self, sql, file, *args):
  547. with self.debug_sql(sql):
  548. return self.cursor.copy_expert(sql, file, *args)
  549. def copy_to(self, file, table, *args, **kwargs):
  550. with self.debug_sql(sql="COPY %s TO STDOUT" % table):
  551. return self.cursor.copy_to(file, table, *args, **kwargs)