base.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. """
  2. PostgreSQL database backend for Django.
  3. Requires psycopg 2: https://www.psycopg.org/
  4. """
  5. import asyncio
  6. import threading
  7. import warnings
  8. from contextlib import contextmanager
  9. from django.conf import settings
  10. from django.core.exceptions import ImproperlyConfigured
  11. from django.db import DatabaseError as WrappedDatabaseError, connections
  12. from django.db.backends.base.base import BaseDatabaseWrapper
  13. from django.db.backends.utils import (
  14. CursorDebugWrapper as BaseCursorDebugWrapper,
  15. )
  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. import psycopg2 as Database
  22. import psycopg2.extensions
  23. import psycopg2.extras
  24. except ImportError as e:
  25. raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
  26. def psycopg2_version():
  27. version = psycopg2.__version__.split(' ', 1)[0]
  28. return get_version_tuple(version)
  29. PSYCOPG2_VERSION = psycopg2_version()
  30. if PSYCOPG2_VERSION < (2, 5, 4):
  31. raise ImproperlyConfigured("psycopg2_version 2.5.4 or newer is required; you have %s" % psycopg2.__version__)
  32. # Some of these import psycopg2, so import them after checking if it's installed.
  33. from .client import DatabaseClient # NOQA
  34. from .creation import DatabaseCreation # NOQA
  35. from .features import DatabaseFeatures # NOQA
  36. from .introspection import DatabaseIntrospection # NOQA
  37. from .operations import DatabaseOperations # NOQA
  38. from .schema import DatabaseSchemaEditor # NOQA
  39. psycopg2.extensions.register_adapter(SafeString, psycopg2.extensions.QuotedString)
  40. psycopg2.extras.register_uuid()
  41. # Register support for inet[] manually so we don't have to handle the Inet()
  42. # object on load all the time.
  43. INETARRAY_OID = 1041
  44. INETARRAY = psycopg2.extensions.new_array_type(
  45. (INETARRAY_OID,),
  46. 'INETARRAY',
  47. psycopg2.extensions.UNICODE,
  48. )
  49. psycopg2.extensions.register_type(INETARRAY)
  50. class DatabaseWrapper(BaseDatabaseWrapper):
  51. vendor = 'postgresql'
  52. display_name = 'PostgreSQL'
  53. # This dictionary maps Field objects to their associated PostgreSQL column
  54. # types, as strings. Column-type strings can contain format strings; they'll
  55. # be interpolated against the values of Field.__dict__ before being output.
  56. # If a column type is set to None, it won't be included in the output.
  57. data_types = {
  58. 'AutoField': 'serial',
  59. 'BigAutoField': 'bigserial',
  60. 'BinaryField': 'bytea',
  61. 'BooleanField': 'boolean',
  62. 'CharField': 'varchar(%(max_length)s)',
  63. 'DateField': 'date',
  64. 'DateTimeField': 'timestamp with time zone',
  65. 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
  66. 'DurationField': 'interval',
  67. 'FileField': 'varchar(%(max_length)s)',
  68. 'FilePathField': 'varchar(%(max_length)s)',
  69. 'FloatField': 'double precision',
  70. 'IntegerField': 'integer',
  71. 'BigIntegerField': 'bigint',
  72. 'IPAddressField': 'inet',
  73. 'GenericIPAddressField': 'inet',
  74. 'JSONField': 'jsonb',
  75. 'NullBooleanField': 'boolean',
  76. 'OneToOneField': 'integer',
  77. 'PositiveBigIntegerField': 'bigint',
  78. 'PositiveIntegerField': 'integer',
  79. 'PositiveSmallIntegerField': 'smallint',
  80. 'SlugField': 'varchar(%(max_length)s)',
  81. 'SmallAutoField': 'smallserial',
  82. 'SmallIntegerField': 'smallint',
  83. 'TextField': 'text',
  84. 'TimeField': 'time',
  85. 'UUIDField': 'uuid',
  86. }
  87. data_type_check_constraints = {
  88. 'PositiveBigIntegerField': '"%(column)s" >= 0',
  89. 'PositiveIntegerField': '"%(column)s" >= 0',
  90. 'PositiveSmallIntegerField': '"%(column)s" >= 0',
  91. }
  92. operators = {
  93. 'exact': '= %s',
  94. 'iexact': '= UPPER(%s)',
  95. 'contains': 'LIKE %s',
  96. 'icontains': 'LIKE UPPER(%s)',
  97. 'regex': '~ %s',
  98. 'iregex': '~* %s',
  99. 'gt': '> %s',
  100. 'gte': '>= %s',
  101. 'lt': '< %s',
  102. 'lte': '<= %s',
  103. 'startswith': 'LIKE %s',
  104. 'endswith': 'LIKE %s',
  105. 'istartswith': 'LIKE UPPER(%s)',
  106. 'iendswith': 'LIKE UPPER(%s)',
  107. }
  108. # The patterns below are used to generate SQL pattern lookup clauses when
  109. # the right-hand side of the lookup isn't a raw string (it might be an expression
  110. # or the result of a bilateral transformation).
  111. # In those cases, special characters for LIKE operators (e.g. \, *, _) should be
  112. # escaped on database side.
  113. #
  114. # Note: we use str.format() here for readability as '%' is used as a wildcard for
  115. # the LIKE operator.
  116. pattern_esc = r"REPLACE(REPLACE(REPLACE({}, E'\\', E'\\\\'), E'%%', E'\\%%'), E'_', E'\\_')"
  117. pattern_ops = {
  118. 'contains': "LIKE '%%' || {} || '%%'",
  119. 'icontains': "LIKE '%%' || UPPER({}) || '%%'",
  120. 'startswith': "LIKE {} || '%%'",
  121. 'istartswith': "LIKE UPPER({}) || '%%'",
  122. 'endswith': "LIKE '%%' || {}",
  123. 'iendswith': "LIKE '%%' || UPPER({})",
  124. }
  125. Database = Database
  126. SchemaEditorClass = DatabaseSchemaEditor
  127. # Classes instantiated in __init__().
  128. client_class = DatabaseClient
  129. creation_class = DatabaseCreation
  130. features_class = DatabaseFeatures
  131. introspection_class = DatabaseIntrospection
  132. ops_class = DatabaseOperations
  133. # PostgreSQL backend-specific attributes.
  134. _named_cursor_idx = 0
  135. def get_connection_params(self):
  136. settings_dict = self.settings_dict
  137. # None may be used to connect to the default 'postgres' db
  138. if settings_dict['NAME'] == '':
  139. raise ImproperlyConfigured(
  140. "settings.DATABASES is improperly configured. "
  141. "Please supply the NAME value.")
  142. if len(settings_dict['NAME'] or '') > self.ops.max_name_length():
  143. raise ImproperlyConfigured(
  144. "The database name '%s' (%d characters) is longer than "
  145. "PostgreSQL's limit of %d characters. Supply a shorter NAME "
  146. "in settings.DATABASES." % (
  147. settings_dict['NAME'],
  148. len(settings_dict['NAME']),
  149. self.ops.max_name_length(),
  150. )
  151. )
  152. conn_params = {
  153. 'database': settings_dict['NAME'] or 'postgres',
  154. **settings_dict['OPTIONS'],
  155. }
  156. conn_params.pop('isolation_level', None)
  157. if settings_dict['USER']:
  158. conn_params['user'] = settings_dict['USER']
  159. if settings_dict['PASSWORD']:
  160. conn_params['password'] = settings_dict['PASSWORD']
  161. if settings_dict['HOST']:
  162. conn_params['host'] = settings_dict['HOST']
  163. if settings_dict['PORT']:
  164. conn_params['port'] = settings_dict['PORT']
  165. return conn_params
  166. @async_unsafe
  167. def get_new_connection(self, conn_params):
  168. connection = Database.connect(**conn_params)
  169. # self.isolation_level must be set:
  170. # - after connecting to the database in order to obtain the database's
  171. # default when no value is explicitly specified in options.
  172. # - before calling _set_autocommit() because if autocommit is on, that
  173. # will set connection.isolation_level to ISOLATION_LEVEL_AUTOCOMMIT.
  174. options = self.settings_dict['OPTIONS']
  175. try:
  176. self.isolation_level = options['isolation_level']
  177. except KeyError:
  178. self.isolation_level = connection.isolation_level
  179. else:
  180. # Set the isolation level to the value from OPTIONS.
  181. if self.isolation_level != connection.isolation_level:
  182. connection.set_session(isolation_level=self.isolation_level)
  183. # Register dummy loads() to avoid a round trip from psycopg2's decode
  184. # to json.dumps() to json.loads(), when using a custom decoder in
  185. # JSONField.
  186. psycopg2.extras.register_default_jsonb(conn_or_curs=connection, loads=lambda x: x)
  187. return connection
  188. def ensure_timezone(self):
  189. if self.connection is None:
  190. return False
  191. conn_timezone_name = self.connection.get_parameter_status('TimeZone')
  192. timezone_name = self.timezone_name
  193. if timezone_name and conn_timezone_name != timezone_name:
  194. with self.connection.cursor() as cursor:
  195. cursor.execute(self.ops.set_time_zone_sql(), [timezone_name])
  196. return True
  197. return False
  198. def init_connection_state(self):
  199. self.connection.set_client_encoding('UTF8')
  200. timezone_changed = self.ensure_timezone()
  201. if timezone_changed:
  202. # Commit after setting the time zone (see #17062)
  203. if not self.get_autocommit():
  204. self.connection.commit()
  205. @async_unsafe
  206. def create_cursor(self, name=None):
  207. if name:
  208. # In autocommit mode, the cursor will be used outside of a
  209. # transaction, hence use a holdable cursor.
  210. cursor = self.connection.cursor(name, scrollable=False, withhold=self.connection.autocommit)
  211. else:
  212. cursor = self.connection.cursor()
  213. cursor.tzinfo_factory = self.tzinfo_factory if settings.USE_TZ else None
  214. return cursor
  215. def tzinfo_factory(self, offset):
  216. return self.timezone
  217. @async_unsafe
  218. def chunked_cursor(self):
  219. self._named_cursor_idx += 1
  220. # Get the current async task
  221. # Note that right now this is behind @async_unsafe, so this is
  222. # unreachable, but in future we'll start loosening this restriction.
  223. # For now, it's here so that every use of "threading" is
  224. # also async-compatible.
  225. try:
  226. if hasattr(asyncio, 'current_task'):
  227. # Python 3.7 and up
  228. current_task = asyncio.current_task()
  229. else:
  230. # Python 3.6
  231. current_task = asyncio.Task.current_task()
  232. except RuntimeError:
  233. current_task = None
  234. # Current task can be none even if the current_task call didn't error
  235. if current_task:
  236. task_ident = str(id(current_task))
  237. else:
  238. task_ident = 'sync'
  239. # Use that and the thread ident to get a unique name
  240. return self._cursor(
  241. name='_django_curs_%d_%s_%d' % (
  242. # Avoid reusing name in other threads / tasks
  243. threading.current_thread().ident,
  244. task_ident,
  245. self._named_cursor_idx,
  246. )
  247. )
  248. def _set_autocommit(self, autocommit):
  249. with self.wrap_database_errors:
  250. self.connection.autocommit = autocommit
  251. def check_constraints(self, table_names=None):
  252. """
  253. Check constraints by setting them to immediate. Return them to deferred
  254. afterward.
  255. """
  256. with self.cursor() as cursor:
  257. cursor.execute('SET CONSTRAINTS ALL IMMEDIATE')
  258. cursor.execute('SET CONSTRAINTS ALL DEFERRED')
  259. def is_usable(self):
  260. try:
  261. # Use a psycopg cursor directly, bypassing Django's utilities.
  262. with self.connection.cursor() as cursor:
  263. cursor.execute('SELECT 1')
  264. except Database.Error:
  265. return False
  266. else:
  267. return True
  268. @contextmanager
  269. def _nodb_cursor(self):
  270. try:
  271. with super()._nodb_cursor() as cursor:
  272. yield cursor
  273. except (Database.DatabaseError, WrappedDatabaseError):
  274. warnings.warn(
  275. "Normally Django will use a connection to the 'postgres' database "
  276. "to avoid running initialization queries against the production "
  277. "database when it's not needed (for example, when running tests). "
  278. "Django was unable to create a connection to the 'postgres' database "
  279. "and will use the first PostgreSQL database instead.",
  280. RuntimeWarning
  281. )
  282. for connection in connections.all():
  283. if connection.vendor == 'postgresql' and connection.settings_dict['NAME'] != 'postgres':
  284. conn = self.__class__(
  285. {**self.settings_dict, 'NAME': connection.settings_dict['NAME']},
  286. alias=self.alias,
  287. )
  288. try:
  289. with conn.cursor() as cursor:
  290. yield cursor
  291. finally:
  292. conn.close()
  293. break
  294. else:
  295. raise
  296. @cached_property
  297. def pg_version(self):
  298. with self.temporary_connection():
  299. return self.connection.server_version
  300. def make_debug_cursor(self, cursor):
  301. return CursorDebugWrapper(cursor, self)
  302. class CursorDebugWrapper(BaseCursorDebugWrapper):
  303. def copy_expert(self, sql, file, *args):
  304. with self.debug_sql(sql):
  305. return self.cursor.copy_expert(sql, file, *args)
  306. def copy_to(self, file, table, *args, **kwargs):
  307. with self.debug_sql(sql='COPY %s TO STDOUT' % table):
  308. return self.cursor.copy_to(file, table, *args, **kwargs)