PageRenderTime 36ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/django/db/backends/oracle/operations.py

https://gitlab.com/Guy1394/django
Python | 449 lines | 440 code | 7 blank | 2 comment | 3 complexity | b3fd450dc10be23a8f1f21f704bac57b MD5 | raw file
  1. from __future__ import unicode_literals
  2. import datetime
  3. import re
  4. import uuid
  5. from django.conf import settings
  6. from django.db.backends.base.operations import BaseDatabaseOperations
  7. from django.db.backends.utils import truncate_name
  8. from django.utils import six, timezone
  9. from django.utils.encoding import force_bytes, force_text
  10. from .base import Database
  11. from .utils import InsertIdVar, Oracle_datetime, convert_unicode
  12. class DatabaseOperations(BaseDatabaseOperations):
  13. compiler_module = "django.db.backends.oracle.compiler"
  14. # Oracle uses NUMBER(11) and NUMBER(19) for integer fields.
  15. integer_field_ranges = {
  16. 'SmallIntegerField': (-99999999999, 99999999999),
  17. 'IntegerField': (-99999999999, 99999999999),
  18. 'BigIntegerField': (-9999999999999999999, 9999999999999999999),
  19. 'PositiveSmallIntegerField': (0, 99999999999),
  20. 'PositiveIntegerField': (0, 99999999999),
  21. }
  22. # TODO: colorize this SQL code with style.SQL_KEYWORD(), etc.
  23. _sequence_reset_sql = """
  24. DECLARE
  25. table_value integer;
  26. seq_value integer;
  27. BEGIN
  28. SELECT NVL(MAX(%(column)s), 0) INTO table_value FROM %(table)s;
  29. SELECT NVL(last_number - cache_size, 0) INTO seq_value FROM user_sequences
  30. WHERE sequence_name = '%(sequence)s';
  31. WHILE table_value > seq_value LOOP
  32. SELECT "%(sequence)s".nextval INTO seq_value FROM dual;
  33. END LOOP;
  34. END;
  35. /"""
  36. def autoinc_sql(self, table, column):
  37. # To simulate auto-incrementing primary keys in Oracle, we have to
  38. # create a sequence and a trigger.
  39. sq_name = self._get_sequence_name(table)
  40. tr_name = self._get_trigger_name(table)
  41. tbl_name = self.quote_name(table)
  42. col_name = self.quote_name(column)
  43. sequence_sql = """
  44. DECLARE
  45. i INTEGER;
  46. BEGIN
  47. SELECT COUNT(*) INTO i FROM USER_CATALOG
  48. WHERE TABLE_NAME = '%(sq_name)s' AND TABLE_TYPE = 'SEQUENCE';
  49. IF i = 0 THEN
  50. EXECUTE IMMEDIATE 'CREATE SEQUENCE "%(sq_name)s"';
  51. END IF;
  52. END;
  53. /""" % locals()
  54. trigger_sql = """
  55. CREATE OR REPLACE TRIGGER "%(tr_name)s"
  56. BEFORE INSERT ON %(tbl_name)s
  57. FOR EACH ROW
  58. WHEN (new.%(col_name)s IS NULL)
  59. BEGIN
  60. SELECT "%(sq_name)s".nextval
  61. INTO :new.%(col_name)s FROM dual;
  62. END;
  63. /""" % locals()
  64. return sequence_sql, trigger_sql
  65. def cache_key_culling_sql(self):
  66. return """
  67. SELECT cache_key
  68. FROM (SELECT cache_key, rank() OVER (ORDER BY cache_key) AS rank FROM %s)
  69. WHERE rank = %%s + 1
  70. """
  71. def date_extract_sql(self, lookup_type, field_name):
  72. if lookup_type == 'week_day':
  73. # TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday.
  74. return "TO_CHAR(%s, 'D')" % field_name
  75. else:
  76. # http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions050.htm
  77. return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
  78. def date_interval_sql(self, timedelta):
  79. """
  80. Implements the interval functionality for expressions
  81. format for Oracle:
  82. INTERVAL '3 00:03:20.000000' DAY(1) TO SECOND(6)
  83. """
  84. minutes, seconds = divmod(timedelta.seconds, 60)
  85. hours, minutes = divmod(minutes, 60)
  86. days = str(timedelta.days)
  87. day_precision = len(days)
  88. fmt = "INTERVAL '%s %02d:%02d:%02d.%06d' DAY(%d) TO SECOND(6)"
  89. return fmt % (days, hours, minutes, seconds, timedelta.microseconds,
  90. day_precision), []
  91. def date_trunc_sql(self, lookup_type, field_name):
  92. # http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions230.htm#i1002084
  93. if lookup_type in ('year', 'month'):
  94. return "TRUNC(%s, '%s')" % (field_name, lookup_type.upper())
  95. else:
  96. return "TRUNC(%s)" % field_name
  97. # Oracle crashes with "ORA-03113: end-of-file on communication channel"
  98. # if the time zone name is passed in parameter. Use interpolation instead.
  99. # https://groups.google.com/forum/#!msg/django-developers/zwQju7hbG78/9l934yelwfsJ
  100. # This regexp matches all time zone names from the zoneinfo database.
  101. _tzname_re = re.compile(r'^[\w/:+-]+$')
  102. def _convert_field_to_tz(self, field_name, tzname):
  103. if not settings.USE_TZ:
  104. return field_name
  105. if not self._tzname_re.match(tzname):
  106. raise ValueError("Invalid time zone name: %s" % tzname)
  107. # Convert from UTC to local time, returning TIMESTAMP WITH TIME ZONE.
  108. result = "(FROM_TZ(%s, '0:00') AT TIME ZONE '%s')" % (field_name, tzname)
  109. # Extracting from a TIMESTAMP WITH TIME ZONE ignore the time zone.
  110. # Convert to a DATETIME, which is called DATE by Oracle. There's no
  111. # built-in function to do that; the easiest is to go through a string.
  112. result = "TO_CHAR(%s, 'YYYY-MM-DD HH24:MI:SS')" % result
  113. result = "TO_DATE(%s, 'YYYY-MM-DD HH24:MI:SS')" % result
  114. # Re-convert to a TIMESTAMP because EXTRACT only handles the date part
  115. # on DATE values, even though they actually store the time part.
  116. return "CAST(%s AS TIMESTAMP)" % result
  117. def datetime_cast_date_sql(self, field_name, tzname):
  118. field_name = self._convert_field_to_tz(field_name, tzname)
  119. sql = 'TRUNC(%s)' % field_name
  120. return sql, []
  121. def datetime_extract_sql(self, lookup_type, field_name, tzname):
  122. field_name = self._convert_field_to_tz(field_name, tzname)
  123. sql = self.date_extract_sql(lookup_type, field_name)
  124. return sql, []
  125. def datetime_trunc_sql(self, lookup_type, field_name, tzname):
  126. field_name = self._convert_field_to_tz(field_name, tzname)
  127. # http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions230.htm#i1002084
  128. if lookup_type in ('year', 'month'):
  129. sql = "TRUNC(%s, '%s')" % (field_name, lookup_type.upper())
  130. elif lookup_type == 'day':
  131. sql = "TRUNC(%s)" % field_name
  132. elif lookup_type == 'hour':
  133. sql = "TRUNC(%s, 'HH24')" % field_name
  134. elif lookup_type == 'minute':
  135. sql = "TRUNC(%s, 'MI')" % field_name
  136. else:
  137. sql = field_name # Cast to DATE removes sub-second precision.
  138. return sql, []
  139. def get_db_converters(self, expression):
  140. converters = super(DatabaseOperations, self).get_db_converters(expression)
  141. internal_type = expression.output_field.get_internal_type()
  142. if internal_type == 'TextField':
  143. converters.append(self.convert_textfield_value)
  144. elif internal_type == 'BinaryField':
  145. converters.append(self.convert_binaryfield_value)
  146. elif internal_type in ['BooleanField', 'NullBooleanField']:
  147. converters.append(self.convert_booleanfield_value)
  148. elif internal_type == 'DateTimeField':
  149. converters.append(self.convert_datetimefield_value)
  150. elif internal_type == 'DateField':
  151. converters.append(self.convert_datefield_value)
  152. elif internal_type == 'TimeField':
  153. converters.append(self.convert_timefield_value)
  154. elif internal_type == 'UUIDField':
  155. converters.append(self.convert_uuidfield_value)
  156. converters.append(self.convert_empty_values)
  157. return converters
  158. def convert_textfield_value(self, value, expression, connection, context):
  159. if isinstance(value, Database.LOB):
  160. value = force_text(value.read())
  161. return value
  162. def convert_binaryfield_value(self, value, expression, connection, context):
  163. if isinstance(value, Database.LOB):
  164. value = force_bytes(value.read())
  165. return value
  166. def convert_booleanfield_value(self, value, expression, connection, context):
  167. if value in (0, 1):
  168. value = bool(value)
  169. return value
  170. # cx_Oracle always returns datetime.datetime objects for
  171. # DATE and TIMESTAMP columns, but Django wants to see a
  172. # python datetime.date, .time, or .datetime.
  173. def convert_datetimefield_value(self, value, expression, connection, context):
  174. if value is not None:
  175. if settings.USE_TZ:
  176. value = timezone.make_aware(value, self.connection.timezone)
  177. return value
  178. def convert_datefield_value(self, value, expression, connection, context):
  179. if isinstance(value, Database.Timestamp):
  180. value = value.date()
  181. return value
  182. def convert_timefield_value(self, value, expression, connection, context):
  183. if isinstance(value, Database.Timestamp):
  184. value = value.time()
  185. return value
  186. def convert_uuidfield_value(self, value, expression, connection, context):
  187. if value is not None:
  188. value = uuid.UUID(value)
  189. return value
  190. def convert_empty_values(self, value, expression, connection, context):
  191. # Oracle stores empty strings as null. We need to undo this in
  192. # order to adhere to the Django convention of using the empty
  193. # string instead of null, but only if the field accepts the
  194. # empty string.
  195. field = expression.output_field
  196. if value is None and field.empty_strings_allowed:
  197. value = ''
  198. if field.get_internal_type() == 'BinaryField':
  199. value = b''
  200. return value
  201. def deferrable_sql(self):
  202. return " DEFERRABLE INITIALLY DEFERRED"
  203. def drop_sequence_sql(self, table):
  204. return "DROP SEQUENCE %s;" % self.quote_name(self._get_sequence_name(table))
  205. def fetch_returned_insert_id(self, cursor):
  206. return int(cursor._insert_id_var.getvalue())
  207. def field_cast_sql(self, db_type, internal_type):
  208. if db_type and db_type.endswith('LOB'):
  209. return "DBMS_LOB.SUBSTR(%s)"
  210. else:
  211. return "%s"
  212. def last_executed_query(self, cursor, sql, params):
  213. # http://cx-oracle.sourceforge.net/html/cursor.html#Cursor.statement
  214. # The DB API definition does not define this attribute.
  215. statement = cursor.statement
  216. if statement and six.PY2 and not isinstance(statement, unicode): # NOQA: unicode undefined on PY3
  217. statement = statement.decode('utf-8')
  218. # Unlike Psycopg's `query` and MySQLdb`'s `_last_executed`, CxOracle's
  219. # `statement` doesn't contain the query parameters. refs #20010.
  220. return super(DatabaseOperations, self).last_executed_query(cursor, statement, params)
  221. def last_insert_id(self, cursor, table_name, pk_name):
  222. sq_name = self._get_sequence_name(table_name)
  223. cursor.execute('SELECT "%s".currval FROM dual' % sq_name)
  224. return cursor.fetchone()[0]
  225. def lookup_cast(self, lookup_type, internal_type=None):
  226. if lookup_type in ('iexact', 'icontains', 'istartswith', 'iendswith'):
  227. return "UPPER(%s)"
  228. return "%s"
  229. def max_in_list_size(self):
  230. return 1000
  231. def max_name_length(self):
  232. return 30
  233. def pk_default_value(self):
  234. return "NULL"
  235. def prep_for_iexact_query(self, x):
  236. return x
  237. def process_clob(self, value):
  238. if value is None:
  239. return ''
  240. return force_text(value.read())
  241. def quote_name(self, name):
  242. # SQL92 requires delimited (quoted) names to be case-sensitive. When
  243. # not quoted, Oracle has case-insensitive behavior for identifiers, but
  244. # always defaults to uppercase.
  245. # We simplify things by making Oracle identifiers always uppercase.
  246. if not name.startswith('"') and not name.endswith('"'):
  247. name = '"%s"' % truncate_name(name.upper(), self.max_name_length())
  248. # Oracle puts the query text into a (query % args) construct, so % signs
  249. # in names need to be escaped. The '%%' will be collapsed back to '%' at
  250. # that stage so we aren't really making the name longer here.
  251. name = name.replace('%', '%%')
  252. return name.upper()
  253. def random_function_sql(self):
  254. return "DBMS_RANDOM.RANDOM"
  255. def regex_lookup(self, lookup_type):
  256. if lookup_type == 'regex':
  257. match_option = "'c'"
  258. else:
  259. match_option = "'i'"
  260. return 'REGEXP_LIKE(%%s, %%s, %s)' % match_option
  261. def return_insert_id(self):
  262. return "RETURNING %s INTO %%s", (InsertIdVar(),)
  263. def savepoint_create_sql(self, sid):
  264. return convert_unicode("SAVEPOINT " + self.quote_name(sid))
  265. def savepoint_rollback_sql(self, sid):
  266. return convert_unicode("ROLLBACK TO SAVEPOINT " + self.quote_name(sid))
  267. def sql_flush(self, style, tables, sequences, allow_cascade=False):
  268. # Return a list of 'TRUNCATE x;', 'TRUNCATE y;',
  269. # 'TRUNCATE z;'... style SQL statements
  270. if tables:
  271. # Oracle does support TRUNCATE, but it seems to get us into
  272. # FK referential trouble, whereas DELETE FROM table works.
  273. sql = ['%s %s %s;' % (
  274. style.SQL_KEYWORD('DELETE'),
  275. style.SQL_KEYWORD('FROM'),
  276. style.SQL_FIELD(self.quote_name(table))
  277. ) for table in tables]
  278. # Since we've just deleted all the rows, running our sequence
  279. # ALTER code will reset the sequence to 0.
  280. sql.extend(self.sequence_reset_by_name_sql(style, sequences))
  281. return sql
  282. else:
  283. return []
  284. def sequence_reset_by_name_sql(self, style, sequences):
  285. sql = []
  286. for sequence_info in sequences:
  287. sequence_name = self._get_sequence_name(sequence_info['table'])
  288. table_name = self.quote_name(sequence_info['table'])
  289. column_name = self.quote_name(sequence_info['column'] or 'id')
  290. query = self._sequence_reset_sql % {
  291. 'sequence': sequence_name,
  292. 'table': table_name,
  293. 'column': column_name,
  294. }
  295. sql.append(query)
  296. return sql
  297. def sequence_reset_sql(self, style, model_list):
  298. from django.db import models
  299. output = []
  300. query = self._sequence_reset_sql
  301. for model in model_list:
  302. for f in model._meta.local_fields:
  303. if isinstance(f, models.AutoField):
  304. table_name = self.quote_name(model._meta.db_table)
  305. sequence_name = self._get_sequence_name(model._meta.db_table)
  306. column_name = self.quote_name(f.column)
  307. output.append(query % {'sequence': sequence_name,
  308. 'table': table_name,
  309. 'column': column_name})
  310. # Only one AutoField is allowed per model, so don't
  311. # continue to loop
  312. break
  313. for f in model._meta.many_to_many:
  314. if not f.remote_field.through:
  315. table_name = self.quote_name(f.m2m_db_table())
  316. sequence_name = self._get_sequence_name(f.m2m_db_table())
  317. column_name = self.quote_name('id')
  318. output.append(query % {'sequence': sequence_name,
  319. 'table': table_name,
  320. 'column': column_name})
  321. return output
  322. def start_transaction_sql(self):
  323. return ''
  324. def tablespace_sql(self, tablespace, inline=False):
  325. if inline:
  326. return "USING INDEX TABLESPACE %s" % self.quote_name(tablespace)
  327. else:
  328. return "TABLESPACE %s" % self.quote_name(tablespace)
  329. def adapt_datefield_value(self, value):
  330. """
  331. Transform a date value to an object compatible with what is expected
  332. by the backend driver for date columns.
  333. The default implementation transforms the date to text, but that is not
  334. necessary for Oracle.
  335. """
  336. return value
  337. def adapt_datetimefield_value(self, value):
  338. """
  339. Transform a datetime value to an object compatible with what is expected
  340. by the backend driver for datetime columns.
  341. If naive datetime is passed assumes that is in UTC. Normally Django
  342. models.DateTimeField makes sure that if USE_TZ is True passed datetime
  343. is timezone aware.
  344. """
  345. if value is None:
  346. return None
  347. # cx_Oracle doesn't support tz-aware datetimes
  348. if timezone.is_aware(value):
  349. if settings.USE_TZ:
  350. value = timezone.make_naive(value, self.connection.timezone)
  351. else:
  352. raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")
  353. return Oracle_datetime.from_datetime(value)
  354. def adapt_timefield_value(self, value):
  355. if value is None:
  356. return None
  357. if isinstance(value, six.string_types):
  358. return datetime.datetime.strptime(value, '%H:%M:%S')
  359. # Oracle doesn't support tz-aware times
  360. if timezone.is_aware(value):
  361. raise ValueError("Oracle backend does not support timezone-aware times.")
  362. return Oracle_datetime(1900, 1, 1, value.hour, value.minute,
  363. value.second, value.microsecond)
  364. def combine_expression(self, connector, sub_expressions):
  365. "Oracle requires special cases for %% and & operators in query expressions"
  366. if connector == '%%':
  367. return 'MOD(%s)' % ','.join(sub_expressions)
  368. elif connector == '&':
  369. return 'BITAND(%s)' % ','.join(sub_expressions)
  370. elif connector == '|':
  371. raise NotImplementedError("Bit-wise or is not supported in Oracle.")
  372. elif connector == '^':
  373. return 'POWER(%s)' % ','.join(sub_expressions)
  374. return super(DatabaseOperations, self).combine_expression(connector, sub_expressions)
  375. def _get_sequence_name(self, table):
  376. name_length = self.max_name_length() - 3
  377. return '%s_SQ' % truncate_name(table, name_length).upper()
  378. def _get_trigger_name(self, table):
  379. name_length = self.max_name_length() - 3
  380. return '%s_TR' % truncate_name(table, name_length).upper()
  381. def bulk_insert_sql(self, fields, placeholder_rows):
  382. return " UNION ALL ".join(
  383. "SELECT %s FROM DUAL" % ", ".join(row)
  384. for row in placeholder_rows
  385. )