[pypy-commit] pypy default: fix issue 1530 by removing oracle module
mattip
noreply at buildbot.pypy.org
Tue Apr 29 23:10:09 CEST 2014
Author: Matti Picus <matti.picus at gmail.com>
Branch:
Changeset: r71064:fadfe9f9e3d4
Date: 2014-04-29 23:58 +0300
http://bitbucket.org/pypy/pypy/changeset/fadfe9f9e3d4/
Log: fix issue 1530 by removing oracle module
diff too long, truncating to 2000 out of 6366 lines
diff --git a/pypy/doc/config/objspace.usemodules.oracle.txt b/pypy/doc/config/objspace.usemodules.oracle.txt
deleted file mode 100644
--- a/pypy/doc/config/objspace.usemodules.oracle.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Use the 'oracle' module.
-This module is off by default, requires oracle client installed.
diff --git a/pypy/module/cpyext/patches/cx_Oracle.patch b/pypy/module/cpyext/patches/cx_Oracle.patch
deleted file mode 100644
--- a/pypy/module/cpyext/patches/cx_Oracle.patch
+++ /dev/null
@@ -1,60 +0,0 @@
-Index: cx_Oracle.c
-===================================================================
---- cx_Oracle.c (r�vision 333)
-+++ cx_Oracle.c (copie de travail)
-@@ -65,6 +65,13 @@
- #define CXORA_BASE_EXCEPTION PyExc_StandardError
- #endif
-
-+// define missing PyDateTime_DELTA macros
-+#ifndef PYPY_VERSION
-+PyDateTime_DELTA_GET_DAYS(o) (((PyDateTime_Delta*)o)->days)
-+PyDateTime_DELTA_GET_SECONDS(o) (((PyDateTime_Delta*)o)->seconds)
-+PyDateTime_DELTA_GET_MICROSECONDS(o) (((PyDateTime_Delta*)o)->microseconds)
-+#endif
-+
- // define simple construct for determining endianness of the platform
- // Oracle uses native encoding with OCI_UTF16 but bails when a BOM is written
- #define IS_LITTLE_ENDIAN (int)*(unsigned char*) &one
-@@ -138,6 +145,7 @@
- *exception = PyErr_NewException(buffer, baseException, NULL);
- if (!*exception)
- return -1;
-+ Py_INCREF(*exception);
- return PyModule_AddObject(module, name, *exception);
- }
-
-Index: IntervalVar.c
-===================================================================
---- IntervalVar.c (r�vision 333)
-+++ IntervalVar.c (copie de travail)
-@@ -121,7 +121,7 @@
- unsigned pos, // array position to set
- PyObject *value) // value to set
- {
-- sb4 hours, minutes, seconds;
-+ sb4 days, hours, minutes, seconds, microseconds;
- PyDateTime_Delta *delta;
- sword status;
-
-@@ -131,13 +131,16 @@
- }
-
- delta = (PyDateTime_Delta*) value;
-- hours = (sb4) delta->seconds / 3600;
-- seconds = delta->seconds - hours * 3600;
-+ days = PyDateTime_DELTA_GET_DAYS(delta);
-+ seconds = PyDateTime_DELTA_GET_SECONDS(delta);
-+ hours = (sb4) seconds / 3600;
-+ seconds -= hours * 3600;
- minutes = (sb4) seconds / 60;
- seconds -= minutes * 60;
-+ microseconds = PyDateTime_DELTA_GET_MICROSECONDS(delta);
- status = OCIIntervalSetDaySecond(var->environment->handle,
-- var->environment->errorHandle, delta->days, hours, minutes,
-- seconds, delta->microseconds, var->data[pos]);
-+ var->environment->errorHandle, days, hours, minutes,
-+ seconds, microseconds, var->data[pos]);
- if (Environment_CheckForError(var->environment, status,
- "IntervalVar_SetValue()") < 0)
- return -1;
diff --git a/pypy/module/oracle/__init__.py b/pypy/module/oracle/__init__.py
deleted file mode 100644
--- a/pypy/module/oracle/__init__.py
+++ /dev/null
@@ -1,54 +0,0 @@
-from pypy.interpreter.mixedmodule import MixedModule
-
-class Module(MixedModule):
- applevel_name = 'cx_Oracle'
-
- interpleveldefs = {
- 'connect': 'interp_connect.W_Connection',
- 'Connection': 'interp_connect.W_Connection',
- 'NUMBER': 'interp_variable.VT_Float',
- 'STRING': 'interp_variable.VT_String',
- 'UNICODE': 'interp_variable.VT_NationalCharString',
- 'DATETIME': 'interp_variable.VT_DateTime',
- 'DATE': 'interp_variable.VT_Date',
- 'TIMESTAMP': 'interp_variable.VT_Timestamp',
- 'INTERVAL': 'interp_variable.VT_Interval',
- 'BINARY': 'interp_variable.VT_Binary',
- 'LONG_STRING': 'interp_variable.VT_LongString',
- 'LONG_BINARY': 'interp_variable.VT_LongBinary',
- 'FIXED_CHAR': 'interp_variable.VT_FixedChar',
- 'FIXED_UNICODE': 'interp_variable.VT_FixedNationalChar',
- 'CURSOR': 'interp_variable.VT_Cursor',
- 'BLOB': 'interp_variable.VT_BLOB',
- 'CLOB': 'interp_variable.VT_CLOB',
- 'OBJECT': 'interp_variable.VT_Object',
- 'Variable': 'interp_variable.W_Variable',
- 'SessionPool': 'interp_pool.W_SessionPool',
- }
-
- appleveldefs = {
- 'version': 'app_oracle.version',
- 'paramstyle': 'app_oracle.paramstyle',
- 'makedsn': 'app_oracle.makedsn',
- 'TimestampFromTicks': 'app_oracle.TimestampFromTicks',
- }
- for name in """DataError DatabaseError Error IntegrityError InterfaceError
- InternalError NotSupportedError OperationalError
- ProgrammingError Warning""".split():
- appleveldefs[name] = "app_oracle.%s" % (name,)
-
- def startup(self, space):
- from pypy.module.oracle.interp_error import get
- state = get(space)
- state.startup(space)
- (state.w_DecimalType,
- state.w_DateTimeType, state.w_DateType, state.w_TimedeltaType,
- ) = space.fixedview(space.appexec([], """():
- import decimal, datetime
- return (decimal.Decimal,
- datetime.datetime, datetime.date, datetime.timedelta)
- """))
- space.setattr(space.wrap(self),
- space.wrap("Timestamp"), state.w_DateTimeType)
- space.setattr(space.wrap(self),
- space.wrap("Date"), state.w_DateType)
diff --git a/pypy/module/oracle/app_oracle.py b/pypy/module/oracle/app_oracle.py
deleted file mode 100644
--- a/pypy/module/oracle/app_oracle.py
+++ /dev/null
@@ -1,42 +0,0 @@
-version = '5.0.0'
-paramstyle = 'named'
-
-class Warning(StandardError):
- pass
-
-class Error(StandardError):
- pass
-
-class InterfaceError(Error):
- pass
-
-class DatabaseError(Error):
- pass
-
-class DataError(DatabaseError):
- pass
-
-class OperationalError(DatabaseError):
- pass
-
-class IntegrityError(DatabaseError):
- pass
-
-class InternalError(DatabaseError):
- pass
-
-class ProgrammingError(DatabaseError):
- pass
-
-class NotSupportedError(DatabaseError):
- pass
-
-
-def makedsn(host, port, sid):
- return ("(DESCRIPTION=(ADDRESS_LIST=(ADDRESS="
- "(PROTOCOL=TCP)(HOST=%s)(PORT=%s)))"
- "(CONNECT_DATA=(SID=%s)))" % (host, port, sid))
-
-def TimestampFromTicks(*args):
- import datetime
- return datetime.datetime.fromtimestamp(*args)
diff --git a/pypy/module/oracle/config.py b/pypy/module/oracle/config.py
deleted file mode 100644
--- a/pypy/module/oracle/config.py
+++ /dev/null
@@ -1,54 +0,0 @@
-from rpython.rtyper.lltypesystem import rffi, lltype
-from pypy.module.oracle import roci
-
-WITH_UNICODE = False
-
-MAX_STRING_CHARS = 4000
-MAX_BINARY_BYTES = 4000
-
-if WITH_UNICODE:
- CHARSETID = roci.OCI_UTF16ID
- BYTES_PER_CHAR = 2
- def string_w(space, w_obj):
- return space.unicode_w(w_obj)
-else:
- def string_w(space, w_obj):
- return space.str_w(w_obj)
-
- def w_string(space, buf, len=-1):
- #assert type(len) is int
- if len < 0:
- return space.wrap(rffi.charp2str(buf))
- else:
- return space.wrap(rffi.charpsize2str(buf, len))
- CHARSETID = 0
- BYTES_PER_CHAR = 1
-
- class StringBuffer:
- "Fill a char* buffer with data, suitable to pass to Oracle functions"
- def __init__(self):
- self.ptr = lltype.nullptr(roci.oratext.TO)
- self.size = 0
-
- def fill(self, space, w_value):
- if w_value is None or space.is_w(w_value, space.w_None):
- self.clear()
- else:
- strvalue = space.str_w(w_value)
- self.ptr = rffi.str2charp(strvalue)
- self.size = len(strvalue)
-
- def fill_with_unicode(self, space, w_value):
- if w_value is None or space.is_w(w_value, space.w_None):
- self.clear()
- else:
- # XXX ucs2 only probably
- univalue = space.unicode_w(w_value)
- self.ptr = rffi.cast(roci.oratext, rffi.unicode2wcharp(univalue))
- self.size = len(univalue) * 2
-
- def clear(self):
- if self.ptr:
- rffi.free_charp(self.ptr)
- self.ptr = lltype.nullptr(roci.oratext.TO)
- self.size = 0
diff --git a/pypy/module/oracle/conftest.py b/pypy/module/oracle/conftest.py
deleted file mode 100644
--- a/pypy/module/oracle/conftest.py
+++ /dev/null
@@ -1,9 +0,0 @@
-import os
-
-def pytest_addoption(parser):
- group = parser.getgroup("Oracle module options")
- group.addoption('--oracle-home', dest="oracle_home",
- help="Home directory of Oracle client installation",
- default=os.environ.get("ORACLE_HOME"))
- group.addoption('--oracle-connect', dest="oracle_connect",
- help="connect string (user/pwd at db) used for tests")
diff --git a/pypy/module/oracle/interp_connect.py b/pypy/module/oracle/interp_connect.py
deleted file mode 100644
--- a/pypy/module/oracle/interp_connect.py
+++ /dev/null
@@ -1,551 +0,0 @@
-from pypy.interpreter.baseobjspace import W_Root
-from pypy.interpreter.gateway import unwrap_spec
-from pypy.interpreter.typedef import (TypeDef, interp_attrproperty_w,
- GetSetProperty)
-from pypy.interpreter.gateway import interp2app
-from pypy.interpreter.error import OperationError
-from rpython.rtyper.lltypesystem import rffi, lltype
-
-from pypy.module.oracle import roci, interp_error
-from pypy.module.oracle.config import string_w, StringBuffer, MAX_STRING_CHARS
-from pypy.module.oracle.interp_environ import Environment
-from pypy.module.oracle.interp_cursor import W_Cursor
-from pypy.module.oracle.interp_pool import W_SessionPool
-from pypy.module.oracle.interp_variable import VT_String
-
-
-class W_Connection(W_Root):
- def __init__(self):
- self.commitMode = roci.OCI_DEFAULT
- self.environment = None
- self.autocommit = False
-
- self.sessionHandle = lltype.nullptr(roci.OCISession.TO)
- self.serverHandle = lltype.nullptr(roci.OCIServer.TO)
-
- self.w_inputTypeHandler = None
- self.w_outputTypeHandler = None
-
- self.w_version = None
- self.release = False
-
-
- @unwrap_spec(mode=int, handle=int,
- threaded=bool, twophase=bool, events=bool,
- purity=bool)
- def descr_new(space, w_subtype,
- w_user=None,
- w_password=None,
- w_dsn=None,
- mode=roci.OCI_DEFAULT,
- handle=0, # XXX should be a ptr type
- w_pool=None,
- threaded=False,
- twophase=False,
- events=False,
- w_cclass=None,
- purity=0,
- w_newpassword=None):
- self = space.allocate_instance(W_Connection, w_subtype)
- W_Connection.__init__(self)
-
- # set up the environment
- if w_pool:
- pool = space.interp_w(W_SessionPool, w_pool)
- self.environment = pool.environment.clone()
- else:
- pool = None
- self.environment = Environment.create(space, threaded, events)
-
- self.w_username = w_user
- self.w_password = w_password
- self.w_tnsentry = w_dsn
-
- # perform some parsing, if necessary
- if (self.w_username and not self.w_password and
- space.is_true(space.contains(self.w_username, space.wrap('/')))):
- (self.w_username, self.w_password) = space.listview(
- space.call_method(self.w_username, 'split',
- space.wrap('/'), space.wrap(1)))
-
- if (self.w_password and not self.w_tnsentry and
- space.is_true(space.contains(self.w_password, space.wrap('@')))):
- (self.w_password, self.w_tnsentry) = space.listview(
- space.call_method(self.w_password, 'split',
- space.wrap('@'), space.wrap(1)))
-
- if pool or w_cclass is not None:
- self.getConnection(space, pool, w_cclass, purity)
- else:
- self.connect(space, mode, twophase)
- return space.wrap(self)
-
- def __del__(self):
- self.enqueue_for_destruction(self.environment.space,
- W_Connection.destructor,
- '__del__ method of ')
-
- def destructor(self):
- assert isinstance(self, W_Connection)
- if self.release:
- roci.OCITransRollback(
- self.handle, self.environment.errorHandle,
- roci.OCI_DEFAULT)
- roci.OCISessionRelease(
- self.handle, self.environment.errorHandle,
- None, 0, roci.OCI_DEFAULT)
- else:
- if self.sessionHandle:
- roci.OCITransRollback(
- self.handle, self.environment.errorHandle,
- roci.OCI_DEFAULT)
- roci.OCISessionEnd(
- self.handle, self.environment.errorHandle,
- self.sessionHandle, roci.OCI_DEFAULT)
- if self.serverHandle:
- roci.OCIServerDetach(
- self.serverHandle, self.environment.errorHandle,
- roci.OCI_DEFAULT)
-
- def connect(self, space, mode, twophase):
- stringBuffer = StringBuffer()
-
- # allocate the server handle
- handleptr = lltype.malloc(rffi.CArrayPtr(roci.OCIServer).TO,
- 1, flavor='raw')
- try:
- status = roci.OCIHandleAlloc(
- self.environment.handle,
- handleptr, roci.OCI_HTYPE_SERVER, 0,
- lltype.nullptr(rffi.CArray(roci.dvoidp)))
- self.environment.checkForError(
- status, "Connection_Connect(): allocate server handle")
- self.serverHandle = handleptr[0]
- finally:
- lltype.free(handleptr, flavor='raw')
-
- # attach to the server
- stringBuffer.fill(space, self.w_tnsentry)
- try:
- status = roci.OCIServerAttach(
- self.serverHandle,
- self.environment.errorHandle,
- stringBuffer.ptr, stringBuffer.size,
- roci.OCI_DEFAULT)
- self.environment.checkForError(
- status, "Connection_Connect(): server attach")
- finally:
- stringBuffer.clear()
-
- # allocate the service context handle
- handleptr = lltype.malloc(rffi.CArrayPtr(roci.OCISvcCtx).TO,
- 1, flavor='raw')
-
- try:
- status = roci.OCIHandleAlloc(
- self.environment.handle,
- handleptr, roci.OCI_HTYPE_SVCCTX, 0,
- lltype.nullptr(rffi.CArray(roci.dvoidp)))
- self.environment.checkForError(
- status, "Connection_Connect(): allocate service context handle")
- self.handle = handleptr[0]
- finally:
- lltype.free(handleptr, flavor='raw')
-
- # set attribute for server handle
- status = roci.OCIAttrSet(
- self.handle, roci.OCI_HTYPE_SVCCTX,
- self.serverHandle, 0,
- roci.OCI_ATTR_SERVER,
- self.environment.errorHandle)
- self.environment.checkForError(
- status, "Connection_Connect(): set server handle")
-
- # set the internal and external names; these are needed for global
- # transactions but are limited in terms of the lengths of the strings
- if twophase:
- status = roci.OCIAttrSet(
- self.serverHandle, roci.OCI_HTYPE_SERVER,
- "cx_Oracle", 0,
- roci.OCI_ATTR_INTERNAL_NAME,
- self.environment.errorHandle)
- self.environment.checkForError(
- status, "Connection_Connect(): set internal name")
- status = roci.OCIAttrSet(
- self.serverHandle, roci.OCI_HTYPE_SERVER,
- "cx_Oracle", 0,
- roci.OCI_ATTR_EXTERNAL_NAME,
- self.environment.errorHandle)
- self.environment.checkForError(
- status, "Connection_Connect(): set external name")
-
- # allocate the session handle
- handleptr = lltype.malloc(rffi.CArrayPtr(roci.OCISession).TO,
- 1, flavor='raw')
- try:
- status = roci.OCIHandleAlloc(
- self.environment.handle,
- handleptr, roci.OCI_HTYPE_SESSION, 0,
- lltype.nullptr(rffi.CArray(roci.dvoidp)))
- self.environment.checkForError(
- status, "Connection_Connect(): allocate session handle")
- self.sessionHandle = handleptr[0]
- finally:
- lltype.free(handleptr, flavor='raw')
-
- credentialType = roci.OCI_CRED_EXT
-
- # set user name in session handle
- stringBuffer.fill(space, self.w_username)
- try:
- if stringBuffer.size > 0:
- credentialType = roci.OCI_CRED_RDBMS
- status = roci.OCIAttrSet(
- self.sessionHandle,
- roci.OCI_HTYPE_SESSION,
- stringBuffer.ptr, stringBuffer.size,
- roci.OCI_ATTR_USERNAME,
- self.environment.errorHandle)
- self.environment.checkForError(
- status, "Connection_Connect(): set user name")
- finally:
- stringBuffer.clear()
-
- # set password in session handle
- stringBuffer.fill(space, self.w_password)
- try:
- if stringBuffer.size > 0:
- credentialType = roci.OCI_CRED_RDBMS
- status = roci.OCIAttrSet(
- self.sessionHandle,
- roci.OCI_HTYPE_SESSION,
- stringBuffer.ptr, stringBuffer.size,
- roci.OCI_ATTR_PASSWORD,
- self.environment.errorHandle)
- self.environment.checkForError(
- status, "Connection_Connect(): set password")
- finally:
- stringBuffer.clear()
-
- # set the session handle on the service context handle
- status = roci.OCIAttrSet(
- self.handle, roci.OCI_HTYPE_SVCCTX,
- self.sessionHandle, 0,
- roci.OCI_ATTR_SESSION,
- self.environment.errorHandle)
- self.environment.checkForError(
- status, "Connection_Connect(): set session handle")
-
- # if a new password has been specified, change it which will also
- # establish the session
-
- # begin the session
- status = roci.OCISessionBegin(
- self.handle, self.environment.errorHandle,
- self.sessionHandle, credentialType, mode)
- try:
- self.environment.checkForError(
- status, "Connection_Connect(): begin session")
- except:
- self.sessionHandle = lltype.nullptr(roci.OCISession.TO)
- raise
-
- def getConnection(self, space, pool, w_cclass, purity):
- """Get a connection using the OCISessionGet() interface
- rather than using the low level interface for connecting."""
-
- proxyCredentials = False
- authInfo = lltype.nullptr(roci.OCIAuthInfo.TO)
-
- if pool:
- w_dbname = pool.w_name
- mode = roci.OCI_SESSGET_SPOOL
- if not pool.homogeneous and pool.w_username and self.w_username:
- proxyCredentials = space.is_true(space.ne(pool.w_username, self.w_username))
- mode |= roci.OCI_SESSGET_CREDPROXY
- else:
- w_dbname = self.w_tnsentry
- mode = roci.OCI_SESSGET_STMTCACHE
-
- stringBuffer = StringBuffer()
-
- # set up authorization handle, if needed
- if not pool or w_cclass or proxyCredentials:
- # create authorization handle
- handleptr = lltype.malloc(rffi.CArrayPtr(roci.OCIAuthInfo).TO,
- 1, flavor='raw')
- try:
- status = roci.OCIHandleAlloc(
- self.environment.handle,
- handleptr,
- roci.OCI_HTYPE_AUTHINFO,
- 0, lltype.nullptr(rffi.CArray(roci.dvoidp)))
- self.environment.checkForError(
- status, "Connection_GetConnection(): allocate handle")
-
- authInfo = handleptr[0]
- finally:
- lltype.free(handleptr, flavor='raw')
-
- externalCredentials = True
-
- # set the user name, if applicable
- stringBuffer.fill(space, self.w_username)
- try:
- if stringBuffer.size > 0:
- externalCredentials = False
- status = roci.OCIAttrSet(
- authInfo,
- roci.OCI_HTYPE_AUTHINFO,
- stringBuffer.ptr, stringBuffer.size,
- roci.OCI_ATTR_USERNAME,
- self.environment.errorHandle)
- self.environment.checkForError(
- status, "Connection_GetConnection(): set user name")
- finally:
- stringBuffer.clear()
-
- # set the password, if applicable
- stringBuffer.fill(space, self.w_password)
- try:
- if stringBuffer.size > 0:
- externalCredentials = False
- status = roci.OCIAttrSet(
- authInfo,
- roci.OCI_HTYPE_AUTHINFO,
- stringBuffer.ptr, stringBuffer.size,
- roci.OCI_ATTR_PASSWORD,
- self.environment.errorHandle)
- self.environment.checkForError(
- status, "Connection_GetConnection(): set password")
- finally:
- stringBuffer.clear()
-
- # if no user name or password are set, using external credentials
- if not pool and externalCredentials:
- mode |= roci.OCI_SESSGET_CREDEXT
-
- # set the connection class, if applicable
- if roci.OCI_ATTR_CONNECTION_CLASS is not None:
- stringBuffer.fill(space, w_cclass)
- try:
- if stringBuffer.size > 0:
- externalCredentials = False
- status = roci.OCIAttrSet(
- authInfo,
- roci.OCI_HTYPE_AUTHINFO,
- stringBuffer.ptr, stringBuffer.size,
- roci.OCI_ATTR_CONNECTION_CLASS,
- self.environment.errorHandle)
- self.environment.checkForError(
- status,
- "Connection_GetConnection(): set connection class")
- finally:
- stringBuffer.clear()
-
- # set the purity, if applicable
- if (roci.OCI_ATTR_PURITY is not None
- and purity != roci.OCI_ATTR_PURITY_DEFAULT):
- purityptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO,
- 1, flavor='raw')
- purityptr[0] = rffi.cast(roci.ub4, purity)
- try:
- status = roci.OCIAttrSet(
- authInfo,
- roci.OCI_HTYPE_AUTHINFO,
- rffi.cast(roci.dvoidp, purityptr),
- rffi.sizeof(roci.ub4),
- roci.OCI_ATTR_PURITY,
- self.environment.errorHandle)
- self.environment.checkForError(
- status, "Connection_GetConnection(): set purity")
- finally:
- lltype.free(purityptr, flavor='raw')
-
- # acquire the new session
- stringBuffer.fill(space, w_dbname)
- foundptr = lltype.malloc(rffi.CArrayPtr(roci.boolean).TO,
- 1, flavor='raw')
- handleptr = lltype.malloc(rffi.CArrayPtr(roci.OCISvcCtx).TO,
- 1, flavor='raw')
- try:
- status = roci.OCISessionGet(
- self.environment.handle,
- self.environment.errorHandle,
- handleptr,
- authInfo,
- stringBuffer.ptr, stringBuffer.size,
- None, 0,
- lltype.nullptr(roci.Ptr(roci.oratext).TO),
- lltype.nullptr(roci.Ptr(roci.ub4).TO),
- foundptr,
- mode)
- self.environment.checkForError(
- status, "Connection_GetConnection(): get connection")
-
- self.handle = handleptr[0]
- finally:
- stringBuffer.clear()
- lltype.free(foundptr, flavor='raw')
- lltype.free(handleptr, flavor='raw')
-
- # eliminate the authorization handle immediately, if applicable
- if authInfo:
- roci.OCIHandleFree(authInfo, roci.OCI_HTYPE_AUTHINFO)
-
- # copy members in the case where a pool is being used
- if pool:
- if not proxyCredentials:
- self.w_username = pool.w_username
- self.w_password = pool.w_password
- self.w_tnsentry = pool.w_tnsentry
- self.sessionPool = pool
-
- self.release = True
-
- def _checkConnected(self, space):
- if not self.handle:
- raise OperationError(
- interp_error.get(space).w_InterfaceError,
- space.wrap("not connected"))
-
- def close(self, space):
- # make sure we are actually connnected
- self._checkConnected(space)
-
- # perform a rollback
- status = roci.OCITransRollback(
- self.handle, self.environment.errorHandle,
- roci.OCI_DEFAULT)
- self.environment.checkForError(
- status, "Connection_Close(): rollback")
-
- # logoff of the server
- if self.sessionHandle:
- status = roci.OCISessionEnd(
- self.handle, self.environment.errorHandle,
- self.sessionHandle, roci.OCI_DEFAULT)
- self.environment.checkForError(
- status, "Connection_Close(): end session")
- roci.OCIHandleFree(self.handle, roci.OCI_HTYPE_SVCCTX)
-
- self.handle = lltype.nullptr(roci.OCISvcCtx.TO)
-
- def commit(self, space):
- # make sure we are actually connected
- self._checkConnected(space)
-
- status = roci.OCITransCommit(
- self.handle, self.environment.errorHandle,
- self.commitMode)
- self.environment.checkForError(
- status, "Connection_Commit()")
-
- self.commitMode = roci.OCI_DEFAULT
-
- def rollback(self, space):
- # make sure we are actually connected
- self._checkConnected(space)
-
- status = roci.OCITransRollback(
- self.handle, self.environment.errorHandle,
- roci.OCI_DEFAULT)
- self.environment.checkForError(
- status, "Connection_Rollback()")
-
- def newCursor(self, space):
- return space.wrap(W_Cursor(space, self))
-
- def _getCharacterSetName(self, space, attribute):
- # get character set id
- charsetIdPtr = lltype.malloc(rffi.CArrayPtr(roci.ub2).TO,
- 1, flavor='raw')
- try:
- status = roci.OCIAttrGet(
- self.environment.handle, roci.OCI_HTYPE_ENV,
- rffi.cast(roci.dvoidp, charsetIdPtr),
- lltype.nullptr(roci.Ptr(roci.ub4).TO),
- attribute,
- self.environment.errorHandle)
- self.environment.checkForError(
- status, "Connection_GetCharacterSetName(): get charset id")
- charsetId = charsetIdPtr[0]
- finally:
- lltype.free(charsetIdPtr, flavor='raw')
-
- # get character set name
- charsetname_buf, charsetname = rffi.alloc_buffer(roci.OCI_NLS_MAXBUFSZ)
- try:
- status = roci.OCINlsCharSetIdToName(
- self.environment.handle,
- charsetname_buf, roci.OCI_NLS_MAXBUFSZ,
- charsetId)
- self.environment.checkForError(
- status,
- "Connection_GetCharacterSetName(): get Oracle charset name")
-
- ianacharset_buf, ianacharset = rffi.alloc_buffer(
- roci.OCI_NLS_MAXBUFSZ)
-
- try:
- # get IANA character set name
- status = roci.OCINlsNameMap(
- self.environment.handle,
- ianacharset_buf, roci.OCI_NLS_MAXBUFSZ,
- charsetname_buf, roci.OCI_NLS_CS_ORA_TO_IANA)
- self.environment.checkForError(
- status,
- "Connection_GetCharacterSetName(): translate NLS charset")
- charset = rffi.charp2str(ianacharset_buf)
- finally:
- rffi.keep_buffer_alive_until_here(ianacharset_buf, ianacharset)
- finally:
- rffi.keep_buffer_alive_until_here(charsetname_buf, charsetname)
- return space.wrap(charset)
-
- def get_encoding(self, space):
- return self._getCharacterSetName(space, roci.OCI_ATTR_ENV_CHARSET_ID)
- def get_nationalencoding(self, space):
- return self._getCharacterSetName(space, roci.OCI_ATTR_ENV_CHARSET_ID)
- def get_maxbytespercharacter(self, space):
- return space.wrap(self.environment.maxBytesPerCharacter)
-
- def get_version(self, space):
- # if version has already been determined, no need to determine again
- if self.w_version:
- return self.w_version
-
- # allocate a cursor to retrieve the version
- cursor = W_Cursor(space, self)
-
- # allocate version and compatibility variables
- versionVar = VT_String(cursor, cursor.arraySize, MAX_STRING_CHARS)
- compatVar = VT_String(cursor, cursor.arraySize, MAX_STRING_CHARS)
-
- # call stored procedure
- cursor._call(space, "dbms_utility.db_version",
- None, space.newlist([space.wrap(versionVar),
- space.wrap(compatVar)]))
-
- # retrieve value
- self.w_version = versionVar.getValue(space, 0)
- return self.w_version
-
-W_Connection.typedef = TypeDef(
- "Connection",
- __new__ = interp2app(W_Connection.descr_new.im_func),
- username = interp_attrproperty_w('w_username', W_Connection),
- password = interp_attrproperty_w('w_password', W_Connection),
- tnsentry = interp_attrproperty_w('w_tnsentry', W_Connection),
-
- close = interp2app(W_Connection.close),
- commit = interp2app(W_Connection.commit),
- rollback = interp2app(W_Connection.rollback),
-
- cursor = interp2app(W_Connection.newCursor),
-
- encoding = GetSetProperty(W_Connection.get_encoding),
- nationalencoding = GetSetProperty(W_Connection.get_nationalencoding),
- maxBytesPerCharacter = GetSetProperty(W_Connection.get_maxbytespercharacter),
- version = GetSetProperty(W_Connection.get_version),
- )
diff --git a/pypy/module/oracle/interp_cursor.py b/pypy/module/oracle/interp_cursor.py
deleted file mode 100644
--- a/pypy/module/oracle/interp_cursor.py
+++ /dev/null
@@ -1,1094 +0,0 @@
-from pypy.interpreter.baseobjspace import W_Root
-from pypy.interpreter.typedef import TypeDef, GetSetProperty
-from pypy.interpreter.typedef import interp_attrproperty, interp_attrproperty_w
-from pypy.interpreter.gateway import interp2app, unwrap_spec
-from pypy.interpreter.error import OperationError
-from rpython.rtyper.lltypesystem import rffi, lltype
-
-from pypy.module.oracle import roci, interp_error
-from pypy.module.oracle.config import w_string, string_w, StringBuffer
-from pypy.module.oracle import interp_variable
-from pypy.module.oracle.interp_error import get
-
-# XXX are those "assert isinstance(xxx, interp_variable.W_Variable)" necessary?
-# the bindList should annotate to SomeList(SomeInstance(W_Variable))
-
-class W_Cursor(W_Root):
- def __init__(self, space, connection):
- self.connection = connection
- self.environment = connection.environment
-
- self.w_statement = None
- self.statementType = -1
- self.handle = lltype.nullptr(roci.OCIStmt.TO)
- self.isOpen = True
- self.isOwned = False
-
- self.setInputSizes = False
- self.arraySize = 50
- self.fetchArraySize = 50
- self.bindArraySize = 1
- self.bindList = None
- self.bindDict = None
- self.numbersAsStrings = False
- self.outputSize = -1
- self.outputSizeColumn = -1
-
- self.w_inputTypeHandler = None
- self.w_outputTypeHandler = None
- self.w_rowFactory = None
-
- def execute(self, space, w_stmt, __args__):
- args_w, kw_w = __args__.unpack()
-
- if space.is_w(w_stmt, space.w_None):
- w_stmt = None
-
- if len(args_w) > 1:
- raise OperationError(
- space.w_TypeError,
- space.wrap("Too many arguments"))
- elif len(args_w) == 1:
- if len(kw_w) > 0:
- raise OperationError(
- interp_error.get(space).w_InterfaceError,
- space.wrap(
- "expecting argument or keyword arguments, not both"))
- w_vars = args_w[0]
- elif len(kw_w) > 0:
- w_vars = space.newdict()
- for key, w_value in kw_w.iteritems():
- space.setitem(w_vars, space.wrap(key), w_value)
- else:
- w_vars = None
-
- # make sure the cursor is open
- self._checkOpen(space)
-
- return self._execute(space, w_stmt, w_vars)
-
- def prepare(self, space, w_stmt, w_tag=None):
- # make sure the cursor is open
- self._checkOpen(space)
-
- # prepare the statement
- self._internalPrepare(space, w_stmt, w_tag)
-
- def _execute(self, space, w_stmt, w_vars):
-
- # prepare the statement, if applicable
- self._internalPrepare(space, w_stmt, None)
-
- # perform binds
- if w_vars is None:
- pass
- elif space.isinstance_w(w_vars, space.w_dict):
- self._setBindVariablesByName(space, w_vars, 1, 0, 0)
- else:
- self._setBindVariablesByPos(space, w_vars, 1, 0, 0)
- self._performBind(space)
-
- # execute the statement
- isQuery = self.statementType == roci.OCI_STMT_SELECT
- if isQuery:
- numIters = 0
- else:
- numIters = 1
- self._internalExecute(space, numIters=numIters)
-
- # perform defines, if necessary
- if isQuery and self.fetchVariables is None:
- self._performDefine()
-
- # reset the values of setoutputsize()
- self.outputSize = -1
- self.outputSizeColumn = -1
-
- # for queries, return the cursor for convenience
- if isQuery:
- return space.wrap(self)
-
- # for all other statements, simply return None
- return space.w_None
-
- def executemany(self, space, w_stmt, w_list_of_args):
- if space.is_w(w_stmt, space.w_None):
- w_stmt = None
- if not space.isinstance_w(w_list_of_args, space.w_list):
- raise OperationError(
- space.w_TypeError,
- space.wrap("list expected"))
-
- # make sure the cursor is open
- self._checkOpen(space)
-
- # prepare the statement
- self._internalPrepare(space, w_stmt, None)
-
- # queries are not supported as the result is undefined
- if self.statementType == roci.OCI_STMT_SELECT:
- raise OperationError(
- get(space).w_NotSupportedError,
- space.wrap("queries not supported: results undefined"))
-
- # perform binds
- args_w = space.listview(w_list_of_args)
- numrows = len(args_w)
- for i in range(numrows):
- w_arguments = args_w[i]
- deferred = i < numrows - 1
- if space.isinstance_w(w_arguments, space.w_dict):
- self._setBindVariablesByName(
- space, w_arguments, numrows, i, deferred)
- else:
- self._setBindVariablesByPos(
- space, w_arguments, numrows, i, deferred)
- self._performBind(space)
-
- # execute the statement, but only if the number of rows is greater than
- # zero since Oracle raises an error otherwise
- if numrows > 0:
- self._internalExecute(space, numIters=numrows)
-
- def close(self, space):
- # make sure we are actually open
- self._checkOpen(space)
-
- # close the cursor
- self.freeHandle(space, raiseError=True)
-
- self.isOpen = False
- self.handle = lltype.nullptr(roci.OCIStmt.TO)
-
- @unwrap_spec(name=str)
- def callfunc(self, space, name, w_returnType, w_parameters=None):
- retvar = interp_variable.newVariableByType(space, self, w_returnType, 1)
- if space.is_none(w_parameters):
- w_parameters = None
-
- self._call(space, name, retvar, w_parameters)
-
- # determine the results
- return retvar.getValue(space, 0)
-
- @unwrap_spec(name=str)
- def callproc(self, space, name, w_parameters=None):
- if space.is_none(w_parameters):
- w_parameters = None
-
- self._call(space, name, None, w_parameters)
-
- # create the return value
- ret_w = []
- if self.bindList:
- for v in self.bindList:
- assert isinstance(v, interp_variable.W_Variable)
- ret_w.append(v.getValue(space, 0))
- return space.newlist(ret_w)
-
- def _call(self, space, name, retvar, w_args):
- # determine the number of arguments passed
- if w_args:
- numArguments = space.len_w(w_args)
- else:
- numArguments = 0
-
- # make sure we are actually open
- self._checkOpen(space)
-
- # add the return value, if applicable
- if retvar:
- offset = 1
- w_vars = space.newlist([retvar])
- if w_args:
- space.call_method(w_vars, "extend", w_args)
- else:
- offset = 0
- w_vars = w_args
-
- # build up the statement
- args = ', '.join([':%d' % (i + offset + 1,)
- for i in range(numArguments)])
- if retvar:
- stmt = "begin :1 := %s(%s); end;" % (name, args)
- else:
- stmt = "begin %s(%s); end;" % (name, args)
-
- self._execute(space, space.wrap(stmt), w_vars)
-
- def _checkOpen(self, space):
- if not self.isOpen:
- raise OperationError(
- interp_error.get(space).w_InterfaceError,
- space.wrap("not open"))
-
- def allocateHandle(self):
- handleptr = lltype.malloc(rffi.CArrayPtr(roci.OCIStmt).TO,
- 1, flavor='raw')
- try:
- status = roci.OCIHandleAlloc(
- self.environment.handle,
- handleptr, roci.OCI_HTYPE_STMT, 0,
- lltype.nullptr(rffi.CArray(roci.dvoidp)))
- self.environment.checkForError(
- status, "Cursor_New()")
- self.handle = handleptr[0]
- finally:
- lltype.free(handleptr, flavor='raw')
- self.isOwned = True
-
- def freeHandle(self, space, raiseError=True):
- if not self.handle:
- return
- if self.isOwned:
- roci.OCIHandleFree(self.handle, roci.OCI_HTYPE_STMT)
- elif self.connection.handle:
- tagBuffer = StringBuffer()
- tagBuffer.fill(space, self.w_statementTag)
- try:
- status = roci.OCIStmtRelease(
- self.handle, self.environment.errorHandle,
- tagBuffer.ptr, tagBuffer.size,
- roci.OCI_DEFAULT)
- self.environment.checkForError(
- status, "Cursor_FreeHandle()")
- finally:
- tagBuffer.clear()
-
- def _internalPrepare(self, space, w_stmt, w_tag):
- # make sure we don't get a situation where nothing is to be executed
- if w_stmt is None and self.w_statement is None:
- raise OperationError(
- interp_error.get(space).w_ProgrammingError,
- space.wrap("no statement specified "
- "and no prior statement prepared"))
-
- # nothing to do if the statement is identical to the one already stored
- # but go ahead and prepare anyway for create, alter and drop statments
- if w_stmt is None or w_stmt == self.w_statement:
- if self.statementType not in (roci.OCI_STMT_CREATE,
- roci.OCI_STMT_DROP,
- roci.OCI_STMT_ALTER):
- return
- w_stmt = self.w_statement
- else:
- self.w_statement = w_stmt
-
- # release existing statement, if necessary
- self.w_statementTag = w_tag
- self.freeHandle(space)
-
- # prepare statement
- self.isOwned = False
- handleptr = lltype.malloc(roci.Ptr(roci.OCIStmt).TO,
- 1, flavor='raw')
- stmtBuffer = StringBuffer()
- tagBuffer = StringBuffer()
- stmtBuffer.fill(space, w_stmt)
- tagBuffer.fill(space, w_tag)
- try:
- status = roci.OCIStmtPrepare2(
- self.connection.handle, handleptr,
- self.environment.errorHandle,
- stmtBuffer.ptr, stmtBuffer.size,
- tagBuffer.ptr, tagBuffer.size,
- roci.OCI_NTV_SYNTAX, roci.OCI_DEFAULT)
-
- self.environment.checkForError(
- status, "Connection_InternalPrepare(): prepare")
- self.handle = handleptr[0]
- finally:
- lltype.free(handleptr, flavor='raw')
- stmtBuffer.clear()
- tagBuffer.clear()
-
- # clear bind variables, if applicable
- if not self.setInputSizes:
- self.bindList = None
- self.bindDict = None
-
- # clear row factory, if applicable
- self.rowFactory = None
-
- # determine if statement is a query
- self._getStatementType()
-
- def _setErrorOffset(self, space, e):
- if e.match(space, get(space).w_DatabaseError):
- attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO, 1, flavor='raw')
- try:
- roci.OCIAttrGet(
- self.handle, roci.OCI_HTYPE_STMT,
- rffi.cast(roci.dvoidp, attrptr),
- lltype.nullptr(roci.Ptr(roci.ub4).TO),
- roci.OCI_ATTR_PARSE_ERROR_OFFSET,
- self.environment.errorHandle)
- e.offset = attrptr[0]
- finally:
- lltype.free(attrptr, flavor='raw')
-
- def _internalExecute(self, space, numIters):
- if self.connection.autocommit:
- mode = roci.OCI_COMMIT_ON_SUCCESS
- else:
- mode = roci.OCI_DEFAULT
-
- status = roci.OCIStmtExecute(
- self.connection.handle,
- self.handle,
- self.environment.errorHandle,
- numIters, 0,
- lltype.nullptr(roci.OCISnapshot.TO),
- lltype.nullptr(roci.OCISnapshot.TO),
- mode)
- try:
- self.environment.checkForError(
- status, "Cursor_InternalExecute()")
- except OperationError, e:
- self._setErrorOffset(space, e)
- raise
- finally:
- self._setRowCount()
-
- def _getStatementType(self):
- attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub2).TO, 1, flavor='raw')
- try:
- status = roci.OCIAttrGet(
- self.handle, roci.OCI_HTYPE_STMT,
- rffi.cast(roci.dvoidp, attrptr),
- lltype.nullptr(roci.Ptr(roci.ub4).TO),
- roci.OCI_ATTR_STMT_TYPE,
- self.environment.errorHandle)
-
- self.environment.checkForError(
- status, "Cursor_GetStatementType()")
- self.statementType = rffi.cast(lltype.Signed, attrptr[0])
- finally:
- lltype.free(attrptr, flavor='raw')
-
- self.fetchVariables = None
-
- def getDescription(self, space):
- "Return a list of 7-tuples consisting of the description of "
- "the define variables"
-
- # make sure the cursor is open
- self._checkOpen(space)
-
- # fixup bound cursor, if necessary
- self._fixupBoundCursor()
-
- # if not a query, return None
- if self.statementType != roci.OCI_STMT_SELECT:
- return
-
- # determine number of items in select-list
- attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub1).TO, 1, flavor='raw')
- try:
- status = roci.OCIAttrGet(
- self.handle, roci.OCI_HTYPE_STMT,
- rffi.cast(roci.dvoidp, attrptr),
- lltype.nullptr(roci.Ptr(roci.ub4).TO),
- roci.OCI_ATTR_PARAM_COUNT,
- self.environment.errorHandle)
- self.environment.checkForError(
- status,
- "Cursor_GetDescription()")
- numItems = attrptr[0]
- finally:
- lltype.free(attrptr, flavor='raw')
-
- return space.newlist(
- [space.newtuple(self._itemDescription(space, i + 1))
- for i in range(numItems)])
-
- def _itemDescription(self, space, pos):
- "Return a tuple describing the item at the given position"
-
- # acquire parameter descriptor
- paramptr = lltype.malloc(roci.Ptr(roci.OCIParam).TO,
- 1, flavor='raw')
- try:
- status = roci.OCIParamGet(
- self.handle, roci.OCI_HTYPE_STMT,
- self.environment.errorHandle,
- rffi.cast(roci.dvoidpp, paramptr),
- pos)
- self.environment.checkForError(
- status,
- "Cursor_GetDescription(): parameter")
- param = paramptr[0]
- finally:
- lltype.free(paramptr, flavor='raw')
-
- try:
- # acquire usable type of item
- varType = interp_variable.typeByOracleDescriptor(
- param, self.environment)
-
- # acquire internal size of item
- attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub2).TO, 1,
- flavor='raw')
- try:
- status = roci.OCIAttrGet(
- param, roci.OCI_HTYPE_DESCRIBE,
- rffi.cast(roci.dvoidp, attrptr),
- lltype.nullptr(roci.Ptr(roci.ub4).TO),
- roci.OCI_ATTR_DATA_SIZE,
- self.environment.errorHandle)
- self.environment.checkForError(
- status,
- "Cursor_ItemDescription(): internal size")
- internalSize = rffi.cast(lltype.Signed, attrptr[0])
- finally:
- lltype.free(attrptr, flavor='raw')
-
- # acquire name of item
- nameptr = lltype.malloc(rffi.CArrayPtr(roci.oratext).TO, 1,
- flavor='raw')
- lenptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO, 1,
- flavor='raw')
- try:
- status = roci.OCIAttrGet(
- param, roci.OCI_HTYPE_DESCRIBE,
- rffi.cast(roci.dvoidp, nameptr),
- lenptr,
- roci.OCI_ATTR_NAME,
- self.environment.errorHandle)
- self.environment.checkForError(
- status,
- "Cursor_ItemDescription(): name")
- name = rffi.charpsize2str(nameptr[0], rffi.cast(lltype.Signed, lenptr[0]))
- finally:
- lltype.free(nameptr, flavor='raw')
- lltype.free(lenptr, flavor='raw')
-
- # lookup precision and scale
- if varType is interp_variable.VT_Float:
- attrptr = lltype.malloc(rffi.CArrayPtr(roci.sb1).TO, 1,
- flavor='raw')
- try:
- status = roci.OCIAttrGet(
- param, roci.OCI_HTYPE_DESCRIBE,
- rffi.cast(roci.dvoidp, attrptr),
- lltype.nullptr(roci.Ptr(roci.ub4).TO),
- roci.OCI_ATTR_SCALE,
- self.environment.errorHandle)
- self.environment.checkForError(
- status,
- "Cursor_ItemDescription(): scale")
- scale = rffi.cast(lltype.Signed, attrptr[0])
- finally:
- lltype.free(attrptr, flavor='raw')
-
- attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub2).TO, 1,
- flavor='raw')
- try:
- status = roci.OCIAttrGet(
- param, roci.OCI_HTYPE_DESCRIBE,
- rffi.cast(roci.dvoidp, attrptr),
- lltype.nullptr(roci.Ptr(roci.ub4).TO),
- roci.OCI_ATTR_PRECISION,
- self.environment.errorHandle)
- self.environment.checkForError(
- status,
- "Cursor_ItemDescription(): precision")
- precision = rffi.cast(lltype.Signed, attrptr[0])
- finally:
- lltype.free(attrptr, flavor='raw')
- else:
- scale = 0
- precision = 0
-
- # lookup whether null is permitted for the attribute
- attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub1).TO, 1,
- flavor='raw')
- try:
- status = roci.OCIAttrGet(
- param, roci.OCI_HTYPE_DESCRIBE,
- rffi.cast(roci.dvoidp, attrptr),
- lltype.nullptr(roci.Ptr(roci.ub4).TO),
- roci.OCI_ATTR_IS_NULL,
- self.environment.errorHandle)
- self.environment.checkForError(
- status,
- "Cursor_ItemDescription(): nullable")
- nullable = rffi.cast(lltype.Signed, attrptr[0]) != 0
- finally:
- lltype.free(attrptr, flavor='raw')
-
- # set display size based on data type
- if varType is interp_variable.VT_String:
- displaySize = internalSize
- elif varType is interp_variable.VT_NationalCharString:
- displaySize = internalSize / 2
- elif varType is interp_variable.VT_Binary:
- displaySize = internalSize
- elif varType is interp_variable.VT_FixedChar:
- displaySize = internalSize
- elif varType is interp_variable.VT_FixedNationalChar:
- displaySize = internalSize / 2
- elif varType is interp_variable.VT_Float:
- if precision:
- displaySize = precision + 1
- if scale > 0:
- displaySize += scale + 1
- else:
- displaySize = 127
- elif varType is interp_variable.VT_DateTime:
- displaySize = 23
- else:
- displaySize = -1
-
- # return the tuple
- return [space.wrap(name), space.gettypeobject(varType.typedef),
- space.wrap(displaySize), space.wrap(internalSize),
- space.wrap(precision), space.wrap(scale),
- space.wrap(nullable)]
-
- finally:
- roci.OCIDescriptorFree(param, roci.OCI_DTYPE_PARAM)
-
- def _setBindVariablesByPos(self, space,
- w_vars, numElements, arrayPos, defer):
- "handle positional binds"
- # make sure positional and named binds are not being intermixed
- if self.bindDict is not None:
- raise OperationError(
- get(space).w_ProgrammingError,
- space.wrap("positional and named binds cannot be intermixed"))
-
- if self.bindList is None:
- self.bindList = []
-
- vars_w = space.fixedview(w_vars)
- for i in range(len(vars_w)):
- w_value = vars_w[i]
- if i < len(self.bindList):
- origVar = self.bindList[i]
- if space.is_w(origVar, space.w_None):
- origVar = None
- else:
- origVar = None
- newVar = self._setBindVariableHelper(space, w_value, origVar,
- numElements, arrayPos, defer)
- if newVar:
- if i < len(self.bindList):
- self.bindList[i] = newVar
- else:
- assert i == len(self.bindList)
- self.bindList.append(newVar)
-
- def _setBindVariablesByName(self, space,
- w_vars, numElements, arrayPos, defer):
- "handle named binds"
- # make sure positional and named binds are not being intermixed
- if self.bindList is not None:
- raise OperationError(
- get(space).w_ProgrammingError,
- space.wrap("positional and named binds cannot be intermixed"))
-
- if self.bindDict is None:
- self.bindDict = space.newdict()
-
- items = space.fixedview(space.call_method(w_vars, "iteritems"))
- for item in items:
- w_key, w_value = space.fixedview(item, 2)
- origVar = space.finditem(self.bindDict, w_key)
- newVar = self._setBindVariableHelper(space, w_value, origVar,
- numElements, arrayPos, defer)
- if newVar:
- space.setitem(self.bindDict, w_key, newVar)
-
- def _setBindVariableHelper(self, space, w_value, origVar,
- numElements, arrayPos, defer):
-
- valueIsVariable = space.isinstance_w(w_value, get(space).w_Variable)
- newVar = None
-
- # handle case where variable is already bound
- if origVar:
- assert isinstance(origVar, interp_variable.W_Variable)
-
- # if the value is a variable object, rebind it if necessary
- if valueIsVariable:
- newVar = space.interp_w(interp_variable.W_Variable, w_value)
- assert isinstance(newVar, interp_variable.W_Variable)
- if newVar == origVar:
- newVar = None
-
- # if the number of elements has changed, create a new variable
- # this is only necessary for executemany() since execute() always
- # passes a value of 1 for the number of elements
- elif numElements > origVar.allocatedElements:
- newVar = origVar.clone(
- self, numElements, origVar.size)
- assert isinstance(newVar, interp_variable.W_Variable)
- newVar.setValue(space, arrayPos, w_value)
-
- # otherwise, attempt to set the value
- else:
- try:
- origVar.setValue(space, arrayPos, w_value)
- except OperationError, e:
- # executemany() should simply fail after the first element
- if arrayPos > 0:
- raise
- # anything other than IndexError or TypeError should fail
- if (not e.match(space, space.w_IndexError) and
- not e.match(space, space.w_TypeError)):
- raise
- # catch the exception and try to create a new variable
- origVar = None
-
- if not origVar:
- # if the value is a variable object, bind it directly
- if valueIsVariable:
- newVar = space.interp_w(interp_variable.W_Variable, w_value)
- assert isinstance(newVar, interp_variable.W_Variable)
- newVar.boundPos = 0
- newVar.boundName = None
-
- # otherwise, create a new variable, unless the value is None and
- # we wish to defer type assignment
- elif not space.is_w(w_value, space.w_None) or not defer:
- newVar = interp_variable.newVariableByValue(space, self,
- w_value,
- numElements)
- assert isinstance(newVar, interp_variable.W_Variable)
- newVar.setValue(space, arrayPos, w_value)
-
- assert newVar is None or isinstance(newVar, interp_variable.W_Variable)
- return newVar
-
- def _performBind(self, space):
- # set values and perform binds for all bind variables
- if self.bindList:
- for i in range(len(self.bindList)):
- var = self.bindList[i]
- assert isinstance(var, interp_variable.W_Variable)
- var.bind(space, self, None, i + 1)
- if self.bindDict:
- items_w = space.fixedview(
- space.call_method(self.bindDict, "iteritems"))
- for w_item in items_w:
- w_key, var = space.fixedview(w_item, 2)
- assert isinstance(var, interp_variable.W_Variable)
- var.bind(space, self, w_key, 0)
-
- # ensure that input sizes are reset
- self.setInputSizes = False
-
- def _setRowCount(self):
- if self.statementType == roci.OCI_STMT_SELECT:
- self.rowCount = 0
- self.actualRows = -1
- self.rowNum = 0
- elif self.statementType in (roci.OCI_STMT_INSERT,
- roci.OCI_STMT_UPDATE,
- roci.OCI_STMT_DELETE):
- attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO,
- 1, flavor='raw')
- try:
- status = roci.OCIAttrGet(
- self.handle, roci.OCI_HTYPE_STMT,
- rffi.cast(roci.dvoidp, attrptr),
- lltype.nullptr(roci.Ptr(roci.ub4).TO),
- roci.OCI_ATTR_ROW_COUNT,
- self.environment.errorHandle)
-
- self.environment.checkForError(
- status, "Cursor_SetRowCount()")
- self.rowCount = rffi.cast(lltype.Signed, attrptr[0])
- finally:
- lltype.free(attrptr, flavor='raw')
- else:
- self.rowCount = -1
-
- def _performDefine(self):
- # determine number of items in select-list
- attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO,
- 1, flavor='raw')
- try:
- status = roci.OCIAttrGet(
- self.handle, roci.OCI_HTYPE_STMT,
- rffi.cast(roci.dvoidp, attrptr),
- lltype.nullptr(roci.Ptr(roci.ub4).TO),
- roci.OCI_ATTR_PARAM_COUNT,
- self.environment.errorHandle)
-
- self.environment.checkForError(
- status, "Cursor_PerformDefine()")
- numParams = attrptr[0]
- finally:
- lltype.free(attrptr, flavor='raw')
-
- self.fetchVariables = []
-
- # define a variable for each select-item
- self.fetchArraySize = self.arraySize
- for i in range(numParams):
- var = interp_variable.define(self, i+1, self.fetchArraySize)
- assert isinstance(var, interp_variable.W_Variable)
- self.fetchVariables.append(var)
-
- def _verifyFetch(self, space):
- # make sure the cursor is open
- self._checkOpen(space)
-
- # fixup bound cursor, if necessary
- self._fixupBoundCursor()
-
- # make sure the cursor is for a query
- if self.statementType != roci.OCI_STMT_SELECT:
- raise OperationError(
- get(space).w_InterfaceError,
- space.wrap("not a query"))
-
- def _fixupBoundCursor(self):
- if self.handle and self.statementType < 0:
- self._getStatementType()
- if self.statementType == roci.OCI_STMT_SELECT:
- self._performDefine()
- self._setRowCount()
-
- def fetchone(self, space):
- # verify fetch can be performed
- self._verifyFetch(space)
-
- # setup return value
- if self._moreRows(space):
- return self._createRow(space)
-
- return space.w_None
-
- def fetchmany(self, space, w_numRows=None):
- if w_numRows is not None:
- numRows = space.int_w(w_numRows)
- else:
- numRows = self.arraySize
-
- # verify fetch can be performed
- self._verifyFetch(space)
-
- return self._multiFetch(space, limit=numRows)
-
- def fetchall(self, space):
- # verify fetch can be performed
- self._verifyFetch(space)
-
- return self._multiFetch(space, limit=0)
-
- def descr_iter(self, space):
- self._verifyFetch(space)
- return space.wrap(self)
-
- def descr_next(self, space):
- # verify fetch can be performed
- self._verifyFetch(space)
-
- # setup return value
- if self._moreRows(space):
- return self._createRow(space)
-
- raise OperationError(space.w_StopIteration, space.w_None)
-
- def _moreRows(self, space):
- if self.rowNum < self.actualRows:
- return True
- if self.actualRows < 0 or self.actualRows == self.fetchArraySize:
- self._internalFetch(space, self.fetchArraySize)
- if self.rowNum < self.actualRows:
- return True
-
- return False
-
- def _internalFetch(self, space, numRows):
- if not self.fetchVariables:
- raise OperationError(
- get(space).w_InterfaceError,
- space.wrap("query not executed"))
-
- status = roci.OCIStmtFetch(
- self.handle,
- self.environment.errorHandle,
- numRows,
- roci.OCI_FETCH_NEXT,
- roci.OCI_DEFAULT)
-
- if status != roci.OCI_NO_DATA:
- self.environment.checkForError(
- status,
- "Cursor_InternalFetch(): fetch")
-
- for var in self.fetchVariables:
- assert isinstance(var, interp_variable.W_Variable)
- var.internalFetchNum += 1
-
- attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO,
- 1, flavor='raw')
- try:
- status = roci.OCIAttrGet(
- self.handle, roci.OCI_HTYPE_STMT,
- rffi.cast(roci.dvoidp, attrptr),
- lltype.nullptr(roci.Ptr(roci.ub4).TO),
- roci.OCI_ATTR_ROW_COUNT,
- self.environment.errorHandle)
-
- self.environment.checkForError(
- status, "Cursor_InternalFetch(): row count")
-
- self.actualRows = (rffi.cast(lltype.Signed, attrptr[0])
- - self.rowCount)
- self.rowNum = 0
- finally:
- lltype.free(attrptr, flavor='raw')
-
- def _multiFetch(self, space, limit=0):
- results_w = []
- rowNum = 0
-
- # fetch as many rows as possible
- while limit == 0 or rowNum < limit:
- rowNum += 1
- if not self._moreRows(space):
- break
- w_row = self._createRow(space)
- results_w.append(w_row)
- return space.newlist(results_w)
-
- def _createRow(self, space):
- items_w = []
- # acquire the value for each item
- for var in self.fetchVariables:
- assert isinstance(var, interp_variable.W_Variable)
- w_item = var.getValue(space, self.rowNum)
- items_w.append(w_item)
-
- # increment row counters
- self.rowNum += 1
- self.rowCount += 1
-
- w_row = space.newtuple(items_w)
-
- # if a row factory is defined, call it
- if self.w_rowFactory:
- w_row = space.call(self.w_rowFactory, w_row)
-
- return w_row
-
- def _get_bind_info(self, space, numElements):
- # avoid bus errors on 64bit platforms
- numElements = numElements + (rffi.sizeof(roci.dvoidp) -
- numElements % rffi.sizeof(roci.dvoidp))
- # initialize the buffers
- bindNames = lltype.malloc(roci.Ptr(roci.oratext).TO,
- numElements, flavor='raw')
- bindNameLengths = lltype.malloc(roci.Ptr(roci.ub1).TO,
- numElements, flavor='raw')
- indicatorNames = lltype.malloc(roci.Ptr(roci.oratext).TO,
- numElements, flavor='raw')
- indicatorNameLengths = lltype.malloc(roci.Ptr(roci.ub1).TO,
- numElements, flavor='raw')
- duplicate = lltype.malloc(roci.Ptr(roci.ub1).TO,
- numElements, flavor='raw')
- bindHandles = lltype.malloc(roci.Ptr(roci.OCIBind).TO,
- numElements, flavor='raw')
-
- foundElementsPtr = lltype.malloc(roci.Ptr(roci.sb4).TO, 1,
- flavor='raw')
-
- try:
- status = roci.OCIStmtGetBindInfo(
- self.handle,
- self.environment.errorHandle,
- numElements,
- 1,
- foundElementsPtr,
- bindNames, bindNameLengths,
- indicatorNames, indicatorNameLengths,
- duplicate, bindHandles)
- if status != roci.OCI_NO_DATA:
- self.environment.checkForError(
- status, "Cursor_GetBindNames()")
-
- # Too few elements allocated
- foundElements = rffi.cast(lltype.Signed, foundElementsPtr[0])
- if foundElements < 0:
- return -foundElements, None
-
- names_w = []
- # process the bind information returned
- for i in range(foundElements):
- if rffi.cast(lltype.Signed, duplicate[i]):
- continue
- names_w.append(
- w_string(space,
- bindNames[i],
- rffi.cast(lltype.Signed, bindNameLengths[i])))
-
- return 0, names_w
- finally:
- lltype.free(bindNames, flavor='raw')
- lltype.free(bindNameLengths, flavor='raw')
- lltype.free(indicatorNames, flavor='raw')
- lltype.free(indicatorNameLengths, flavor='raw')
- lltype.free(duplicate, flavor='raw')
- lltype.free(bindHandles, flavor='raw')
- lltype.free(foundElementsPtr, flavor='raw')
-
- def bindnames(self, space):
- # make sure the cursor is open
- self._checkOpen(space)
-
- # ensure that a statement has already been prepared
- if not self.w_statement:
- raise OperationError(get(space).w_ProgrammingError,
- space.wrap("statement must be prepared first"))
-
- nbElements, names = self._get_bind_info(space, 8)
- if nbElements:
- _, names = self._get_bind_info(space, nbElements)
- return space.newlist(names)
-
- @unwrap_spec(size=int)
- def var(self, space, w_type, size=0, w_arraysize=None,
- w_inconverter=None, w_outconverter=None):
- if space.is_none(w_arraysize):
- arraySize = self.bindArraySize
- else:
- arraySize = space.int_w(w_arraysize)
-
- # determine the type of variable
- varType = interp_variable.typeByPythonType(space, self, w_type)
- if varType.isVariableLength and size == 0:
- size = varType.size
-
- # create the variable
- var = varType(self, arraySize, size)
- var.w_inconverter = w_inconverter
- var.w_outconverter = w_outconverter
-
- return space.wrap(var)
-
- @unwrap_spec(size=int)
- def arrayvar(self, space, w_type, w_value, size=0):
- # determine the type of variable
- varType = interp_variable.typeByPythonType(space, self, w_type)
- if varType.isVariableLength and size == 0:
- size = varType.size
-
- # determine the number of elements to create
- if space.isinstance_w(w_value, space.w_list):
- numElements = space.len_w(w_value)
- elif space.isinstance_w(w_value, space.w_int):
- numElements = space.int_w(w_value)
- else:
- raise OperationError(
- get(space).w_NotSupportedError,
- space.wrap("expecting integer or list of values"))
-
- # create the variable
- var = varType(self, numElements, size)
- var.makeArray(space)
-
- # set the value, if applicable
- if space.isinstance_w(w_value, space.w_list):
- var.setArrayValue(space, w_value)
-
- return var
-
- def setinputsizes(self, space, __args__):
- args_w, kw_w = __args__.unpack()
-
- # only expect keyword arguments or positional arguments, not both
- if args_w and kw_w:
- raise OperationError(
- interp_error.get(space).w_InterfaceError,
- space.wrap(
- "expecting argument or keyword arguments, not both"))
-
- # make sure the cursor is open
- self._checkOpen(space)
-
- # eliminate existing bind variables
- self.bindList = None
- self.bindDict = None
-
- self.setInputSizes = True
-
- # process each input
- if kw_w:
- self.bindDict = space.newdict()
- for key, w_value in kw_w.iteritems():
- var = interp_variable.newVariableByType(
- space, self, w_value, self.bindArraySize)
- space.setitem(self.bindDict, space.wrap(key), var)
- return self.bindDict
- else:
- self.bindList = [None] * len(args_w)
- for i in range(len(args_w)):
- w_value = args_w[i]
- if space.is_w(w_value, space.w_None):
- var = None
- else:
- var = interp_variable.newVariableByType(
- space, self, w_value, self.bindArraySize)
- self.bindList[i] = var
- return space.newlist(self.bindList)
-
- @unwrap_spec(outputSize=int, outputSizeColumn=int)
- def setoutputsize(self, space, outputSize, outputSizeColumn=-1):
- self.outputSize = outputSize
- self.outputSizeColumn = outputSizeColumn
-
-
- def arraysize_get(self, space):
- return space.wrap(self.arraySize)
- def arraysize_set(self, space, w_value):
- self.arraySize = space.int_w(w_value)
-
- def bindarraysize_get(self, space):
- return space.wrap(self.bindArraySize)
- def bindarraysize_set(self, space, w_value):
- self.bindArraySize = space.int_w(w_value)
-
- def bindvars_get(self, space):
- if self.bindList:
- return space.newlist(self.bindList)
- if self.bindDict:
- return self.bindDict
-
- def fetchvars_get(self, space):
- return space.newlist(self.fetchVariables)
-
-W_Cursor.typedef = TypeDef(
- 'Cursor',
- execute = interp2app(W_Cursor.execute),
- executemany = interp2app(W_Cursor.executemany),
- prepare = interp2app(W_Cursor.prepare),
- fetchone = interp2app(W_Cursor.fetchone),
- fetchmany = interp2app(W_Cursor.fetchmany),
- fetchall = interp2app(W_Cursor.fetchall),
- close = interp2app(W_Cursor.close),
- bindnames = interp2app(W_Cursor.bindnames),
- callfunc = interp2app(W_Cursor.callfunc),
- callproc = interp2app(W_Cursor.callproc),
- var = interp2app(W_Cursor.var),
- arrayvar = interp2app(W_Cursor.arrayvar),
- setinputsizes = interp2app(W_Cursor.setinputsizes),
- setoutputsize = interp2app(W_Cursor.setoutputsize),
-
- __iter__ = interp2app(W_Cursor.descr_iter),
- next = interp2app(W_Cursor.descr_next),
-
- arraysize = GetSetProperty(W_Cursor.arraysize_get,
- W_Cursor.arraysize_set),
- bindarraysize = GetSetProperty(W_Cursor.bindarraysize_get,
- W_Cursor.bindarraysize_set),
- rowcount = interp_attrproperty('rowCount', W_Cursor),
- statement = interp_attrproperty_w('w_statement', W_Cursor),
- bindvars = GetSetProperty(W_Cursor.bindvars_get),
- fetchvars = GetSetProperty(W_Cursor.fetchvars_get),
- description = GetSetProperty(W_Cursor.getDescription),
-)
diff --git a/pypy/module/oracle/interp_environ.py b/pypy/module/oracle/interp_environ.py
deleted file mode 100644
--- a/pypy/module/oracle/interp_environ.py
+++ /dev/null
@@ -1,99 +0,0 @@
-from rpython.rtyper.lltypesystem import rffi, lltype
-from pypy.module.oracle import roci, config
-from pypy.interpreter.error import OperationError
-
-from pypy.module.oracle.interp_error import W_Error, get
-
-class Environment(object):
- def __init__(self, space, handle):
- self.space = space
- self.handle = handle
-
- # create the error handle
- handleptr = lltype.malloc(rffi.CArrayPtr(roci.OCIError).TO,
- 1, flavor='raw')
- try:
- status = roci.OCIHandleAlloc(
- self.handle,
- handleptr, roci.OCI_HTYPE_ERROR, 0,
- lltype.nullptr(rffi.CArray(roci.dvoidp)))
- self.checkForError(
- status, "Environment_New(): create error handle")
- self.errorHandle = handleptr[0]
- finally:
- lltype.free(handleptr, flavor='raw')
-
-
- def checkForError(self, status, context):
- if status in (roci.OCI_SUCCESS, roci.OCI_SUCCESS_WITH_INFO):
- return
-
- if status != roci.OCI_INVALID_HANDLE:
- # At this point it is assumed that the Oracle
- # environment is fully initialized
- error = W_Error(self.space, self, context, 1)
- if error.code in (1, 1400, 2290, 2291, 2292):
- w_type = get(self.space).w_IntegrityError
- elif error.code in (1012, 1033, 1034, 1089, 3113, 3114,
- 12203, 12500, 12571):
- w_type = get(self.space).w_OperationalError
- else:
- w_type = get(self.space).w_DatabaseError
- raise OperationError(w_type, self.space.wrap(error))
-
- error = W_Error(self.space, self, context, 0)
- error.code = 0
- error.w_message = self.space.wrap("Invalid handle!")
- raise OperationError(get(self.space).w_DatabaseError,
- self.space.wrap(error))
-
- @staticmethod
- def create(space, threaded, events):
- "Create a new environment object from scratch"
- mode = roci.OCI_OBJECT
- if threaded:
- mode |= roci.OCI_THREADED
- if events:
- mode |= roci.OCI_EVENTS
-
- handleptr = lltype.malloc(rffi.CArrayPtr(roci.OCIEnv).TO,
- 1, flavor='raw')
-
- try:
-
- status = roci.OCIEnvNlsCreate(
- handleptr, mode,
- None,
- None, None, None,
- 0, lltype.nullptr(rffi.CArray(roci.dvoidp)),
- config.CHARSETID, config.CHARSETID)
-
- if not handleptr[0] or status not in (roci.OCI_SUCCESS,
- roci.OCI_SUCCESS_WITH_INFO):
- raise OperationError(
- get(space).w_InterfaceError,
- space.wrap(
- "Unable to acquire Oracle environment handle"))
-
- handle = handleptr[0]
- finally:
- lltype.free(handleptr, flavor='raw')
-
- try:
- newenv = Environment(space, handle)
- except:
- roci.OCIHandleFree(handle, roci.OCI_HTYPE_ENV)
- raise
-
- newenv.maxBytesPerCharacter = config.BYTES_PER_CHAR
- newenv.maxStringBytes = config.BYTES_PER_CHAR * config.MAX_STRING_CHARS
More information about the pypy-commit
mailing list