2
0

base.py 23 KB

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