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
|
|
|
"""
|
2013-09-15 03:32:25 +08:00
|
|
|
import datetime
|
2011-07-13 17:35:51 +08:00
|
|
|
import decimal
|
2015-01-13 04:20:40 +08:00
|
|
|
import os
|
2013-07-08 08:39:54 +08:00
|
|
|
import platform
|
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
|
|
|
|
2015-01-13 04:20:40 +08:00
|
|
|
from django.conf import settings
|
2017-01-17 01:48:41 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2015-01-13 04:20:40 +08:00
|
|
|
from django.db import utils
|
|
|
|
from django.db.backends.base.base import BaseDatabaseWrapper
|
|
|
|
from django.utils.encoding import force_bytes, force_text
|
|
|
|
from django.utils.functional import cached_property
|
|
|
|
|
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
|
|
|
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:
|
|
|
|
os.environ.update(environ)
|
|
|
|
|
2016-11-13 01:11:23 +08:00
|
|
|
|
2010-12-03 08:54:39 +08:00
|
|
|
_setup_environment([
|
|
|
|
# Oracle takes client-side character set encoding from the environment.
|
2016-09-13 20:14:49 +08:00
|
|
|
('NLS_LANG', '.AL32UTF8'),
|
2010-12-03 08:54:39 +08:00
|
|
|
# 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:
|
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
|
|
|
|
2015-01-13 04:20:40 +08:00
|
|
|
# Some of these import cx_Oracle, so import them after checking if it's installed.
|
2016-04-04 09:41:37 +08:00
|
|
|
from .client import DatabaseClient # NOQA isort:skip
|
|
|
|
from .creation import DatabaseCreation # NOQA isort:skip
|
|
|
|
from .features import DatabaseFeatures # NOQA isort:skip
|
|
|
|
from .introspection import DatabaseIntrospection # NOQA isort:skip
|
|
|
|
from .operations import DatabaseOperations # NOQA isort:skip
|
|
|
|
from .schema import DatabaseSchemaEditor # NOQA isort:skip
|
2016-12-30 01:45:25 +08:00
|
|
|
from .utils import Oracle_datetime # NOQA isort:skip
|
2017-05-23 23:02:40 +08:00
|
|
|
from .validation import DatabaseValidation # NOQA isort:skip
|
2008-08-22 22:18:53 +08:00
|
|
|
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class _UninitializedOperatorsDescriptor:
|
2011-01-25 05:34:18 +08:00
|
|
|
|
2015-10-26 23:31:16 +08:00
|
|
|
def __get__(self, instance, cls=None):
|
2011-01-25 05:34:18 +08:00
|
|
|
# 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'
|
2017-05-23 21:09:35 +08:00
|
|
|
display_name = 'Oracle'
|
2014-12-30 04:14:40 +08:00
|
|
|
# This dictionary maps Field objects to their associated Oracle column
|
|
|
|
# types, as strings. Column-type strings can contain format strings; they'll
|
|
|
|
# be interpolated against the values of Field.__dict__ before being output.
|
|
|
|
# If a column type is set to None, it won't be included in the output.
|
|
|
|
#
|
|
|
|
# Any format strings starting with "qn_" are quoted before being used in the
|
|
|
|
# output (the "qn_" prefix is stripped before the lookup is performed.
|
|
|
|
data_types = {
|
|
|
|
'AutoField': 'NUMBER(11)',
|
2015-07-02 16:43:15 +08:00
|
|
|
'BigAutoField': 'NUMBER(19)',
|
2014-12-30 04:14:40 +08:00
|
|
|
'BinaryField': 'BLOB',
|
|
|
|
'BooleanField': 'NUMBER(1)',
|
|
|
|
'CharField': 'NVARCHAR2(%(max_length)s)',
|
|
|
|
'DateField': 'DATE',
|
|
|
|
'DateTimeField': 'TIMESTAMP',
|
|
|
|
'DecimalField': 'NUMBER(%(max_digits)s, %(decimal_places)s)',
|
|
|
|
'DurationField': 'INTERVAL DAY(9) TO SECOND(6)',
|
|
|
|
'FileField': 'NVARCHAR2(%(max_length)s)',
|
|
|
|
'FilePathField': 'NVARCHAR2(%(max_length)s)',
|
|
|
|
'FloatField': 'DOUBLE PRECISION',
|
|
|
|
'IntegerField': 'NUMBER(11)',
|
|
|
|
'BigIntegerField': 'NUMBER(19)',
|
|
|
|
'IPAddressField': 'VARCHAR2(15)',
|
|
|
|
'GenericIPAddressField': 'VARCHAR2(39)',
|
|
|
|
'NullBooleanField': 'NUMBER(1)',
|
|
|
|
'OneToOneField': 'NUMBER(11)',
|
|
|
|
'PositiveIntegerField': 'NUMBER(11)',
|
|
|
|
'PositiveSmallIntegerField': 'NUMBER(11)',
|
|
|
|
'SlugField': 'NVARCHAR2(%(max_length)s)',
|
|
|
|
'SmallIntegerField': 'NUMBER(11)',
|
|
|
|
'TextField': 'NCLOB',
|
|
|
|
'TimeField': 'TIMESTAMP',
|
|
|
|
'URLField': 'VARCHAR2(%(max_length)s)',
|
|
|
|
'UUIDField': 'VARCHAR2(32)',
|
|
|
|
}
|
|
|
|
data_type_check_constraints = {
|
|
|
|
'BooleanField': '%(qn_column)s IN (0,1)',
|
|
|
|
'NullBooleanField': '(%(qn_column)s IN (0,1)) OR (%(qn_column)s IS NULL)',
|
|
|
|
'PositiveIntegerField': '%(qn_column)s >= 0',
|
|
|
|
'PositiveSmallIntegerField': '%(qn_column)s >= 0',
|
|
|
|
}
|
|
|
|
|
2017-05-23 23:02:40 +08:00
|
|
|
# Oracle doesn't support a database index on these columns.
|
|
|
|
_limited_data_types = ('clob', 'nclob', 'blob')
|
|
|
|
|
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 '\\'",
|
|
|
|
})
|
|
|
|
|
2014-09-27 18:41:54 +08:00
|
|
|
# The patterns below are used to generate SQL pattern lookup clauses when
|
|
|
|
# the right-hand side of the lookup isn't a raw string (it might be an expression
|
|
|
|
# or the result of a bilateral transformation).
|
|
|
|
# In those cases, special characters for LIKE operators (e.g. \, *, _) should be
|
|
|
|
# escaped on database side.
|
|
|
|
#
|
|
|
|
# Note: we use str.format() here for readability as '%' is used as a wildcard for
|
|
|
|
# the LIKE operator.
|
|
|
|
pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\', '\\'), '%%', '\%%'), '_', '\_')"
|
|
|
|
_pattern_ops = {
|
|
|
|
'contains': "'%%' || {} || '%%'",
|
|
|
|
'icontains': "'%%' || UPPER({}) || '%%'",
|
|
|
|
'startswith': "{} || '%%'",
|
|
|
|
'istartswith': "UPPER({}) || '%%'",
|
|
|
|
'endswith': "'%%' || {}",
|
|
|
|
'iendswith': "'%%' || UPPER({})",
|
|
|
|
}
|
|
|
|
|
|
|
|
_standard_pattern_ops = {k: "LIKE TRANSLATE( " + v + " USING NCHAR_CS)"
|
|
|
|
" ESCAPE TRANSLATE('\\' USING NCHAR_CS)"
|
|
|
|
for k, v in _pattern_ops.items()}
|
|
|
|
_likec_pattern_ops = {k: "LIKEC " + v + " ESCAPE '\\'"
|
|
|
|
for k, v in _pattern_ops.items()}
|
|
|
|
|
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
|
2014-09-26 01:59:03 +08:00
|
|
|
SchemaEditorClass = DatabaseSchemaEditor
|
2016-09-09 04:33:36 +08:00
|
|
|
# Classes instantiated in __init__().
|
|
|
|
client_class = DatabaseClient
|
|
|
|
creation_class = DatabaseCreation
|
|
|
|
features_class = DatabaseFeatures
|
|
|
|
introspection_class = DatabaseIntrospection
|
|
|
|
ops_class = DatabaseOperations
|
2017-05-23 23:02:40 +08:00
|
|
|
validation_class = DatabaseValidation
|
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
|
|
|
|
2008-08-25 04:16:56 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*args, **kwargs)
|
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
|
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'
|
2016-09-28 03:01:30 +08:00
|
|
|
if settings_dict['PORT']:
|
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):
|
2016-12-30 01:45:25 +08:00
|
|
|
return Database.connect(self._connect_string(), **conn_params)
|
2012-11-27 04:42:27 +08:00
|
|
|
|
|
|
|
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'")
|
2014-03-02 22:25:53 +08:00
|
|
|
# Set Oracle date to ANSI date format. This only needs to execute
|
2012-11-27 04:42:27 +08:00
|
|
|
# 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'"
|
2016-04-04 08:37:32 +08:00
|
|
|
" NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'" +
|
|
|
|
(" TIME_ZONE = 'UTC'" if settings.USE_TZ else '')
|
|
|
|
)
|
2012-11-27 04:42:27 +08:00
|
|
|
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'])
|
2016-09-27 06:31:41 +08:00
|
|
|
except Database.DatabaseError:
|
2012-11-27 04:42:27 +08:00
|
|
|
self.operators = self._likec_operators
|
2014-09-27 18:41:54 +08:00
|
|
|
self.pattern_ops = self._likec_pattern_ops
|
2012-11-27 04:42:27 +08:00
|
|
|
else:
|
|
|
|
self.operators = self._standard_operators
|
2014-09-27 18:41:54 +08:00
|
|
|
self.pattern_ops = self._standard_pattern_ops
|
2012-11-27 04:42:27 +08:00
|
|
|
cursor.close()
|
2016-12-30 01:45:25 +08:00
|
|
|
self.connection.stmtcachesize = 20
|
2014-01-13 03:27:08 +08:00
|
|
|
# Ensure all changes are preserved even when AUTOCOMMIT is False.
|
|
|
|
if not self.get_autocommit():
|
|
|
|
self.commit()
|
2012-11-27 04:42:27 +08:00
|
|
|
|
2016-06-04 06:31:21 +08:00
|
|
|
def create_cursor(self, name=None):
|
2013-03-02 19:12:51 +08:00
|
|
|
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:
|
2016-12-30 01:45:25 +08:00
|
|
|
# cx_Oracle raises a cx_Oracle.DatabaseError exception
|
2010-11-11 12:36:20 +08:00
|
|
|
# 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:
|
2017-01-08 03:13:29 +08:00
|
|
|
raise utils.IntegrityError(*tuple(e.args))
|
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
|
|
|
|
2014-06-09 04:42:12 +08:00
|
|
|
# Oracle doesn't support releasing savepoints. But we fake them when query
|
|
|
|
# logging is enabled to keep query counts consistent with other backends.
|
2013-03-02 19:12:51 +08:00
|
|
|
def _savepoint_commit(self, sid):
|
2014-06-09 04:42:12 +08:00
|
|
|
if self.queries_logged:
|
|
|
|
self.queries_log.append({
|
|
|
|
'sql': '-- RELEASE SAVEPOINT %s (faked)' % self.ops.quote_name(sid),
|
|
|
|
'time': '0.000',
|
|
|
|
})
|
2013-03-02 19:12:51 +08:00
|
|
|
|
2013-03-02 20:47:46 +08:00
|
|
|
def _set_autocommit(self, autocommit):
|
2014-03-24 06:09:26 +08:00
|
|
|
with self.wrap_database_errors:
|
|
|
|
self.connection.autocommit = autocommit
|
2013-03-02 20:47:46 +08:00
|
|
|
|
2013-03-02 19:12:51 +08:00
|
|
|
def check_constraints(self, table_names=None):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Check constraints by setting them to immediate. Return them to deferred
|
|
|
|
afterward.
|
2013-03-02 19:12:51 +08:00
|
|
|
"""
|
|
|
|
self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
|
|
|
|
self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
|
|
|
|
|
|
|
|
def is_usable(self):
|
|
|
|
try:
|
2014-08-02 00:53:18 +08:00
|
|
|
self.connection.ping()
|
2014-04-10 04:41:33 +08:00
|
|
|
except Database.Error:
|
2013-03-02 19:12:51 +08:00
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
|
2013-02-19 17:50:22 +08:00
|
|
|
@cached_property
|
2014-08-22 10:08:53 +08:00
|
|
|
def oracle_full_version(self):
|
2013-02-19 17:51:24 +08:00
|
|
|
with self.temporary_connection():
|
2014-08-22 10:08:53 +08:00
|
|
|
return self.connection.version
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def oracle_version(self):
|
2013-02-19 17:50:22 +08:00
|
|
|
try:
|
2014-08-22 10:08:53 +08:00
|
|
|
return int(self.oracle_full_version.split('.')[0])
|
2013-02-19 17:50:22 +08:00
|
|
|
except ValueError:
|
|
|
|
return None
|
|
|
|
|
2008-08-25 04:16:56 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class OracleParam:
|
2008-07-30 09:29:31 +08:00
|
|
|
"""
|
|
|
|
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.
|
2014-03-13 05:43:45 +08:00
|
|
|
if settings.USE_TZ and (isinstance(param, datetime.datetime) and
|
|
|
|
not isinstance(param, Oracle_datetime)):
|
2015-05-02 21:54:17 +08:00
|
|
|
param = Oracle_datetime.from_datetime(param)
|
2012-02-28 05:15:25 +08:00
|
|
|
|
2014-05-17 01:04:26 +08:00
|
|
|
string_size = 0
|
2017-01-26 02:59:25 +08:00
|
|
|
# Oracle doesn't recognize True and False correctly.
|
2012-08-20 02:15:52 +08:00
|
|
|
if param is True:
|
2014-09-07 10:26:05 +08:00
|
|
|
param = 1
|
2012-08-20 02:15:52 +08:00
|
|
|
elif param is False:
|
2014-09-07 10:26:05 +08:00
|
|
|
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)
|
2016-12-30 04:49:18 +08:00
|
|
|
elif isinstance(param, (Database.Binary, datetime.timedelta)):
|
2013-03-10 06:39:14 +08:00
|
|
|
self.force_bytes = param
|
2009-03-13 07:41:27 +08:00
|
|
|
else:
|
2014-05-17 01:04:26 +08:00
|
|
|
# To transmit to the database, we need Unicode if supported
|
|
|
|
# To get size right, we must consider bytes.
|
2016-12-30 01:45:25 +08:00
|
|
|
self.force_bytes = force_text(param, cursor.charset, strings_only)
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(self.force_bytes, str):
|
2014-05-17 01:04:26 +08:00
|
|
|
# We could optimize by only converting up to 4000 bytes here
|
|
|
|
string_size = len(force_bytes(param, cursor.charset, 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
|
2014-05-17 01:04:26 +08:00
|
|
|
elif string_size > 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
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class VariableWrapper:
|
2010-04-29 01:08:06 +08:00
|
|
|
"""
|
|
|
|
An adapter class for cursor variables that prevents the wrapped object
|
2014-03-02 22:25:53 +08:00
|
|
|
from being converted into a string when used to instantiate an OracleParam.
|
2010-04-29 01:08:06 +08:00
|
|
|
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)
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class FormatStylePlaceholderCursor:
|
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()
|
2017-04-28 22:27:21 +08:00
|
|
|
self.cursor.outputtypehandler = self._output_type_handler
|
2017-03-28 21:41:45 +08:00
|
|
|
# The default for cx_Oracle < 5.3 is 50.
|
2009-01-17 06:23:58 +08:00
|
|
|
self.cursor.arraysize = 100
|
|
|
|
|
2017-04-28 22:27:21 +08:00
|
|
|
@staticmethod
|
|
|
|
def _output_type_handler(cursor, name, defaultType, length, precision, scale):
|
|
|
|
"""
|
|
|
|
Called for each db column fetched from cursors. Return numbers as
|
|
|
|
strings so that decimal values don't have rounding error.
|
|
|
|
"""
|
|
|
|
if defaultType == Database.NUMBER:
|
|
|
|
return cursor.var(
|
|
|
|
Database.STRING,
|
|
|
|
size=255,
|
|
|
|
arraysize=cursor.arraysize,
|
|
|
|
outconverter=str,
|
|
|
|
)
|
|
|
|
|
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:
|
2014-12-07 05:00:09 +08:00
|
|
|
return {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'):
|
2014-12-07 05:00:09 +08:00
|
|
|
return {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
|
|
|
|
2016-12-24 20:26:15 +08:00
|
|
|
def _fix_for_params(self, query, params, unify_by_values=False):
|
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 = []
|
2016-12-30 01:45:25 +08:00
|
|
|
query = query
|
2013-06-28 11:15:03 +08:00
|
|
|
elif hasattr(params, 'keys'):
|
|
|
|
# Handle params as dict
|
2017-05-28 07:08:46 +08:00
|
|
|
args = {k: ":%s" % k for k in params}
|
2016-12-30 01:45:25 +08:00
|
|
|
query = query % args
|
2016-12-29 06:20:42 +08:00
|
|
|
elif unify_by_values and len(params) > 0:
|
2016-12-24 20:26:15 +08:00
|
|
|
# Handle params as a dict with unified query parameters by their
|
|
|
|
# values. It can be used only in single query execute() because
|
|
|
|
# executemany() shares the formatted query with each of the params
|
|
|
|
# list. e.g. for input params = [0.75, 2, 0.75, 'sth', 0.75]
|
2017-01-20 11:20:14 +08:00
|
|
|
# params_dict = {0.75: ':arg0', 2: ':arg1', 'sth': ':arg2'}
|
2016-12-24 20:26:15 +08:00
|
|
|
# args = [':arg0', ':arg1', ':arg0', ':arg2', ':arg0']
|
|
|
|
# params = {':arg0': 0.75, ':arg1': 2, ':arg2': 'sth'}
|
|
|
|
params_dict = {param: ':arg%d' % i for i, param in enumerate(set(params))}
|
|
|
|
args = [params_dict[param] for param in params]
|
2017-01-20 11:20:14 +08:00
|
|
|
params = {value: key for key, value in params_dict.items()}
|
2016-12-30 01:45:25 +08:00
|
|
|
query = query % tuple(args)
|
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))]
|
2016-12-30 01:45:25 +08:00
|
|
|
query = query % tuple(args)
|
2017-04-17 20:22:00 +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):
|
2016-12-24 20:26:15 +08:00
|
|
|
query, params = self._fix_for_params(query, params, unify_by_values=True)
|
2007-12-11 10:22:40 +08:00
|
|
|
self._guess_input_sizes([params])
|
2016-12-30 01:45:25 +08:00
|
|
|
return self.cursor.execute(query, self._param_generator(params))
|
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)
|
2016-12-30 01:45:25 +08:00
|
|
|
return self.cursor.executemany(query, [self._param_generator(p) for p in formatted])
|
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-12-13 04:23:24 +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-12-13 04:23:24 +08:00
|
|
|
return tuple(_rowfactory(r, self.cursor) for r in self.cursor.fetchall())
|
2008-12-12 04:12:00 +08:00
|
|
|
|
2014-04-25 05:36:40 +08:00
|
|
|
def close(self):
|
|
|
|
try:
|
|
|
|
self.cursor.close()
|
|
|
|
except Database.InterfaceError:
|
|
|
|
# already closed
|
|
|
|
pass
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
2017-01-07 19:11:46 +08:00
|
|
|
class CursorIterator:
|
2015-09-01 04:14:35 +08:00
|
|
|
"""
|
|
|
|
Cursor iterator wrapper that invokes our custom row factory.
|
|
|
|
"""
|
2009-12-23 05:05:15 +08:00
|
|
|
|
|
|
|
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
|
2017-01-21 05:04:05 +08:00
|
|
|
# cursor description.
|
2009-12-23 05:05:15 +08:00
|
|
|
casted = []
|
|
|
|
for value, desc in zip(row, cursor.description):
|
|
|
|
if value is not None and desc[1] is Database.NUMBER:
|
2017-03-11 06:02:44 +08:00
|
|
|
precision = desc[4] or 0
|
|
|
|
scale = desc[5] or 0
|
2009-12-23 05:05:15 +08:00
|
|
|
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)
|
|
|
|
casted.append(value)
|
|
|
|
return tuple(casted)
|