base.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. """
  2. Oracle database backend for Django.
  3. Requires cx_Oracle: https://oracle.github.io/python-cx_Oracle/
  4. """
  5. import datetime
  6. import decimal
  7. import os
  8. import platform
  9. from contextlib import contextmanager
  10. from django.conf import settings
  11. from django.core.exceptions import ImproperlyConfigured
  12. from django.db import utils
  13. from django.db.backends.base.base import BaseDatabaseWrapper
  14. from django.utils.asyncio import async_unsafe
  15. from django.utils.encoding import force_bytes, force_str
  16. from django.utils.functional import cached_property
  17. def _setup_environment(environ):
  18. # Cygwin requires some special voodoo to set the environment variables
  19. # properly so that Oracle will see them.
  20. if platform.system().upper().startswith('CYGWIN'):
  21. try:
  22. import ctypes
  23. except ImportError as e:
  24. raise ImproperlyConfigured("Error loading ctypes: %s; "
  25. "the Oracle backend requires ctypes to "
  26. "operate correctly under Cygwin." % e)
  27. kernel32 = ctypes.CDLL('kernel32')
  28. for name, value in environ:
  29. kernel32.SetEnvironmentVariableA(name, value)
  30. else:
  31. os.environ.update(environ)
  32. _setup_environment([
  33. # Oracle takes client-side character set encoding from the environment.
  34. ('NLS_LANG', '.AL32UTF8'),
  35. # This prevents unicode from getting mangled by getting encoded into the
  36. # potentially non-unicode database character set.
  37. ('ORA_NCHAR_LITERAL_REPLACE', 'TRUE'),
  38. ])
  39. try:
  40. import cx_Oracle as Database
  41. except ImportError as e:
  42. raise ImproperlyConfigured("Error loading cx_Oracle module: %s" % e)
  43. # Some of these import cx_Oracle, so import them after checking if it's installed.
  44. from .client import DatabaseClient # NOQA isort:skip
  45. from .creation import DatabaseCreation # NOQA isort:skip
  46. from .features import DatabaseFeatures # NOQA isort:skip
  47. from .introspection import DatabaseIntrospection # NOQA isort:skip
  48. from .operations import DatabaseOperations # NOQA isort:skip
  49. from .schema import DatabaseSchemaEditor # NOQA isort:skip
  50. from .utils import Oracle_datetime # NOQA isort:skip
  51. from .validation import DatabaseValidation # NOQA isort:skip
  52. @contextmanager
  53. def wrap_oracle_errors():
  54. try:
  55. yield
  56. except Database.DatabaseError as e:
  57. # cx_Oracle raises a cx_Oracle.DatabaseError exception with the
  58. # following attributes and values:
  59. # code = 2091
  60. # message = 'ORA-02091: transaction rolled back
  61. # 'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS
  62. # _C00102056) violated - parent key not found'
  63. # Convert that case to Django's IntegrityError exception.
  64. x = e.args[0]
  65. if hasattr(x, 'code') and hasattr(x, 'message') and x.code == 2091 and 'ORA-02291' in x.message:
  66. raise utils.IntegrityError(*tuple(e.args))
  67. raise
  68. class _UninitializedOperatorsDescriptor:
  69. def __get__(self, instance, cls=None):
  70. # If connection.operators is looked up before a connection has been
  71. # created, transparently initialize connection.operators to avert an
  72. # AttributeError.
  73. if instance is None:
  74. raise AttributeError("operators not available as class attribute")
  75. # Creating a cursor will initialize the operators.
  76. instance.cursor().close()
  77. return instance.__dict__['operators']
  78. class DatabaseWrapper(BaseDatabaseWrapper):
  79. vendor = 'oracle'
  80. display_name = 'Oracle'
  81. # This dictionary maps Field objects to their associated Oracle column
  82. # types, as strings. Column-type strings can contain format strings; they'll
  83. # be interpolated against the values of Field.__dict__ before being output.
  84. # If a column type is set to None, it won't be included in the output.
  85. #
  86. # Any format strings starting with "qn_" are quoted before being used in the
  87. # output (the "qn_" prefix is stripped before the lookup is performed.
  88. data_types = {
  89. 'AutoField': 'NUMBER(11) GENERATED BY DEFAULT ON NULL AS IDENTITY',
  90. 'BigAutoField': 'NUMBER(19) GENERATED BY DEFAULT ON NULL AS IDENTITY',
  91. 'BinaryField': 'BLOB',
  92. 'BooleanField': 'NUMBER(1)',
  93. 'CharField': 'NVARCHAR2(%(max_length)s)',
  94. 'DateField': 'DATE',
  95. 'DateTimeField': 'TIMESTAMP',
  96. 'DecimalField': 'NUMBER(%(max_digits)s, %(decimal_places)s)',
  97. 'DurationField': 'INTERVAL DAY(9) TO SECOND(6)',
  98. 'FileField': 'NVARCHAR2(%(max_length)s)',
  99. 'FilePathField': 'NVARCHAR2(%(max_length)s)',
  100. 'FloatField': 'DOUBLE PRECISION',
  101. 'IntegerField': 'NUMBER(11)',
  102. 'BigIntegerField': 'NUMBER(19)',
  103. 'IPAddressField': 'VARCHAR2(15)',
  104. 'GenericIPAddressField': 'VARCHAR2(39)',
  105. 'NullBooleanField': 'NUMBER(1)',
  106. 'OneToOneField': 'NUMBER(11)',
  107. 'PositiveIntegerField': 'NUMBER(11)',
  108. 'PositiveSmallIntegerField': 'NUMBER(11)',
  109. 'SlugField': 'NVARCHAR2(%(max_length)s)',
  110. 'SmallAutoField': 'NUMBER(5) GENERATED BY DEFAULT ON NULL AS IDENTITY',
  111. 'SmallIntegerField': 'NUMBER(11)',
  112. 'TextField': 'NCLOB',
  113. 'TimeField': 'TIMESTAMP',
  114. 'URLField': 'VARCHAR2(%(max_length)s)',
  115. 'UUIDField': 'VARCHAR2(32)',
  116. }
  117. data_type_check_constraints = {
  118. 'BooleanField': '%(qn_column)s IN (0,1)',
  119. 'NullBooleanField': '%(qn_column)s IN (0,1)',
  120. 'PositiveIntegerField': '%(qn_column)s >= 0',
  121. 'PositiveSmallIntegerField': '%(qn_column)s >= 0',
  122. }
  123. # Oracle doesn't support a database index on these columns.
  124. _limited_data_types = ('clob', 'nclob', 'blob')
  125. operators = _UninitializedOperatorsDescriptor()
  126. _standard_operators = {
  127. 'exact': '= %s',
  128. 'iexact': '= UPPER(%s)',
  129. 'contains': "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
  130. 'icontains': "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
  131. 'gt': '> %s',
  132. 'gte': '>= %s',
  133. 'lt': '< %s',
  134. 'lte': '<= %s',
  135. 'startswith': "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
  136. 'endswith': "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
  137. 'istartswith': "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
  138. 'iendswith': "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
  139. }
  140. _likec_operators = {
  141. **_standard_operators,
  142. 'contains': "LIKEC %s ESCAPE '\\'",
  143. 'icontains': "LIKEC UPPER(%s) ESCAPE '\\'",
  144. 'startswith': "LIKEC %s ESCAPE '\\'",
  145. 'endswith': "LIKEC %s ESCAPE '\\'",
  146. 'istartswith': "LIKEC UPPER(%s) ESCAPE '\\'",
  147. 'iendswith': "LIKEC UPPER(%s) ESCAPE '\\'",
  148. }
  149. # The patterns below are used to generate SQL pattern lookup clauses when
  150. # the right-hand side of the lookup isn't a raw string (it might be an expression
  151. # or the result of a bilateral transformation).
  152. # In those cases, special characters for LIKE operators (e.g. \, %, _)
  153. # should be escaped on the database side.
  154. #
  155. # Note: we use str.format() here for readability as '%' is used as a wildcard for
  156. # the LIKE operator.
  157. pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\', '\\'), '%%', '\%%'), '_', '\_')"
  158. _pattern_ops = {
  159. 'contains': "'%%' || {} || '%%'",
  160. 'icontains': "'%%' || UPPER({}) || '%%'",
  161. 'startswith': "{} || '%%'",
  162. 'istartswith': "UPPER({}) || '%%'",
  163. 'endswith': "'%%' || {}",
  164. 'iendswith': "'%%' || UPPER({})",
  165. }
  166. _standard_pattern_ops = {k: "LIKE TRANSLATE( " + v + " USING NCHAR_CS)"
  167. " ESCAPE TRANSLATE('\\' USING NCHAR_CS)"
  168. for k, v in _pattern_ops.items()}
  169. _likec_pattern_ops = {k: "LIKEC " + v + " ESCAPE '\\'"
  170. for k, v in _pattern_ops.items()}
  171. Database = Database
  172. SchemaEditorClass = DatabaseSchemaEditor
  173. # Classes instantiated in __init__().
  174. client_class = DatabaseClient
  175. creation_class = DatabaseCreation
  176. features_class = DatabaseFeatures
  177. introspection_class = DatabaseIntrospection
  178. ops_class = DatabaseOperations
  179. validation_class = DatabaseValidation
  180. def __init__(self, *args, **kwargs):
  181. super().__init__(*args, **kwargs)
  182. use_returning_into = self.settings_dict["OPTIONS"].get('use_returning_into', True)
  183. self.features.can_return_columns_from_insert = use_returning_into
  184. def _dsn(self):
  185. settings_dict = self.settings_dict
  186. if not settings_dict['HOST'].strip():
  187. settings_dict['HOST'] = 'localhost'
  188. if settings_dict['PORT']:
  189. return Database.makedsn(settings_dict['HOST'], int(settings_dict['PORT']), settings_dict['NAME'])
  190. return settings_dict['NAME']
  191. def _connect_string(self):
  192. return '%s/"%s"@%s' % (self.settings_dict['USER'], self.settings_dict['PASSWORD'], self._dsn())
  193. def get_connection_params(self):
  194. conn_params = self.settings_dict['OPTIONS'].copy()
  195. if 'use_returning_into' in conn_params:
  196. del conn_params['use_returning_into']
  197. return conn_params
  198. @async_unsafe
  199. def get_new_connection(self, conn_params):
  200. return Database.connect(
  201. user=self.settings_dict['USER'],
  202. password=self.settings_dict['PASSWORD'],
  203. dsn=self._dsn(),
  204. **conn_params,
  205. )
  206. def init_connection_state(self):
  207. cursor = self.create_cursor()
  208. # Set the territory first. The territory overrides NLS_DATE_FORMAT
  209. # and NLS_TIMESTAMP_FORMAT to the territory default. When all of
  210. # these are set in single statement it isn't clear what is supposed
  211. # to happen.
  212. cursor.execute("ALTER SESSION SET NLS_TERRITORY = 'AMERICA'")
  213. # Set Oracle date to ANSI date format. This only needs to execute
  214. # once when we create a new connection. We also set the Territory
  215. # to 'AMERICA' which forces Sunday to evaluate to a '1' in
  216. # TO_CHAR().
  217. cursor.execute(
  218. "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'"
  219. " NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'" +
  220. (" TIME_ZONE = 'UTC'" if settings.USE_TZ else '')
  221. )
  222. cursor.close()
  223. if 'operators' not in self.__dict__:
  224. # Ticket #14149: Check whether our LIKE implementation will
  225. # work for this connection or we need to fall back on LIKEC.
  226. # This check is performed only once per DatabaseWrapper
  227. # instance per thread, since subsequent connections will use
  228. # the same settings.
  229. cursor = self.create_cursor()
  230. try:
  231. cursor.execute("SELECT 1 FROM DUAL WHERE DUMMY %s"
  232. % self._standard_operators['contains'],
  233. ['X'])
  234. except Database.DatabaseError:
  235. self.operators = self._likec_operators
  236. self.pattern_ops = self._likec_pattern_ops
  237. else:
  238. self.operators = self._standard_operators
  239. self.pattern_ops = self._standard_pattern_ops
  240. cursor.close()
  241. self.connection.stmtcachesize = 20
  242. # Ensure all changes are preserved even when AUTOCOMMIT is False.
  243. if not self.get_autocommit():
  244. self.commit()
  245. @async_unsafe
  246. def create_cursor(self, name=None):
  247. return FormatStylePlaceholderCursor(self.connection)
  248. def _commit(self):
  249. if self.connection is not None:
  250. with wrap_oracle_errors():
  251. return self.connection.commit()
  252. # Oracle doesn't support releasing savepoints. But we fake them when query
  253. # logging is enabled to keep query counts consistent with other backends.
  254. def _savepoint_commit(self, sid):
  255. if self.queries_logged:
  256. self.queries_log.append({
  257. 'sql': '-- RELEASE SAVEPOINT %s (faked)' % self.ops.quote_name(sid),
  258. 'time': '0.000',
  259. })
  260. def _set_autocommit(self, autocommit):
  261. with self.wrap_database_errors:
  262. self.connection.autocommit = autocommit
  263. def check_constraints(self, table_names=None):
  264. """
  265. Check constraints by setting them to immediate. Return them to deferred
  266. afterward.
  267. """
  268. self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
  269. self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
  270. def is_usable(self):
  271. try:
  272. self.connection.ping()
  273. except Database.Error:
  274. return False
  275. else:
  276. return True
  277. @cached_property
  278. def oracle_version(self):
  279. with self.temporary_connection():
  280. return tuple(int(x) for x in self.connection.version.split('.'))
  281. class OracleParam:
  282. """
  283. Wrapper object for formatting parameters for Oracle. If the string
  284. representation of the value is large enough (greater than 4000 characters)
  285. the input size needs to be set as CLOB. Alternatively, if the parameter
  286. has an `input_size` attribute, then the value of the `input_size` attribute
  287. will be used instead. Otherwise, no input size will be set for the
  288. parameter when executing the query.
  289. """
  290. def __init__(self, param, cursor, strings_only=False):
  291. # With raw SQL queries, datetimes can reach this function
  292. # without being converted by DateTimeField.get_db_prep_value.
  293. if settings.USE_TZ and (isinstance(param, datetime.datetime) and
  294. not isinstance(param, Oracle_datetime)):
  295. param = Oracle_datetime.from_datetime(param)
  296. string_size = 0
  297. # Oracle doesn't recognize True and False correctly.
  298. if param is True:
  299. param = 1
  300. elif param is False:
  301. param = 0
  302. if hasattr(param, 'bind_parameter'):
  303. self.force_bytes = param.bind_parameter(cursor)
  304. elif isinstance(param, (Database.Binary, datetime.timedelta)):
  305. self.force_bytes = param
  306. else:
  307. # To transmit to the database, we need Unicode if supported
  308. # To get size right, we must consider bytes.
  309. self.force_bytes = force_str(param, cursor.charset, strings_only)
  310. if isinstance(self.force_bytes, str):
  311. # We could optimize by only converting up to 4000 bytes here
  312. string_size = len(force_bytes(param, cursor.charset, strings_only))
  313. if hasattr(param, 'input_size'):
  314. # If parameter has `input_size` attribute, use that.
  315. self.input_size = param.input_size
  316. elif string_size > 4000:
  317. # Mark any string param greater than 4000 characters as a CLOB.
  318. self.input_size = Database.CLOB
  319. elif isinstance(param, datetime.datetime):
  320. self.input_size = Database.TIMESTAMP
  321. else:
  322. self.input_size = None
  323. class VariableWrapper:
  324. """
  325. An adapter class for cursor variables that prevents the wrapped object
  326. from being converted into a string when used to instantiate an OracleParam.
  327. This can be used generally for any other object that should be passed into
  328. Cursor.execute as-is.
  329. """
  330. def __init__(self, var):
  331. self.var = var
  332. def bind_parameter(self, cursor):
  333. return self.var
  334. def __getattr__(self, key):
  335. return getattr(self.var, key)
  336. def __setattr__(self, key, value):
  337. if key == 'var':
  338. self.__dict__[key] = value
  339. else:
  340. setattr(self.var, key, value)
  341. class FormatStylePlaceholderCursor:
  342. """
  343. Django uses "format" (e.g. '%s') style placeholders, but Oracle uses ":var"
  344. style. This fixes it -- but note that if you want to use a literal "%s" in
  345. a query, you'll need to use "%%s".
  346. """
  347. charset = 'utf-8'
  348. def __init__(self, connection):
  349. self.cursor = connection.cursor()
  350. self.cursor.outputtypehandler = self._output_type_handler
  351. @staticmethod
  352. def _output_number_converter(value):
  353. return decimal.Decimal(value) if '.' in value else int(value)
  354. @staticmethod
  355. def _get_decimal_converter(precision, scale):
  356. if scale == 0:
  357. return int
  358. context = decimal.Context(prec=precision)
  359. quantize_value = decimal.Decimal(1).scaleb(-scale)
  360. return lambda v: decimal.Decimal(v).quantize(quantize_value, context=context)
  361. @staticmethod
  362. def _output_type_handler(cursor, name, defaultType, length, precision, scale):
  363. """
  364. Called for each db column fetched from cursors. Return numbers as the
  365. appropriate Python type.
  366. """
  367. if defaultType == Database.NUMBER:
  368. if scale == -127:
  369. if precision == 0:
  370. # NUMBER column: decimal-precision floating point.
  371. # This will normally be an integer from a sequence,
  372. # but it could be a decimal value.
  373. outconverter = FormatStylePlaceholderCursor._output_number_converter
  374. else:
  375. # FLOAT column: binary-precision floating point.
  376. # This comes from FloatField columns.
  377. outconverter = float
  378. elif precision > 0:
  379. # NUMBER(p,s) column: decimal-precision fixed point.
  380. # This comes from IntegerField and DecimalField columns.
  381. outconverter = FormatStylePlaceholderCursor._get_decimal_converter(precision, scale)
  382. else:
  383. # No type information. This normally comes from a
  384. # mathematical expression in the SELECT list. Guess int
  385. # or Decimal based on whether it has a decimal point.
  386. outconverter = FormatStylePlaceholderCursor._output_number_converter
  387. return cursor.var(
  388. Database.STRING,
  389. size=255,
  390. arraysize=cursor.arraysize,
  391. outconverter=outconverter,
  392. )
  393. def _format_params(self, params):
  394. try:
  395. return {k: OracleParam(v, self, True) for k, v in params.items()}
  396. except AttributeError:
  397. return tuple(OracleParam(p, self, True) for p in params)
  398. def _guess_input_sizes(self, params_list):
  399. # Try dict handling; if that fails, treat as sequence
  400. if hasattr(params_list[0], 'keys'):
  401. sizes = {}
  402. for params in params_list:
  403. for k, value in params.items():
  404. if value.input_size:
  405. sizes[k] = value.input_size
  406. if sizes:
  407. self.setinputsizes(**sizes)
  408. else:
  409. # It's not a list of dicts; it's a list of sequences
  410. sizes = [None] * len(params_list[0])
  411. for params in params_list:
  412. for i, value in enumerate(params):
  413. if value.input_size:
  414. sizes[i] = value.input_size
  415. if sizes:
  416. self.setinputsizes(*sizes)
  417. def _param_generator(self, params):
  418. # Try dict handling; if that fails, treat as sequence
  419. if hasattr(params, 'items'):
  420. return {k: v.force_bytes for k, v in params.items()}
  421. else:
  422. return [p.force_bytes for p in params]
  423. def _fix_for_params(self, query, params, unify_by_values=False):
  424. # cx_Oracle wants no trailing ';' for SQL statements. For PL/SQL, it
  425. # it does want a trailing ';' but not a trailing '/'. However, these
  426. # characters must be included in the original query in case the query
  427. # is being passed to SQL*Plus.
  428. if query.endswith(';') or query.endswith('/'):
  429. query = query[:-1]
  430. if params is None:
  431. params = []
  432. elif hasattr(params, 'keys'):
  433. # Handle params as dict
  434. args = {k: ":%s" % k for k in params}
  435. query = query % args
  436. elif unify_by_values and params:
  437. # Handle params as a dict with unified query parameters by their
  438. # values. It can be used only in single query execute() because
  439. # executemany() shares the formatted query with each of the params
  440. # list. e.g. for input params = [0.75, 2, 0.75, 'sth', 0.75]
  441. # params_dict = {0.75: ':arg0', 2: ':arg1', 'sth': ':arg2'}
  442. # args = [':arg0', ':arg1', ':arg0', ':arg2', ':arg0']
  443. # params = {':arg0': 0.75, ':arg1': 2, ':arg2': 'sth'}
  444. params_dict = {
  445. param: ':arg%d' % i
  446. for i, param in enumerate(dict.fromkeys(params))
  447. }
  448. args = [params_dict[param] for param in params]
  449. params = {value: key for key, value in params_dict.items()}
  450. query = query % tuple(args)
  451. else:
  452. # Handle params as sequence
  453. args = [(':arg%d' % i) for i in range(len(params))]
  454. query = query % tuple(args)
  455. return query, self._format_params(params)
  456. def execute(self, query, params=None):
  457. query, params = self._fix_for_params(query, params, unify_by_values=True)
  458. self._guess_input_sizes([params])
  459. with wrap_oracle_errors():
  460. return self.cursor.execute(query, self._param_generator(params))
  461. def executemany(self, query, params=None):
  462. if not params:
  463. # No params given, nothing to do
  464. return None
  465. # uniform treatment for sequences and iterables
  466. params_iter = iter(params)
  467. query, firstparams = self._fix_for_params(query, next(params_iter))
  468. # we build a list of formatted params; as we're going to traverse it
  469. # more than once, we can't make it lazy by using a generator
  470. formatted = [firstparams] + [self._format_params(p) for p in params_iter]
  471. self._guess_input_sizes(formatted)
  472. with wrap_oracle_errors():
  473. return self.cursor.executemany(query, [self._param_generator(p) for p in formatted])
  474. def close(self):
  475. try:
  476. self.cursor.close()
  477. except Database.InterfaceError:
  478. # already closed
  479. pass
  480. def var(self, *args):
  481. return VariableWrapper(self.cursor.var(*args))
  482. def arrayvar(self, *args):
  483. return VariableWrapper(self.cursor.arrayvar(*args))
  484. def __getattr__(self, attr):
  485. return getattr(self.cursor, attr)
  486. def __iter__(self):
  487. return iter(self.cursor)