2006-05-26 13:37:21 +08:00
|
|
|
"""
|
|
|
|
Oracle database backend for Django.
|
|
|
|
|
2008-12-12 04:12:00 +08:00
|
|
|
Requires cx_Oracle: http://cx-oracle.sourceforge.net/
|
2006-05-26 13:37:21 +08:00
|
|
|
"""
|
2012-06-08 00:08:47 +08:00
|
|
|
from __future__ import unicode_literals
|
2010-01-29 23:45:55 +08:00
|
|
|
|
2013-09-15 03:32:25 +08:00
|
|
|
import datetime
|
2011-07-13 17:35:51 +08:00
|
|
|
import decimal
|
2013-02-10 23:15:49 +08:00
|
|
|
import re
|
2013-07-08 08:39:54 +08:00
|
|
|
import platform
|
2011-06-11 02:43:29 +08:00
|
|
|
import sys
|
2012-03-17 17:11:24 +08:00
|
|
|
import warnings
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2010-12-03 08:54:39 +08:00
|
|
|
def _setup_environment(environ):
|
|
|
|
# Cygwin requires some special voodoo to set the environment variables
|
|
|
|
# properly so that Oracle will see them.
|
|
|
|
if platform.system().upper().startswith('CYGWIN'):
|
|
|
|
try:
|
|
|
|
import ctypes
|
2012-04-29 00:09:37 +08:00
|
|
|
except ImportError as e:
|
2010-12-08 15:56:43 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
|
|
|
raise ImproperlyConfigured("Error loading ctypes: %s; "
|
|
|
|
"the Oracle backend requires ctypes to "
|
|
|
|
"operate correctly under Cygwin." % e)
|
2010-12-03 08:54:39 +08:00
|
|
|
kernel32 = ctypes.CDLL('kernel32')
|
|
|
|
for name, value in environ:
|
|
|
|
kernel32.SetEnvironmentVariableA(name, value)
|
|
|
|
else:
|
|
|
|
import os
|
|
|
|
os.environ.update(environ)
|
|
|
|
|
|
|
|
_setup_environment([
|
|
|
|
# Oracle takes client-side character set encoding from the environment.
|
|
|
|
('NLS_LANG', '.UTF8'),
|
|
|
|
# This prevents unicode from getting mangled by getting encoded into the
|
|
|
|
# potentially non-unicode database character set.
|
|
|
|
('ORA_NCHAR_LITERAL_REPLACE', 'TRUE'),
|
|
|
|
])
|
|
|
|
|
2009-03-28 03:48:02 +08:00
|
|
|
|
2006-05-27 02:58:46 +08:00
|
|
|
try:
|
|
|
|
import cx_Oracle as Database
|
2012-04-29 00:09:37 +08:00
|
|
|
except ImportError as e:
|
2006-05-27 02:58:46 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2007-08-20 11:32:06 +08:00
|
|
|
raise ImproperlyConfigured("Error loading cx_Oracle module: %s" % e)
|
2007-06-23 22:16:00 +08:00
|
|
|
|
2013-05-19 20:38:16 +08:00
|
|
|
try:
|
|
|
|
import pytz
|
|
|
|
except ImportError:
|
|
|
|
pytz = None
|
|
|
|
|
2013-09-15 03:32:25 +08:00
|
|
|
from django.conf import settings
|
2010-01-29 23:45:55 +08:00
|
|
|
from django.db import utils
|
2013-09-17 00:52:05 +08:00
|
|
|
from django.db.backends import (BaseDatabaseFeatures, BaseDatabaseOperations,
|
|
|
|
BaseDatabaseWrapper, BaseDatabaseValidation, utils as backend_utils)
|
2008-08-22 22:18:53 +08:00
|
|
|
from django.db.backends.oracle.client import DatabaseClient
|
|
|
|
from django.db.backends.oracle.creation import DatabaseCreation
|
|
|
|
from django.db.backends.oracle.introspection import DatabaseIntrospection
|
2012-09-08 03:48:22 +08:00
|
|
|
from django.db.backends.oracle.schema import DatabaseSchemaEditor
|
2013-10-02 00:34:19 +08:00
|
|
|
from django.db.utils import InterfaceError
|
2013-09-15 03:32:25 +08:00
|
|
|
from django.utils import six, timezone
|
2012-08-29 02:59:56 +08:00
|
|
|
from django.utils.encoding import force_bytes, force_text
|
2013-09-15 03:32:25 +08:00
|
|
|
from django.utils.functional import cached_property
|
2013-03-11 10:50:18 +08:00
|
|
|
|
2008-08-22 22:18:53 +08:00
|
|
|
|
2008-09-02 03:58:41 +08:00
|
|
|
DatabaseError = Database.DatabaseError
|
2007-04-25 18:18:56 +08:00
|
|
|
IntegrityError = Database.IntegrityError
|
2006-05-26 13:37:21 +08:00
|
|
|
|
2013-01-15 21:05:58 +08:00
|
|
|
# Check whether cx_Oracle was compiled with the WITH_UNICODE option if cx_Oracle is pre-5.1. This will
|
|
|
|
# also be True for cx_Oracle 5.1 and in Python 3.0. See #19606
|
|
|
|
if int(Database.version.split('.', 1)[0]) >= 5 and \
|
|
|
|
(int(Database.version.split('.', 2)[1]) >= 1 or
|
|
|
|
not hasattr(Database, 'UNICODE')):
|
2012-07-21 16:00:10 +08:00
|
|
|
convert_unicode = force_text
|
2009-08-24 23:45:48 +08:00
|
|
|
else:
|
2012-08-29 02:59:56 +08:00
|
|
|
convert_unicode = force_bytes
|
2009-08-24 23:45:48 +08:00
|
|
|
|
|
|
|
|
2007-08-20 10:20:33 +08:00
|
|
|
class DatabaseFeatures(BaseDatabaseFeatures):
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
empty_fetchmany_value = ()
|
2007-08-20 10:20:33 +08:00
|
|
|
needs_datetime_string_cast = False
|
2008-06-16 11:15:04 +08:00
|
|
|
interprets_empty_strings_as_nulls = True
|
2009-03-11 02:37:22 +08:00
|
|
|
uses_savepoints = True
|
2011-04-21 04:42:07 +08:00
|
|
|
has_select_for_update = True
|
|
|
|
has_select_for_update_nowait = True
|
2009-03-13 07:41:27 +08:00
|
|
|
can_return_id_from_insert = True
|
2010-04-05 01:05:43 +08:00
|
|
|
allow_sliced_subqueries = False
|
2010-11-13 01:51:31 +08:00
|
|
|
supports_subqueries_in_group_by = False
|
2013-02-11 00:36:35 +08:00
|
|
|
supports_transactions = True
|
2010-10-11 20:55:17 +08:00
|
|
|
supports_timezones = False
|
2013-05-19 20:38:16 +08:00
|
|
|
has_zoneinfo_database = pytz is not None
|
2010-10-11 20:55:17 +08:00
|
|
|
supports_bitwise_or = False
|
2010-11-10 00:46:42 +08:00
|
|
|
can_defer_constraint_checks = True
|
2011-03-09 06:41:25 +08:00
|
|
|
ignores_nulls_in_unique_constraints = False
|
2011-09-12 07:02:53 +08:00
|
|
|
has_bulk_insert = True
|
2011-10-15 05:49:43 +08:00
|
|
|
supports_tablespaces = True
|
2012-05-23 04:46:27 +08:00
|
|
|
supports_sequence_reset = False
|
2013-09-23 04:14:17 +08:00
|
|
|
atomic_transactions = False
|
2013-08-13 03:05:20 +08:00
|
|
|
supports_combined_alters = False
|
2013-08-14 03:54:57 +08:00
|
|
|
max_index_name_length = 30
|
2013-08-21 00:28:59 +08:00
|
|
|
nulls_order_largest = True
|
2013-08-23 19:07:55 +08:00
|
|
|
requires_literal_defaults = True
|
|
|
|
connection_persists_old_columns = True
|
2013-08-21 00:28:59 +08:00
|
|
|
nulls_order_largest = True
|
2013-10-02 00:34:19 +08:00
|
|
|
closed_cursor_error_class = InterfaceError
|
2008-08-25 04:16:56 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2007-08-20 06:29:57 +08:00
|
|
|
class DatabaseOperations(BaseDatabaseOperations):
|
2009-12-22 23:18:51 +08:00
|
|
|
compiler_module = "django.db.backends.oracle.compiler"
|
2008-12-12 04:12:00 +08:00
|
|
|
|
2007-09-15 02:12:36 +08:00
|
|
|
def autoinc_sql(self, table, column):
|
2007-08-20 06:29:57 +08:00
|
|
|
# To simulate auto-incrementing primary keys in Oracle, we have to
|
|
|
|
# create a sequence and a trigger.
|
2011-04-05 08:19:17 +08:00
|
|
|
sq_name = self._get_sequence_name(table)
|
|
|
|
tr_name = self._get_trigger_name(table)
|
2007-09-15 02:12:36 +08:00
|
|
|
tbl_name = self.quote_name(table)
|
|
|
|
col_name = self.quote_name(column)
|
2008-08-25 04:16:56 +08:00
|
|
|
sequence_sql = """
|
2008-12-12 04:12:00 +08:00
|
|
|
DECLARE
|
|
|
|
i INTEGER;
|
|
|
|
BEGIN
|
|
|
|
SELECT COUNT(*) INTO i FROM USER_CATALOG
|
|
|
|
WHERE TABLE_NAME = '%(sq_name)s' AND TABLE_TYPE = 'SEQUENCE';
|
|
|
|
IF i = 0 THEN
|
|
|
|
EXECUTE IMMEDIATE 'CREATE SEQUENCE "%(sq_name)s"';
|
|
|
|
END IF;
|
|
|
|
END;
|
|
|
|
/""" % locals()
|
2007-08-20 06:29:57 +08:00
|
|
|
trigger_sql = """
|
2008-12-12 04:12:00 +08:00
|
|
|
CREATE OR REPLACE TRIGGER "%(tr_name)s"
|
|
|
|
BEFORE INSERT ON %(tbl_name)s
|
|
|
|
FOR EACH ROW
|
|
|
|
WHEN (new.%(col_name)s IS NULL)
|
|
|
|
BEGIN
|
|
|
|
SELECT "%(sq_name)s".nextval
|
|
|
|
INTO :new.%(col_name)s FROM dual;
|
|
|
|
END;
|
|
|
|
/""" % locals()
|
2007-08-20 06:29:57 +08:00
|
|
|
return sequence_sql, trigger_sql
|
|
|
|
|
2012-07-05 22:20:48 +08:00
|
|
|
def cache_key_culling_sql(self):
|
|
|
|
return """
|
|
|
|
SELECT cache_key
|
|
|
|
FROM (SELECT cache_key, rank() OVER (ORDER BY cache_key) AS rank FROM %s)
|
|
|
|
WHERE rank = %%s + 1
|
|
|
|
"""
|
|
|
|
|
2007-08-20 06:40:06 +08:00
|
|
|
def date_extract_sql(self, lookup_type, field_name):
|
2009-02-08 13:08:06 +08:00
|
|
|
if lookup_type == 'week_day':
|
|
|
|
# TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday.
|
|
|
|
return "TO_CHAR(%s, 'D')" % field_name
|
|
|
|
else:
|
2013-02-10 23:15:49 +08:00
|
|
|
# http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions050.htm
|
|
|
|
return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
|
2007-08-20 06:40:06 +08:00
|
|
|
|
2010-12-22 11:34:04 +08:00
|
|
|
def date_interval_sql(self, sql, connector, timedelta):
|
|
|
|
"""
|
|
|
|
Implements the interval functionality for expressions
|
|
|
|
format for Oracle:
|
|
|
|
(datefield + INTERVAL '3 00:03:20.000000' DAY(1) TO SECOND(6))
|
|
|
|
"""
|
|
|
|
minutes, seconds = divmod(timedelta.seconds, 60)
|
|
|
|
hours, minutes = divmod(minutes, 60)
|
|
|
|
days = str(timedelta.days)
|
|
|
|
day_precision = len(days)
|
|
|
|
fmt = "(%s %s INTERVAL '%s %02d:%02d:%02d.%06d' DAY(%d) TO SECOND(6))"
|
|
|
|
return fmt % (sql, connector, days, hours, minutes, seconds,
|
|
|
|
timedelta.microseconds, day_precision)
|
|
|
|
|
2007-08-20 06:47:43 +08:00
|
|
|
def date_trunc_sql(self, lookup_type, field_name):
|
2013-02-10 23:15:49 +08:00
|
|
|
# http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions230.htm#i1002084
|
|
|
|
if lookup_type in ('year', 'month'):
|
|
|
|
return "TRUNC(%s, '%s')" % (field_name, lookup_type.upper())
|
2007-08-20 06:47:43 +08:00
|
|
|
else:
|
2013-02-10 23:15:49 +08:00
|
|
|
return "TRUNC(%s)" % field_name
|
|
|
|
|
|
|
|
# Oracle crashes with "ORA-03113: end-of-file on communication channel"
|
|
|
|
# if the time zone name is passed in parameter. Use interpolation instead.
|
|
|
|
# https://groups.google.com/forum/#!msg/django-developers/zwQju7hbG78/9l934yelwfsJ
|
|
|
|
# This regexp matches all time zone names from the zoneinfo database.
|
|
|
|
_tzname_re = re.compile(r'^[\w/:+-]+$')
|
|
|
|
|
|
|
|
def _convert_field_to_tz(self, field_name, tzname):
|
|
|
|
if not self._tzname_re.match(tzname):
|
|
|
|
raise ValueError("Invalid time zone name: %s" % tzname)
|
|
|
|
# Convert from UTC to local time, returning TIMESTAMP WITH TIME ZONE.
|
|
|
|
result = "(FROM_TZ(%s, '0:00') AT TIME ZONE '%s')" % (field_name, tzname)
|
|
|
|
# Extracting from a TIMESTAMP WITH TIME ZONE ignore the time zone.
|
|
|
|
# Convert to a DATETIME, which is called DATE by Oracle. There's no
|
|
|
|
# built-in function to do that; the easiest is to go through a string.
|
|
|
|
result = "TO_CHAR(%s, 'YYYY-MM-DD HH24:MI:SS')" % result
|
|
|
|
result = "TO_DATE(%s, 'YYYY-MM-DD HH24:MI:SS')" % result
|
|
|
|
# Re-convert to a TIMESTAMP because EXTRACT only handles the date part
|
|
|
|
# on DATE values, even though they actually store the time part.
|
|
|
|
return "CAST(%s AS TIMESTAMP)" % result
|
|
|
|
|
|
|
|
def datetime_extract_sql(self, lookup_type, field_name, tzname):
|
|
|
|
if settings.USE_TZ:
|
|
|
|
field_name = self._convert_field_to_tz(field_name, tzname)
|
|
|
|
if lookup_type == 'week_day':
|
|
|
|
# TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday.
|
|
|
|
sql = "TO_CHAR(%s, 'D')" % field_name
|
|
|
|
else:
|
|
|
|
# http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions050.htm
|
|
|
|
sql = "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
|
|
|
|
return sql, []
|
|
|
|
|
|
|
|
def datetime_trunc_sql(self, lookup_type, field_name, tzname):
|
|
|
|
if settings.USE_TZ:
|
|
|
|
field_name = self._convert_field_to_tz(field_name, tzname)
|
|
|
|
# http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions230.htm#i1002084
|
|
|
|
if lookup_type in ('year', 'month'):
|
|
|
|
sql = "TRUNC(%s, '%s')" % (field_name, lookup_type.upper())
|
|
|
|
elif lookup_type == 'day':
|
|
|
|
sql = "TRUNC(%s)" % field_name
|
|
|
|
elif lookup_type == 'hour':
|
|
|
|
sql = "TRUNC(%s, 'HH24')" % field_name
|
|
|
|
elif lookup_type == 'minute':
|
|
|
|
sql = "TRUNC(%s, 'MI')" % field_name
|
|
|
|
else:
|
|
|
|
sql = field_name # Cast to DATE removes sub-second precision.
|
|
|
|
return sql, []
|
2007-08-20 06:47:43 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def convert_values(self, value, field):
|
|
|
|
if isinstance(value, Database.LOB):
|
|
|
|
value = value.read()
|
|
|
|
if field and field.get_internal_type() == 'TextField':
|
2012-07-21 16:00:10 +08:00
|
|
|
value = force_text(value)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
# Oracle stores empty strings as null. We need to undo this in
|
|
|
|
# order to adhere to the Django convention of using the empty
|
|
|
|
# string instead of null, but only if the field accepts the
|
|
|
|
# empty string.
|
|
|
|
if value is None and field and field.empty_strings_allowed:
|
2012-06-08 00:08:47 +08:00
|
|
|
value = ''
|
2009-12-22 23:18:51 +08:00
|
|
|
# Convert 1 or 0 to True or False
|
|
|
|
elif value in (1, 0) and field and field.get_internal_type() in ('BooleanField', 'NullBooleanField'):
|
|
|
|
value = bool(value)
|
|
|
|
# Force floats to the correct type
|
|
|
|
elif value is not None and field and field.get_internal_type() == 'FloatField':
|
|
|
|
value = float(value)
|
|
|
|
# Convert floats to decimals
|
|
|
|
elif value is not None and field and field.get_internal_type() == 'DecimalField':
|
2013-09-17 00:52:05 +08:00
|
|
|
value = backend_utils.typecast_decimal(field.format_number(value))
|
2009-12-22 23:18:51 +08:00
|
|
|
# cx_Oracle always returns datetime.datetime objects for
|
|
|
|
# DATE and TIMESTAMP columns, but Django wants to see a
|
|
|
|
# python datetime.date, .time, or .datetime. We use the type
|
|
|
|
# of the Field to determine which to cast to, but it's not
|
|
|
|
# always available.
|
|
|
|
# As a workaround, we cast to date if all the time-related
|
|
|
|
# values are 0, or to time if the date is 1/1/1900.
|
|
|
|
# This could be cleaned a bit by adding a method to the Field
|
|
|
|
# classes to normalize values from the database (the to_python
|
|
|
|
# method is used for validation and isn't what we want here).
|
|
|
|
elif isinstance(value, Database.Timestamp):
|
|
|
|
if field and field.get_internal_type() == 'DateTimeField':
|
|
|
|
pass
|
|
|
|
elif field and field.get_internal_type() == 'DateField':
|
|
|
|
value = value.date()
|
|
|
|
elif field and field.get_internal_type() == 'TimeField' or (value.year == 1900 and value.month == value.day == 1):
|
|
|
|
value = value.time()
|
|
|
|
elif value.hour == value.minute == value.second == value.microsecond == 0:
|
|
|
|
value = value.date()
|
|
|
|
return value
|
|
|
|
|
2007-08-20 07:03:38 +08:00
|
|
|
def deferrable_sql(self):
|
|
|
|
return " DEFERRABLE INITIALLY DEFERRED"
|
|
|
|
|
2007-08-20 11:08:32 +08:00
|
|
|
def drop_sequence_sql(self, table):
|
2011-04-05 08:19:17 +08:00
|
|
|
return "DROP SEQUENCE %s;" % self.quote_name(self._get_sequence_name(table))
|
2007-08-20 11:08:32 +08:00
|
|
|
|
2009-03-13 07:41:27 +08:00
|
|
|
def fetch_returned_insert_id(self, cursor):
|
2012-07-20 18:45:19 +08:00
|
|
|
return int(cursor._insert_id_var.getvalue())
|
2009-03-13 07:41:27 +08:00
|
|
|
|
2013-05-19 19:28:09 +08:00
|
|
|
def field_cast_sql(self, db_type, internal_type):
|
2007-08-22 01:06:06 +08:00
|
|
|
if db_type and db_type.endswith('LOB'):
|
2007-08-20 11:03:40 +08:00
|
|
|
return "DBMS_LOB.SUBSTR(%s)"
|
|
|
|
else:
|
|
|
|
return "%s"
|
|
|
|
|
2011-04-22 20:14:54 +08:00
|
|
|
def last_executed_query(self, cursor, sql, params):
|
|
|
|
# http://cx-oracle.sourceforge.net/html/cursor.html#Cursor.statement
|
|
|
|
# The DB API definition does not define this attribute.
|
2013-03-11 10:50:18 +08:00
|
|
|
statement = cursor.statement
|
2013-09-02 18:06:32 +08:00
|
|
|
if statement and six.PY2 and not isinstance(statement, unicode):
|
2013-03-11 10:50:18 +08:00
|
|
|
statement = statement.decode('utf-8')
|
|
|
|
# Unlike Psycopg's `query` and MySQLdb`'s `_last_executed`, CxOracle's
|
|
|
|
# `statement` doesn't contain the query parameters. refs #20010.
|
|
|
|
return super(DatabaseOperations, self).last_executed_query(cursor, statement, params)
|
2011-04-22 20:14:54 +08:00
|
|
|
|
2007-08-20 07:18:43 +08:00
|
|
|
def last_insert_id(self, cursor, table_name, pk_name):
|
2011-04-05 08:19:17 +08:00
|
|
|
sq_name = self._get_sequence_name(table_name)
|
2008-12-09 02:36:22 +08:00
|
|
|
cursor.execute('SELECT "%s".currval FROM dual' % sq_name)
|
2007-08-20 07:18:43 +08:00
|
|
|
return cursor.fetchone()[0]
|
|
|
|
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
def lookup_cast(self, lookup_type):
|
|
|
|
if lookup_type in ('iexact', 'icontains', 'istartswith', 'iendswith'):
|
|
|
|
return "UPPER(%s)"
|
|
|
|
return "%s"
|
|
|
|
|
2010-09-17 03:53:41 +08:00
|
|
|
def max_in_list_size(self):
|
|
|
|
return 1000
|
|
|
|
|
2007-08-20 07:53:39 +08:00
|
|
|
def max_name_length(self):
|
|
|
|
return 30
|
|
|
|
|
2008-09-02 03:37:48 +08:00
|
|
|
def prep_for_iexact_query(self, x):
|
|
|
|
return x
|
|
|
|
|
2009-03-14 05:04:48 +08:00
|
|
|
def process_clob(self, value):
|
|
|
|
if value is None:
|
2012-06-08 00:08:47 +08:00
|
|
|
return ''
|
2012-07-21 16:00:10 +08:00
|
|
|
return force_text(value.read())
|
2009-03-14 05:04:48 +08:00
|
|
|
|
2007-08-20 09:03:33 +08:00
|
|
|
def quote_name(self, name):
|
|
|
|
# SQL92 requires delimited (quoted) names to be case-sensitive. When
|
|
|
|
# not quoted, Oracle has case-insensitive behavior for identifiers, but
|
|
|
|
# always defaults to uppercase.
|
|
|
|
# We simplify things by making Oracle identifiers always uppercase.
|
|
|
|
if not name.startswith('"') and not name.endswith('"'):
|
2013-09-17 00:52:05 +08:00
|
|
|
name = '"%s"' % backend_utils.truncate_name(name.upper(),
|
2008-12-12 04:12:00 +08:00
|
|
|
self.max_name_length())
|
2012-10-27 09:51:14 +08:00
|
|
|
# Oracle puts the query text into a (query % args) construct, so % signs
|
|
|
|
# in names need to be escaped. The '%%' will be collapsed back to '%' at
|
|
|
|
# that stage so we aren't really making the name longer here.
|
2013-07-08 08:39:54 +08:00
|
|
|
name = name.replace('%', '%%')
|
2007-08-20 09:03:33 +08:00
|
|
|
return name.upper()
|
|
|
|
|
2013-09-07 04:27:51 +08:00
|
|
|
def quote_parameter(self, value):
|
|
|
|
if isinstance(value, (datetime.date, datetime.time, datetime.datetime)):
|
|
|
|
return "'%s'" % value
|
|
|
|
elif isinstance(value, six.string_types):
|
|
|
|
return repr(value)
|
|
|
|
elif isinstance(value, bool):
|
|
|
|
return "1" if value else "0"
|
|
|
|
else:
|
|
|
|
return str(value)
|
|
|
|
|
2007-08-20 08:04:20 +08:00
|
|
|
def random_function_sql(self):
|
|
|
|
return "DBMS_RANDOM.RANDOM"
|
|
|
|
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
def regex_lookup_9(self, lookup_type):
|
|
|
|
raise NotImplementedError("Regexes are not supported in Oracle before version 10g.")
|
|
|
|
|
|
|
|
def regex_lookup_10(self, lookup_type):
|
|
|
|
if lookup_type == 'regex':
|
|
|
|
match_option = "'c'"
|
|
|
|
else:
|
|
|
|
match_option = "'i'"
|
|
|
|
return 'REGEXP_LIKE(%%s, %%s, %s)' % match_option
|
|
|
|
|
|
|
|
def regex_lookup(self, lookup_type):
|
|
|
|
# If regex_lookup is called before it's been initialized, then create
|
|
|
|
# a cursor to initialize it and recur.
|
2011-04-19 05:59:20 +08:00
|
|
|
self.connection.cursor()
|
|
|
|
return self.connection.ops.regex_lookup(lookup_type)
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
|
2009-03-13 07:41:27 +08:00
|
|
|
def return_insert_id(self):
|
|
|
|
return "RETURNING %s INTO %%s", (InsertIdVar(),)
|
|
|
|
|
2009-03-11 02:37:22 +08:00
|
|
|
def savepoint_create_sql(self, sid):
|
2009-08-24 23:45:48 +08:00
|
|
|
return convert_unicode("SAVEPOINT " + self.quote_name(sid))
|
2009-03-11 02:37:22 +08:00
|
|
|
|
|
|
|
def savepoint_rollback_sql(self, sid):
|
2009-08-24 23:45:48 +08:00
|
|
|
return convert_unicode("ROLLBACK TO SAVEPOINT " + self.quote_name(sid))
|
2009-03-11 02:37:22 +08:00
|
|
|
|
2013-06-10 03:04:36 +08:00
|
|
|
def sql_flush(self, style, tables, sequences, allow_cascade=False):
|
2007-08-20 08:15:53 +08:00
|
|
|
# Return a list of 'TRUNCATE x;', 'TRUNCATE y;',
|
|
|
|
# 'TRUNCATE z;'... style SQL statements
|
|
|
|
if tables:
|
|
|
|
# Oracle does support TRUNCATE, but it seems to get us into
|
|
|
|
# FK referential trouble, whereas DELETE FROM table works.
|
2013-06-10 03:04:36 +08:00
|
|
|
sql = ['%s %s %s;' % (
|
|
|
|
style.SQL_KEYWORD('DELETE'),
|
|
|
|
style.SQL_KEYWORD('FROM'),
|
|
|
|
style.SQL_FIELD(self.quote_name(table))
|
|
|
|
) for table in tables]
|
2007-08-20 08:15:53 +08:00
|
|
|
# Since we've just deleted all the rows, running our sequence
|
|
|
|
# ALTER code will reset the sequence to 0.
|
2012-07-25 04:24:16 +08:00
|
|
|
sql.extend(self.sequence_reset_by_name_sql(style, sequences))
|
2007-08-20 08:15:53 +08:00
|
|
|
return sql
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2012-07-25 04:24:16 +08:00
|
|
|
def sequence_reset_by_name_sql(self, style, sequences):
|
|
|
|
sql = []
|
|
|
|
for sequence_info in sequences:
|
|
|
|
sequence_name = self._get_sequence_name(sequence_info['table'])
|
|
|
|
table_name = self.quote_name(sequence_info['table'])
|
|
|
|
column_name = self.quote_name(sequence_info['column'] or 'id')
|
|
|
|
query = _get_sequence_reset_sql() % {'sequence': sequence_name,
|
|
|
|
'table': table_name,
|
|
|
|
'column': column_name}
|
|
|
|
sql.append(query)
|
|
|
|
return sql
|
|
|
|
|
2007-08-20 08:21:10 +08:00
|
|
|
def sequence_reset_sql(self, style, model_list):
|
|
|
|
from django.db import models
|
|
|
|
output = []
|
|
|
|
query = _get_sequence_reset_sql()
|
|
|
|
for model in model_list:
|
2008-07-04 02:42:47 +08:00
|
|
|
for f in model._meta.local_fields:
|
2007-08-20 08:21:10 +08:00
|
|
|
if isinstance(f, models.AutoField):
|
2008-07-04 02:42:47 +08:00
|
|
|
table_name = self.quote_name(model._meta.db_table)
|
2011-04-05 08:19:17 +08:00
|
|
|
sequence_name = self._get_sequence_name(model._meta.db_table)
|
2008-07-04 02:42:47 +08:00
|
|
|
column_name = self.quote_name(f.column)
|
2007-09-15 06:07:54 +08:00
|
|
|
output.append(query % {'sequence': sequence_name,
|
2008-07-04 02:42:47 +08:00
|
|
|
'table': table_name,
|
2007-09-15 06:07:54 +08:00
|
|
|
'column': column_name})
|
2008-12-12 04:12:00 +08:00
|
|
|
# Only one AutoField is allowed per model, so don't
|
|
|
|
# continue to loop
|
|
|
|
break
|
2007-08-20 08:21:10 +08:00
|
|
|
for f in model._meta.many_to_many:
|
2009-07-11 22:22:52 +08:00
|
|
|
if not f.rel.through:
|
|
|
|
table_name = self.quote_name(f.m2m_db_table())
|
2011-04-05 08:19:17 +08:00
|
|
|
sequence_name = self._get_sequence_name(f.m2m_db_table())
|
2009-07-11 22:22:52 +08:00
|
|
|
column_name = self.quote_name('id')
|
|
|
|
output.append(query % {'sequence': sequence_name,
|
|
|
|
'table': table_name,
|
|
|
|
'column': column_name})
|
2007-08-20 08:21:10 +08:00
|
|
|
return output
|
|
|
|
|
2007-08-20 08:24:03 +08:00
|
|
|
def start_transaction_sql(self):
|
|
|
|
return ''
|
|
|
|
|
2007-08-20 08:30:19 +08:00
|
|
|
def tablespace_sql(self, tablespace, inline=False):
|
2011-10-15 05:49:43 +08:00
|
|
|
if inline:
|
|
|
|
return "USING INDEX TABLESPACE %s" % self.quote_name(tablespace)
|
|
|
|
else:
|
|
|
|
return "TABLESPACE %s" % self.quote_name(tablespace)
|
2007-08-20 08:30:19 +08:00
|
|
|
|
2010-11-13 02:39:30 +08:00
|
|
|
def value_to_db_datetime(self, value):
|
2011-11-18 21:01:06 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
|
2010-11-13 02:39:30 +08:00
|
|
|
# Oracle doesn't support tz-aware datetimes
|
2012-02-28 05:15:25 +08:00
|
|
|
if timezone.is_aware(value):
|
2011-11-18 21:01:06 +08:00
|
|
|
if settings.USE_TZ:
|
2012-02-28 05:15:25 +08:00
|
|
|
value = value.astimezone(timezone.utc).replace(tzinfo=None)
|
2011-11-18 21:01:06 +08:00
|
|
|
else:
|
|
|
|
raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")
|
2010-11-13 02:39:30 +08:00
|
|
|
|
2012-07-20 20:48:51 +08:00
|
|
|
return six.text_type(value)
|
2010-11-13 02:39:30 +08:00
|
|
|
|
2008-07-29 13:09:29 +08:00
|
|
|
def value_to_db_time(self, value):
|
|
|
|
if value is None:
|
|
|
|
return None
|
2010-11-13 02:39:30 +08:00
|
|
|
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(value, six.string_types):
|
2011-06-11 02:43:29 +08:00
|
|
|
return datetime.datetime.strptime(value, '%H:%M:%S')
|
2010-11-13 02:39:30 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
# Oracle doesn't support tz-aware times
|
2012-02-28 05:15:25 +08:00
|
|
|
if timezone.is_aware(value):
|
2011-11-18 21:01:06 +08:00
|
|
|
raise ValueError("Oracle backend does not support timezone-aware times.")
|
2010-11-13 02:39:30 +08:00
|
|
|
|
2008-07-29 13:09:29 +08:00
|
|
|
return datetime.datetime(1900, 1, 1, value.hour, value.minute,
|
|
|
|
value.second, value.microsecond)
|
|
|
|
|
|
|
|
def year_lookup_bounds_for_date_field(self, value):
|
|
|
|
first = '%s-01-01'
|
|
|
|
second = '%s-12-31'
|
|
|
|
return [first % value, second % value]
|
|
|
|
|
2013-05-22 06:31:14 +08:00
|
|
|
def year_lookup_bounds_for_datetime_field(self, value):
|
|
|
|
# The default implementation uses datetime objects for the bounds.
|
|
|
|
# This must be overridden here, to use a formatted date (string) as
|
|
|
|
# 'second' instead -- cx_Oracle chops the fraction-of-second part
|
|
|
|
# off of datetime objects, leaving almost an entire second out of
|
|
|
|
# the year under the default implementation.
|
2013-05-27 21:48:28 +08:00
|
|
|
bounds = super(DatabaseOperations, self).year_lookup_bounds_for_datetime_field(value)
|
|
|
|
if settings.USE_TZ:
|
|
|
|
bounds = [b.astimezone(timezone.utc).replace(tzinfo=None) for b in bounds]
|
|
|
|
return [b.isoformat(b' ') for b in bounds]
|
2013-05-22 06:31:14 +08:00
|
|
|
|
2009-02-24 19:15:31 +08:00
|
|
|
def combine_expression(self, connector, sub_expressions):
|
|
|
|
"Oracle requires special cases for %% and & operators in query expressions"
|
|
|
|
if connector == '%%':
|
|
|
|
return 'MOD(%s)' % ','.join(sub_expressions)
|
|
|
|
elif connector == '&':
|
|
|
|
return 'BITAND(%s)' % ','.join(sub_expressions)
|
|
|
|
elif connector == '|':
|
|
|
|
raise NotImplementedError("Bit-wise or is not supported in Oracle.")
|
2013-02-22 06:02:18 +08:00
|
|
|
elif connector == '^':
|
|
|
|
return 'POWER(%s)' % ','.join(sub_expressions)
|
2009-02-24 19:15:31 +08:00
|
|
|
return super(DatabaseOperations, self).combine_expression(connector, sub_expressions)
|
|
|
|
|
2011-04-05 08:19:17 +08:00
|
|
|
def _get_sequence_name(self, table):
|
|
|
|
name_length = self.max_name_length() - 3
|
2013-09-17 00:52:05 +08:00
|
|
|
return '%s_SQ' % backend_utils.truncate_name(table, name_length).upper()
|
2011-04-05 08:19:17 +08:00
|
|
|
|
|
|
|
def _get_trigger_name(self, table):
|
|
|
|
name_length = self.max_name_length() - 3
|
2013-09-17 00:52:05 +08:00
|
|
|
return '%s_TR' % backend_utils.truncate_name(table, name_length).upper()
|
2011-04-05 08:19:17 +08:00
|
|
|
|
2011-09-12 07:02:53 +08:00
|
|
|
def bulk_insert_sql(self, fields, num_values):
|
|
|
|
items_sql = "SELECT %s FROM DUAL" % ", ".join(["%s"] * len(fields))
|
|
|
|
return " UNION ALL ".join([items_sql] * num_values)
|
|
|
|
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2011-01-25 05:34:18 +08:00
|
|
|
class _UninitializedOperatorsDescriptor(object):
|
|
|
|
|
|
|
|
def __get__(self, instance, owner):
|
|
|
|
# If connection.operators is looked up before a connection has been
|
|
|
|
# created, transparently initialize connection.operators to avert an
|
|
|
|
# AttributeError.
|
|
|
|
if instance is None:
|
|
|
|
raise AttributeError("operators not available as class attribute")
|
|
|
|
# Creating a cursor will initialize the operators.
|
|
|
|
instance.cursor().close()
|
|
|
|
return instance.__dict__['operators']
|
|
|
|
|
|
|
|
|
2007-08-20 05:30:57 +08:00
|
|
|
class DatabaseWrapper(BaseDatabaseWrapper):
|
2010-10-11 20:55:17 +08:00
|
|
|
vendor = 'oracle'
|
2011-01-25 05:34:18 +08:00
|
|
|
operators = _UninitializedOperatorsDescriptor()
|
|
|
|
|
|
|
|
_standard_operators = {
|
2007-08-20 11:26:55 +08:00
|
|
|
'exact': '= %s',
|
|
|
|
'iexact': '= UPPER(%s)',
|
2010-01-26 03:28:36 +08:00
|
|
|
'contains': "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
|
|
|
|
'icontains': "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
|
2007-08-20 11:26:55 +08:00
|
|
|
'gt': '> %s',
|
|
|
|
'gte': '>= %s',
|
|
|
|
'lt': '< %s',
|
|
|
|
'lte': '<= %s',
|
2010-01-26 03:28:36 +08:00
|
|
|
'startswith': "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
|
|
|
|
'endswith': "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
|
|
|
|
'istartswith': "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
|
|
|
|
'iendswith': "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
|
2007-08-20 11:26:55 +08:00
|
|
|
}
|
2007-08-20 06:29:57 +08:00
|
|
|
|
2011-01-25 05:34:18 +08:00
|
|
|
_likec_operators = _standard_operators.copy()
|
|
|
|
_likec_operators.update({
|
|
|
|
'contains': "LIKEC %s ESCAPE '\\'",
|
|
|
|
'icontains': "LIKEC UPPER(%s) ESCAPE '\\'",
|
|
|
|
'startswith': "LIKEC %s ESCAPE '\\'",
|
|
|
|
'endswith': "LIKEC %s ESCAPE '\\'",
|
|
|
|
'istartswith': "LIKEC UPPER(%s) ESCAPE '\\'",
|
|
|
|
'iendswith': "LIKEC UPPER(%s) ESCAPE '\\'",
|
|
|
|
})
|
|
|
|
|
Refactored database exceptions wrapping.
Squashed commit of the following:
commit 2181d833ed1a2e422494738dcef311164c4e097e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Wed Feb 27 14:28:39 2013 +0100
Fixed #15901 -- Wrapped all PEP-249 exceptions.
commit 5476a5d93c19aa2f928c497d39ce6e33f52694e2
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:26:52 2013 +0100
Added PEP 3134 exception chaining.
Thanks Jacob Kaplan-Moss for the suggestion.
commit 9365fad0a650328002fb424457d675a273c95802
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:13:49 2013 +0100
Improved API for wrapping database errors.
Thanks Alex Gaynor for the proposal.
commit 1b463b765f2826f73a8d9266795cd5da4f8d5e9e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 15:00:39 2013 +0100
Removed redundant exception wrapping.
This is now taken care of by the cursor wrapper.
commit 524bc7345a724bf526bdd2dd1bcf5ede67d6bb5c
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:55:10 2013 +0100
Wrapped database exceptions in the base backend.
This covers the most common PEP-249 APIs:
- Connection APIs: close(), commit(), rollback(), cursor()
- Cursor APIs: callproc(), close(), execute(), executemany(),
fetchone(), fetchmany(), fetchall(), nextset().
Fixed #19920.
commit a66746bb5f0839f35543222787fce3b6a0d0a3ea
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:53:34 2013 +0100
Added a wrap_database_exception context manager and decorator.
It re-throws backend-specific exceptions using Django's common wrappers.
2013-02-26 21:53:34 +08:00
|
|
|
Database = Database
|
|
|
|
|
2008-08-25 04:16:56 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
2008-08-11 20:11:25 +08:00
|
|
|
super(DatabaseWrapper, self).__init__(*args, **kwargs)
|
|
|
|
|
2010-10-11 20:55:17 +08:00
|
|
|
self.features = DatabaseFeatures(self)
|
2010-12-02 07:36:56 +08:00
|
|
|
use_returning_into = self.settings_dict["OPTIONS"].get('use_returning_into', True)
|
|
|
|
self.features.can_return_id_from_insert = use_returning_into
|
2011-04-05 08:19:17 +08:00
|
|
|
self.ops = DatabaseOperations(self)
|
2009-03-11 11:39:34 +08:00
|
|
|
self.client = DatabaseClient(self)
|
2008-08-11 20:11:25 +08:00
|
|
|
self.creation = DatabaseCreation(self)
|
|
|
|
self.introspection = DatabaseIntrospection(self)
|
2009-12-22 23:18:51 +08:00
|
|
|
self.validation = BaseDatabaseValidation(self)
|
2008-08-11 20:11:25 +08:00
|
|
|
|
2009-03-11 11:39:34 +08:00
|
|
|
def _connect_string(self):
|
|
|
|
settings_dict = self.settings_dict
|
2010-11-11 13:17:31 +08:00
|
|
|
if not settings_dict['HOST'].strip():
|
2009-12-22 23:18:51 +08:00
|
|
|
settings_dict['HOST'] = 'localhost'
|
2010-11-11 13:07:32 +08:00
|
|
|
if settings_dict['PORT'].strip():
|
2009-12-22 23:18:51 +08:00
|
|
|
dsn = Database.makedsn(settings_dict['HOST'],
|
|
|
|
int(settings_dict['PORT']),
|
|
|
|
settings_dict['NAME'])
|
2009-01-08 13:12:14 +08:00
|
|
|
else:
|
2009-12-22 23:18:51 +08:00
|
|
|
dsn = settings_dict['NAME']
|
|
|
|
return "%s/%s@%s" % (settings_dict['USER'],
|
|
|
|
settings_dict['PASSWORD'], dsn)
|
2009-01-08 13:12:14 +08:00
|
|
|
|
2012-11-27 04:42:27 +08:00
|
|
|
def get_connection_params(self):
|
|
|
|
conn_params = self.settings_dict['OPTIONS'].copy()
|
|
|
|
if 'use_returning_into' in conn_params:
|
|
|
|
del conn_params['use_returning_into']
|
|
|
|
return conn_params
|
|
|
|
|
|
|
|
def get_new_connection(self, conn_params):
|
|
|
|
conn_string = convert_unicode(self._connect_string())
|
|
|
|
return Database.connect(conn_string, **conn_params)
|
|
|
|
|
|
|
|
def init_connection_state(self):
|
2013-02-19 00:12:42 +08:00
|
|
|
cursor = self.create_cursor()
|
2012-11-27 04:42:27 +08:00
|
|
|
# Set the territory first. The territory overrides NLS_DATE_FORMAT
|
|
|
|
# and NLS_TIMESTAMP_FORMAT to the territory default. When all of
|
|
|
|
# these are set in single statement it isn't clear what is supposed
|
|
|
|
# to happen.
|
|
|
|
cursor.execute("ALTER SESSION SET NLS_TERRITORY = 'AMERICA'")
|
|
|
|
# Set oracle date to ansi date format. This only needs to execute
|
|
|
|
# once when we create a new connection. We also set the Territory
|
|
|
|
# to 'AMERICA' which forces Sunday to evaluate to a '1' in
|
|
|
|
# TO_CHAR().
|
|
|
|
cursor.execute(
|
|
|
|
"ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'"
|
|
|
|
" NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'"
|
|
|
|
+ (" TIME_ZONE = 'UTC'" if settings.USE_TZ else ''))
|
|
|
|
cursor.close()
|
|
|
|
if 'operators' not in self.__dict__:
|
|
|
|
# Ticket #14149: Check whether our LIKE implementation will
|
|
|
|
# work for this connection or we need to fall back on LIKEC.
|
|
|
|
# This check is performed only once per DatabaseWrapper
|
|
|
|
# instance per thread, since subsequent connections will use
|
|
|
|
# the same settings.
|
2013-02-19 00:12:42 +08:00
|
|
|
cursor = self.create_cursor()
|
2012-11-27 04:42:27 +08:00
|
|
|
try:
|
|
|
|
cursor.execute("SELECT 1 FROM DUAL WHERE DUMMY %s"
|
|
|
|
% self._standard_operators['contains'],
|
|
|
|
['X'])
|
2013-09-02 18:06:32 +08:00
|
|
|
except DatabaseError:
|
2012-11-27 04:42:27 +08:00
|
|
|
self.operators = self._likec_operators
|
|
|
|
else:
|
|
|
|
self.operators = self._standard_operators
|
|
|
|
cursor.close()
|
|
|
|
|
2013-02-19 17:50:22 +08:00
|
|
|
# There's no way for the DatabaseOperations class to know the
|
|
|
|
# currently active Oracle version, so we do some setups here.
|
|
|
|
# TODO: Multi-db support will need a better solution (a way to
|
|
|
|
# communicate the current version).
|
|
|
|
if self.oracle_version is not None and self.oracle_version <= 9:
|
|
|
|
self.ops.regex_lookup = self.ops.regex_lookup_9
|
|
|
|
else:
|
|
|
|
self.ops.regex_lookup = self.ops.regex_lookup_10
|
|
|
|
|
2012-11-27 04:42:27 +08:00
|
|
|
try:
|
|
|
|
self.connection.stmtcachesize = 20
|
2013-09-30 23:55:14 +08:00
|
|
|
except AttributeError:
|
2012-11-27 04:42:27 +08:00
|
|
|
# Django docs specify cx_Oracle version 4.3.1 or higher, but
|
|
|
|
# stmtcachesize is available only in 4.3.2 and up.
|
|
|
|
pass
|
|
|
|
|
2013-03-02 19:12:51 +08:00
|
|
|
def create_cursor(self):
|
|
|
|
return FormatStylePlaceholderCursor(self.connection)
|
2009-03-11 02:37:22 +08:00
|
|
|
|
2010-11-11 12:36:20 +08:00
|
|
|
def _commit(self):
|
|
|
|
if self.connection is not None:
|
|
|
|
try:
|
|
|
|
return self.connection.commit()
|
2012-04-29 00:09:37 +08:00
|
|
|
except Database.DatabaseError as e:
|
2010-11-11 12:36:20 +08:00
|
|
|
# cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception
|
|
|
|
# with the following attributes and values:
|
|
|
|
# code = 2091
|
|
|
|
# message = 'ORA-02091: transaction rolled back
|
|
|
|
# 'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS
|
|
|
|
# _C00102056) violated - parent key not found'
|
|
|
|
# We convert that particular case to our IntegrityError exception
|
|
|
|
x = e.args[0]
|
|
|
|
if hasattr(x, 'code') and hasattr(x, 'message') \
|
|
|
|
and x.code == 2091 and 'ORA-02291' in x.message:
|
2012-07-22 03:06:13 +08:00
|
|
|
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
|
Refactored database exceptions wrapping.
Squashed commit of the following:
commit 2181d833ed1a2e422494738dcef311164c4e097e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Wed Feb 27 14:28:39 2013 +0100
Fixed #15901 -- Wrapped all PEP-249 exceptions.
commit 5476a5d93c19aa2f928c497d39ce6e33f52694e2
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:26:52 2013 +0100
Added PEP 3134 exception chaining.
Thanks Jacob Kaplan-Moss for the suggestion.
commit 9365fad0a650328002fb424457d675a273c95802
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:13:49 2013 +0100
Improved API for wrapping database errors.
Thanks Alex Gaynor for the proposal.
commit 1b463b765f2826f73a8d9266795cd5da4f8d5e9e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 15:00:39 2013 +0100
Removed redundant exception wrapping.
This is now taken care of by the cursor wrapper.
commit 524bc7345a724bf526bdd2dd1bcf5ede67d6bb5c
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:55:10 2013 +0100
Wrapped database exceptions in the base backend.
This covers the most common PEP-249 APIs:
- Connection APIs: close(), commit(), rollback(), cursor()
- Cursor APIs: callproc(), close(), execute(), executemany(),
fetchone(), fetchmany(), fetchall(), nextset().
Fixed #19920.
commit a66746bb5f0839f35543222787fce3b6a0d0a3ea
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:53:34 2013 +0100
Added a wrap_database_exception context manager and decorator.
It re-throws backend-specific exceptions using Django's common wrappers.
2013-02-26 21:53:34 +08:00
|
|
|
raise
|
2013-09-02 18:06:32 +08:00
|
|
|
|
2013-09-07 04:27:51 +08:00
|
|
|
def schema_editor(self, *args, **kwargs):
|
2012-09-08 03:48:22 +08:00
|
|
|
"Returns a new instance of this backend's SchemaEditor"
|
2013-09-07 04:27:51 +08:00
|
|
|
return DatabaseSchemaEditor(self, *args, **kwargs)
|
2010-11-11 12:36:20 +08:00
|
|
|
|
2013-03-02 19:12:51 +08:00
|
|
|
# Oracle doesn't support savepoint commits. Ignore them.
|
|
|
|
def _savepoint_commit(self, sid):
|
|
|
|
pass
|
|
|
|
|
2013-03-02 20:47:46 +08:00
|
|
|
def _set_autocommit(self, autocommit):
|
|
|
|
self.connection.autocommit = autocommit
|
|
|
|
|
2013-03-02 19:12:51 +08:00
|
|
|
def check_constraints(self, table_names=None):
|
|
|
|
"""
|
|
|
|
To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they
|
|
|
|
are returned to deferred.
|
|
|
|
"""
|
|
|
|
self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
|
|
|
|
self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
|
|
|
|
|
|
|
|
def is_usable(self):
|
|
|
|
try:
|
|
|
|
if hasattr(self.connection, 'ping'): # Oracle 10g R2 and higher
|
|
|
|
self.connection.ping()
|
|
|
|
else:
|
|
|
|
# Use a cx_Oracle cursor directly, bypassing Django's utilities.
|
|
|
|
self.connection.cursor().execute("SELECT 1 FROM DUAL")
|
|
|
|
except DatabaseError:
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
|
2013-02-19 17:50:22 +08:00
|
|
|
@cached_property
|
|
|
|
def oracle_version(self):
|
2013-02-19 17:51:24 +08:00
|
|
|
with self.temporary_connection():
|
|
|
|
version = self.connection.version
|
2013-02-19 17:50:22 +08:00
|
|
|
try:
|
2013-02-19 17:51:24 +08:00
|
|
|
return int(version.split('.')[0])
|
2013-02-19 17:50:22 +08:00
|
|
|
except ValueError:
|
|
|
|
return None
|
|
|
|
|
2008-08-25 04:16:56 +08:00
|
|
|
|
2008-07-30 09:29:31 +08:00
|
|
|
class OracleParam(object):
|
|
|
|
"""
|
|
|
|
Wrapper object for formatting parameters for Oracle. If the string
|
|
|
|
representation of the value is large enough (greater than 4000 characters)
|
2009-07-22 05:20:18 +08:00
|
|
|
the input size needs to be set as CLOB. Alternatively, if the parameter
|
2008-12-12 04:12:00 +08:00
|
|
|
has an `input_size` attribute, then the value of the `input_size` attribute
|
|
|
|
will be used instead. Otherwise, no input size will be set for the
|
|
|
|
parameter when executing the query.
|
2008-07-30 09:29:31 +08:00
|
|
|
"""
|
2008-12-12 04:12:00 +08:00
|
|
|
|
2009-03-13 07:41:27 +08:00
|
|
|
def __init__(self, param, cursor, strings_only=False):
|
2012-02-28 05:15:25 +08:00
|
|
|
# With raw SQL queries, datetimes can reach this function
|
|
|
|
# without being converted by DateTimeField.get_db_prep_value.
|
|
|
|
if settings.USE_TZ and isinstance(param, datetime.datetime):
|
|
|
|
if timezone.is_naive(param):
|
2012-06-08 00:08:47 +08:00
|
|
|
warnings.warn("Oracle received a naive datetime (%s)"
|
|
|
|
" while time zone support is active." % param,
|
2012-02-28 05:15:25 +08:00
|
|
|
RuntimeWarning)
|
|
|
|
default_timezone = timezone.get_default_timezone()
|
|
|
|
param = timezone.make_aware(param, default_timezone)
|
|
|
|
param = param.astimezone(timezone.utc).replace(tzinfo=None)
|
|
|
|
|
2012-08-20 02:15:52 +08:00
|
|
|
# Oracle doesn't recognize True and False correctly in Python 3.
|
|
|
|
# The conversion done below works both in 2 and 3.
|
|
|
|
if param is True:
|
|
|
|
param = "1"
|
|
|
|
elif param is False:
|
|
|
|
param = "0"
|
2009-03-13 07:41:27 +08:00
|
|
|
if hasattr(param, 'bind_parameter'):
|
2012-08-29 02:59:56 +08:00
|
|
|
self.force_bytes = param.bind_parameter(cursor)
|
2013-03-10 06:39:14 +08:00
|
|
|
elif isinstance(param, six.memoryview):
|
|
|
|
self.force_bytes = param
|
2009-03-13 07:41:27 +08:00
|
|
|
else:
|
2012-08-29 02:59:56 +08:00
|
|
|
self.force_bytes = convert_unicode(param, cursor.charset,
|
2009-08-24 23:45:48 +08:00
|
|
|
strings_only)
|
2008-07-30 09:29:31 +08:00
|
|
|
if hasattr(param, 'input_size'):
|
|
|
|
# If parameter has `input_size` attribute, use that.
|
|
|
|
self.input_size = param.input_size
|
2012-07-20 20:22:00 +08:00
|
|
|
elif isinstance(param, six.string_types) and len(param) > 4000:
|
2009-07-22 05:20:18 +08:00
|
|
|
# Mark any string param greater than 4000 characters as a CLOB.
|
|
|
|
self.input_size = Database.CLOB
|
2008-07-30 09:29:31 +08:00
|
|
|
else:
|
|
|
|
self.input_size = None
|
|
|
|
|
2008-08-25 04:16:56 +08:00
|
|
|
|
2010-04-29 01:08:06 +08:00
|
|
|
class VariableWrapper(object):
|
|
|
|
"""
|
|
|
|
An adapter class for cursor variables that prevents the wrapped object
|
|
|
|
from being converted into a string when used to instanciate an OracleParam.
|
|
|
|
This can be used generally for any other object that should be passed into
|
|
|
|
Cursor.execute as-is.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, var):
|
|
|
|
self.var = var
|
|
|
|
|
|
|
|
def bind_parameter(self, cursor):
|
|
|
|
return self.var
|
|
|
|
|
|
|
|
def __getattr__(self, key):
|
|
|
|
return getattr(self.var, key)
|
|
|
|
|
|
|
|
def __setattr__(self, key, value):
|
|
|
|
if key == 'var':
|
|
|
|
self.__dict__[key] = value
|
|
|
|
else:
|
|
|
|
setattr(self.var, key, value)
|
|
|
|
|
|
|
|
|
2009-03-13 07:41:27 +08:00
|
|
|
class InsertIdVar(object):
|
|
|
|
"""
|
|
|
|
A late-binding cursor variable that can be passed to Cursor.execute
|
|
|
|
as a parameter, in order to receive the id of the row created by an
|
|
|
|
insert statement.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def bind_parameter(self, cursor):
|
2010-04-29 01:08:06 +08:00
|
|
|
param = cursor.cursor.var(Database.NUMBER)
|
2009-03-13 07:41:27 +08:00
|
|
|
cursor._insert_id_var = param
|
|
|
|
return param
|
|
|
|
|
|
|
|
|
2009-01-17 06:23:58 +08:00
|
|
|
class FormatStylePlaceholderCursor(object):
|
2006-05-26 13:37:21 +08:00
|
|
|
"""
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
Django uses "format" (e.g. '%s') style placeholders, but Oracle uses ":var"
|
|
|
|
style. This fixes it -- but note that if you want to use a literal "%s" in
|
|
|
|
a query, you'll need to use "%%s".
|
|
|
|
|
|
|
|
We also do automatic conversion between Unicode on the Python side and
|
|
|
|
UTF-8 -- for talking to Oracle -- in here.
|
2006-05-26 13:37:21 +08:00
|
|
|
"""
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
charset = 'utf-8'
|
|
|
|
|
2009-01-17 06:23:58 +08:00
|
|
|
def __init__(self, connection):
|
|
|
|
self.cursor = connection.cursor()
|
|
|
|
# Necessary to retrieve decimal values without rounding error.
|
|
|
|
self.cursor.numbersAsStrings = True
|
|
|
|
# Default arraysize of 1 is highly sub-optimal.
|
|
|
|
self.cursor.arraysize = 100
|
|
|
|
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
def _format_params(self, params):
|
2013-06-28 11:15:03 +08:00
|
|
|
try:
|
2013-07-08 08:39:54 +08:00
|
|
|
return dict((k, OracleParam(v, self, True)) for k, v in params.items())
|
2013-06-28 11:15:03 +08:00
|
|
|
except AttributeError:
|
2013-08-30 00:09:35 +08:00
|
|
|
return tuple(OracleParam(p, self, True) for p in params)
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2007-12-11 10:22:40 +08:00
|
|
|
def _guess_input_sizes(self, params_list):
|
2013-06-28 11:15:03 +08:00
|
|
|
# Try dict handling; if that fails, treat as sequence
|
|
|
|
if hasattr(params_list[0], 'keys'):
|
|
|
|
sizes = {}
|
|
|
|
for params in params_list:
|
|
|
|
for k, value in params.items():
|
|
|
|
if value.input_size:
|
|
|
|
sizes[k] = value.input_size
|
|
|
|
self.setinputsizes(**sizes)
|
|
|
|
else:
|
|
|
|
# It's not a list of dicts; it's a list of sequences
|
|
|
|
sizes = [None] * len(params_list[0])
|
|
|
|
for params in params_list:
|
|
|
|
for i, value in enumerate(params):
|
|
|
|
if value.input_size:
|
|
|
|
sizes[i] = value.input_size
|
2013-07-08 08:39:54 +08:00
|
|
|
self.setinputsizes(*sizes)
|
2007-12-11 10:22:40 +08:00
|
|
|
|
2008-07-30 09:29:31 +08:00
|
|
|
def _param_generator(self, params):
|
2013-06-28 11:15:03 +08:00
|
|
|
# Try dict handling; if that fails, treat as sequence
|
|
|
|
if hasattr(params, 'items'):
|
2013-07-08 08:39:54 +08:00
|
|
|
return dict((k, v.force_bytes) for k, v in params.items())
|
2013-06-28 11:15:03 +08:00
|
|
|
else:
|
|
|
|
return [p.force_bytes for p in params]
|
2008-07-30 09:29:31 +08:00
|
|
|
|
2013-06-28 11:15:03 +08:00
|
|
|
def _fix_for_params(self, query, params):
|
2007-09-15 05:32:25 +08:00
|
|
|
# cx_Oracle wants no trailing ';' for SQL statements. For PL/SQL, it
|
|
|
|
# it does want a trailing ';' but not a trailing '/'. However, these
|
|
|
|
# characters must be included in the original query in case the query
|
|
|
|
# is being passed to SQL*Plus.
|
|
|
|
if query.endswith(';') or query.endswith('/'):
|
|
|
|
query = query[:-1]
|
2013-03-23 23:09:56 +08:00
|
|
|
if params is None:
|
|
|
|
params = []
|
|
|
|
query = convert_unicode(query, self.charset)
|
2013-06-28 11:15:03 +08:00
|
|
|
elif hasattr(params, 'keys'):
|
|
|
|
# Handle params as dict
|
2013-07-08 08:39:54 +08:00
|
|
|
args = dict((k, ":%s" % k) for k in params.keys())
|
2013-06-28 11:15:03 +08:00
|
|
|
query = convert_unicode(query % args, self.charset)
|
2013-03-23 23:09:56 +08:00
|
|
|
else:
|
2013-06-28 11:15:03 +08:00
|
|
|
# Handle params as sequence
|
2013-03-23 23:09:56 +08:00
|
|
|
args = [(':arg%d' % i) for i in range(len(params))]
|
|
|
|
query = convert_unicode(query % tuple(args), self.charset)
|
2013-06-28 11:15:03 +08:00
|
|
|
return query, self._format_params(params)
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2013-06-28 11:15:03 +08:00
|
|
|
def execute(self, query, params=None):
|
|
|
|
query, params = self._fix_for_params(query, params)
|
2007-12-11 10:22:40 +08:00
|
|
|
self._guess_input_sizes([params])
|
2008-08-26 01:20:28 +08:00
|
|
|
try:
|
2009-01-17 06:23:58 +08:00
|
|
|
return self.cursor.execute(query, self._param_generator(params))
|
2012-04-29 00:09:37 +08:00
|
|
|
except Database.DatabaseError as e:
|
2008-08-26 01:20:28 +08:00
|
|
|
# cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
|
2010-04-29 01:08:06 +08:00
|
|
|
if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
|
2012-07-22 03:06:13 +08:00
|
|
|
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
|
Refactored database exceptions wrapping.
Squashed commit of the following:
commit 2181d833ed1a2e422494738dcef311164c4e097e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Wed Feb 27 14:28:39 2013 +0100
Fixed #15901 -- Wrapped all PEP-249 exceptions.
commit 5476a5d93c19aa2f928c497d39ce6e33f52694e2
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:26:52 2013 +0100
Added PEP 3134 exception chaining.
Thanks Jacob Kaplan-Moss for the suggestion.
commit 9365fad0a650328002fb424457d675a273c95802
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:13:49 2013 +0100
Improved API for wrapping database errors.
Thanks Alex Gaynor for the proposal.
commit 1b463b765f2826f73a8d9266795cd5da4f8d5e9e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 15:00:39 2013 +0100
Removed redundant exception wrapping.
This is now taken care of by the cursor wrapper.
commit 524bc7345a724bf526bdd2dd1bcf5ede67d6bb5c
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:55:10 2013 +0100
Wrapped database exceptions in the base backend.
This covers the most common PEP-249 APIs:
- Connection APIs: close(), commit(), rollback(), cursor()
- Cursor APIs: callproc(), close(), execute(), executemany(),
fetchone(), fetchmany(), fetchall(), nextset().
Fixed #19920.
commit a66746bb5f0839f35543222787fce3b6a0d0a3ea
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:53:34 2013 +0100
Added a wrap_database_exception context manager and decorator.
It re-throws backend-specific exceptions using Django's common wrappers.
2013-02-26 21:53:34 +08:00
|
|
|
raise
|
2006-05-26 13:37:21 +08:00
|
|
|
|
2006-06-03 21:37:34 +08:00
|
|
|
def executemany(self, query, params=None):
|
2013-06-28 11:15:03 +08:00
|
|
|
if not params:
|
2008-12-12 04:12:00 +08:00
|
|
|
# No params given, nothing to do
|
|
|
|
return None
|
2013-06-28 11:15:03 +08:00
|
|
|
# uniform treatment for sequences and iterables
|
|
|
|
params_iter = iter(params)
|
|
|
|
query, firstparams = self._fix_for_params(query, next(params_iter))
|
2013-07-08 08:39:54 +08:00
|
|
|
# we build a list of formatted params; as we're going to traverse it
|
2013-06-28 11:15:03 +08:00
|
|
|
# more than once, we can't make it lazy by using a generator
|
2013-07-08 08:39:54 +08:00
|
|
|
formatted = [firstparams] + [self._format_params(p) for p in params_iter]
|
2008-07-30 09:29:31 +08:00
|
|
|
self._guess_input_sizes(formatted)
|
2008-08-26 01:20:28 +08:00
|
|
|
try:
|
2009-01-17 06:23:58 +08:00
|
|
|
return self.cursor.executemany(query,
|
2008-12-12 04:12:00 +08:00
|
|
|
[self._param_generator(p) for p in formatted])
|
2012-04-29 00:09:37 +08:00
|
|
|
except Database.DatabaseError as e:
|
2008-08-26 01:20:28 +08:00
|
|
|
# cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
|
2010-04-29 01:08:06 +08:00
|
|
|
if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
|
2012-07-22 03:06:13 +08:00
|
|
|
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
|
Refactored database exceptions wrapping.
Squashed commit of the following:
commit 2181d833ed1a2e422494738dcef311164c4e097e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Wed Feb 27 14:28:39 2013 +0100
Fixed #15901 -- Wrapped all PEP-249 exceptions.
commit 5476a5d93c19aa2f928c497d39ce6e33f52694e2
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:26:52 2013 +0100
Added PEP 3134 exception chaining.
Thanks Jacob Kaplan-Moss for the suggestion.
commit 9365fad0a650328002fb424457d675a273c95802
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:13:49 2013 +0100
Improved API for wrapping database errors.
Thanks Alex Gaynor for the proposal.
commit 1b463b765f2826f73a8d9266795cd5da4f8d5e9e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 15:00:39 2013 +0100
Removed redundant exception wrapping.
This is now taken care of by the cursor wrapper.
commit 524bc7345a724bf526bdd2dd1bcf5ede67d6bb5c
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:55:10 2013 +0100
Wrapped database exceptions in the base backend.
This covers the most common PEP-249 APIs:
- Connection APIs: close(), commit(), rollback(), cursor()
- Cursor APIs: callproc(), close(), execute(), executemany(),
fetchone(), fetchmany(), fetchall(), nextset().
Fixed #19920.
commit a66746bb5f0839f35543222787fce3b6a0d0a3ea
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:53:34 2013 +0100
Added a wrap_database_exception context manager and decorator.
It re-throws backend-specific exceptions using Django's common wrappers.
2013-02-26 21:53:34 +08:00
|
|
|
raise
|
2006-05-26 13:37:21 +08:00
|
|
|
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
def fetchone(self):
|
2009-01-17 06:23:58 +08:00
|
|
|
row = self.cursor.fetchone()
|
2008-01-05 06:51:22 +08:00
|
|
|
if row is None:
|
|
|
|
return row
|
2009-12-23 05:05:15 +08:00
|
|
|
return _rowfactory(row, self.cursor)
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
|
|
|
def fetchmany(self, size=None):
|
|
|
|
if size is None:
|
|
|
|
size = self.arraysize
|
2013-08-30 07:20:00 +08:00
|
|
|
return tuple(_rowfactory(r, self.cursor)
|
|
|
|
for r in self.cursor.fetchmany(size))
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
|
|
|
def fetchall(self):
|
2013-08-30 07:20:00 +08:00
|
|
|
return tuple(_rowfactory(r, self.cursor)
|
|
|
|
for r in self.cursor.fetchall())
|
2008-12-12 04:12:00 +08:00
|
|
|
|
2010-04-29 01:08:06 +08:00
|
|
|
def var(self, *args):
|
|
|
|
return VariableWrapper(self.cursor.var(*args))
|
|
|
|
|
|
|
|
def arrayvar(self, *args):
|
|
|
|
return VariableWrapper(self.cursor.arrayvar(*args))
|
|
|
|
|
2009-01-17 06:23:58 +08:00
|
|
|
def __getattr__(self, attr):
|
|
|
|
if attr in self.__dict__:
|
|
|
|
return self.__dict__[attr]
|
|
|
|
else:
|
|
|
|
return getattr(self.cursor, attr)
|
|
|
|
|
|
|
|
def __iter__(self):
|
2009-12-23 05:05:15 +08:00
|
|
|
return CursorIterator(self.cursor)
|
|
|
|
|
|
|
|
|
2012-11-04 04:43:11 +08:00
|
|
|
class CursorIterator(six.Iterator):
|
2009-12-23 05:05:15 +08:00
|
|
|
|
|
|
|
"""Cursor iterator wrapper that invokes our custom row factory."""
|
|
|
|
|
|
|
|
def __init__(self, cursor):
|
|
|
|
self.cursor = cursor
|
|
|
|
self.iter = iter(cursor)
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
return self
|
|
|
|
|
2012-08-09 20:36:05 +08:00
|
|
|
def __next__(self):
|
2012-05-11 02:14:04 +08:00
|
|
|
return _rowfactory(next(self.iter), self.cursor)
|
2009-12-23 05:05:15 +08:00
|
|
|
|
|
|
|
|
|
|
|
def _rowfactory(row, cursor):
|
|
|
|
# Cast numeric values as the appropriate Python type based upon the
|
|
|
|
# cursor description, and convert strings to unicode.
|
|
|
|
casted = []
|
|
|
|
for value, desc in zip(row, cursor.description):
|
|
|
|
if value is not None and desc[1] is Database.NUMBER:
|
|
|
|
precision, scale = desc[4:6]
|
|
|
|
if scale == -127:
|
|
|
|
if precision == 0:
|
|
|
|
# NUMBER column: decimal-precision floating point
|
|
|
|
# This will normally be an integer from a sequence,
|
|
|
|
# but it could be a decimal value.
|
|
|
|
if '.' in value:
|
2011-07-13 17:35:51 +08:00
|
|
|
value = decimal.Decimal(value)
|
2009-12-23 05:05:15 +08:00
|
|
|
else:
|
|
|
|
value = int(value)
|
|
|
|
else:
|
|
|
|
# FLOAT column: binary-precision floating point.
|
|
|
|
# This comes from FloatField columns.
|
|
|
|
value = float(value)
|
|
|
|
elif precision > 0:
|
|
|
|
# NUMBER(p,s) column: decimal-precision fixed point.
|
|
|
|
# This comes from IntField and DecimalField columns.
|
|
|
|
if scale == 0:
|
|
|
|
value = int(value)
|
|
|
|
else:
|
2011-07-13 17:35:51 +08:00
|
|
|
value = decimal.Decimal(value)
|
2009-12-23 05:05:15 +08:00
|
|
|
elif '.' in value:
|
|
|
|
# No type information. This normally comes from a
|
|
|
|
# mathematical expression in the SELECT list. Guess int
|
|
|
|
# or Decimal based on whether it has a decimal point.
|
2011-07-13 17:35:51 +08:00
|
|
|
value = decimal.Decimal(value)
|
2009-12-23 05:05:15 +08:00
|
|
|
else:
|
|
|
|
value = int(value)
|
2011-12-07 16:43:30 +08:00
|
|
|
# datetimes are returned as TIMESTAMP, except the results
|
|
|
|
# of "dates" queries, which are returned as DATETIME.
|
|
|
|
elif desc[1] in (Database.TIMESTAMP, Database.DATETIME):
|
|
|
|
# Confirm that dt is naive before overwriting its tzinfo.
|
2012-02-28 05:15:25 +08:00
|
|
|
if settings.USE_TZ and value is not None and timezone.is_naive(value):
|
|
|
|
value = value.replace(tzinfo=timezone.utc)
|
2009-12-23 05:05:15 +08:00
|
|
|
elif desc[1] in (Database.STRING, Database.FIXED_CHAR,
|
|
|
|
Database.LONG_STRING):
|
|
|
|
value = to_unicode(value)
|
|
|
|
casted.append(value)
|
|
|
|
return tuple(casted)
|
2009-01-17 06:23:58 +08:00
|
|
|
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
|
|
|
def to_unicode(s):
|
|
|
|
"""
|
|
|
|
Convert strings to Unicode objects (and return all other data types
|
|
|
|
unchanged).
|
|
|
|
"""
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(s, six.string_types):
|
2012-07-21 16:00:10 +08:00
|
|
|
return force_text(s)
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
return s
|
|
|
|
|
2008-12-12 04:12:00 +08:00
|
|
|
|
2007-06-23 22:16:00 +08:00
|
|
|
def _get_sequence_reset_sql():
|
|
|
|
# TODO: colorize this SQL code with style.SQL_KEYWORD(), etc.
|
|
|
|
return """
|
2008-12-12 04:12:00 +08:00
|
|
|
DECLARE
|
2010-11-12 09:44:22 +08:00
|
|
|
table_value integer;
|
|
|
|
seq_value integer;
|
2008-12-12 04:12:00 +08:00
|
|
|
BEGIN
|
2010-11-12 09:44:22 +08:00
|
|
|
SELECT NVL(MAX(%(column)s), 0) INTO table_value FROM %(table)s;
|
|
|
|
SELECT NVL(last_number - cache_size, 0) INTO seq_value FROM user_sequences
|
|
|
|
WHERE sequence_name = '%(sequence)s';
|
|
|
|
WHILE table_value > seq_value LOOP
|
|
|
|
SELECT "%(sequence)s".nextval INTO seq_value FROM dual;
|
|
|
|
END LOOP;
|
2008-12-12 04:12:00 +08:00
|
|
|
END;
|
|
|
|
/"""
|