zxjdbc.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. # oracle/zxjdbc.py
  2. # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """
  8. .. dialect:: oracle+zxjdbc
  9. :name: zxJDBC for Jython
  10. :dbapi: zxjdbc
  11. :connectstring: oracle+zxjdbc://user:pass@host/dbname
  12. :driverurl: http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html
  13. .. note:: Jython is not supported by current versions of SQLAlchemy. The
  14. zxjdbc dialect should be considered as experimental.
  15. """
  16. import decimal
  17. import re
  18. from sqlalchemy import sql, types as sqltypes, util
  19. from sqlalchemy.connectors.zxJDBC import ZxJDBCConnector
  20. from sqlalchemy.dialects.oracle.base import (OracleCompiler,
  21. OracleDialect,
  22. OracleExecutionContext)
  23. from sqlalchemy.engine import result as _result
  24. from sqlalchemy.sql import expression
  25. import collections
  26. SQLException = zxJDBC = None
  27. class _ZxJDBCDate(sqltypes.Date):
  28. def result_processor(self, dialect, coltype):
  29. def process(value):
  30. if value is None:
  31. return None
  32. else:
  33. return value.date()
  34. return process
  35. class _ZxJDBCNumeric(sqltypes.Numeric):
  36. def result_processor(self, dialect, coltype):
  37. # XXX: does the dialect return Decimal or not???
  38. # if it does (in all cases), we could use a None processor as well as
  39. # the to_float generic processor
  40. if self.asdecimal:
  41. def process(value):
  42. if isinstance(value, decimal.Decimal):
  43. return value
  44. else:
  45. return decimal.Decimal(str(value))
  46. else:
  47. def process(value):
  48. if isinstance(value, decimal.Decimal):
  49. return float(value)
  50. else:
  51. return value
  52. return process
  53. class OracleCompiler_zxjdbc(OracleCompiler):
  54. def returning_clause(self, stmt, returning_cols):
  55. self.returning_cols = list(
  56. expression._select_iterables(returning_cols))
  57. # within_columns_clause=False so that labels (foo AS bar) don't render
  58. columns = [self.process(c, within_columns_clause=False)
  59. for c in self.returning_cols]
  60. if not hasattr(self, 'returning_parameters'):
  61. self.returning_parameters = []
  62. binds = []
  63. for i, col in enumerate(self.returning_cols):
  64. dbtype = col.type.dialect_impl(
  65. self.dialect).get_dbapi_type(self.dialect.dbapi)
  66. self.returning_parameters.append((i + 1, dbtype))
  67. bindparam = sql.bindparam(
  68. "ret_%d" % i, value=ReturningParam(dbtype))
  69. self.binds[bindparam.key] = bindparam
  70. binds.append(
  71. self.bindparam_string(self._truncate_bindparam(bindparam)))
  72. return 'RETURNING ' + ', '.join(columns) + " INTO " + ", ".join(binds)
  73. class OracleExecutionContext_zxjdbc(OracleExecutionContext):
  74. def pre_exec(self):
  75. if hasattr(self.compiled, 'returning_parameters'):
  76. # prepare a zxJDBC statement so we can grab its underlying
  77. # OraclePreparedStatement's getReturnResultSet later
  78. self.statement = self.cursor.prepare(self.statement)
  79. def get_result_proxy(self):
  80. if hasattr(self.compiled, 'returning_parameters'):
  81. rrs = None
  82. try:
  83. try:
  84. rrs = self.statement.__statement__.getReturnResultSet()
  85. next(rrs)
  86. except SQLException as sqle:
  87. msg = '%s [SQLCode: %d]' % (
  88. sqle.getMessage(), sqle.getErrorCode())
  89. if sqle.getSQLState() is not None:
  90. msg += ' [SQLState: %s]' % sqle.getSQLState()
  91. raise zxJDBC.Error(msg)
  92. else:
  93. row = tuple(
  94. self.cursor.datahandler.getPyObject(
  95. rrs, index, dbtype)
  96. for index, dbtype in
  97. self.compiled.returning_parameters)
  98. return ReturningResultProxy(self, row)
  99. finally:
  100. if rrs is not None:
  101. try:
  102. rrs.close()
  103. except SQLException:
  104. pass
  105. self.statement.close()
  106. return _result.ResultProxy(self)
  107. def create_cursor(self):
  108. cursor = self._dbapi_connection.cursor()
  109. cursor.datahandler = self.dialect.DataHandler(cursor.datahandler)
  110. return cursor
  111. class ReturningResultProxy(_result.FullyBufferedResultProxy):
  112. """ResultProxy backed by the RETURNING ResultSet results."""
  113. def __init__(self, context, returning_row):
  114. self._returning_row = returning_row
  115. super(ReturningResultProxy, self).__init__(context)
  116. def _cursor_description(self):
  117. ret = []
  118. for c in self.context.compiled.returning_cols:
  119. if hasattr(c, 'name'):
  120. ret.append((c.name, c.type))
  121. else:
  122. ret.append((c.anon_label, c.type))
  123. return ret
  124. def _buffer_rows(self):
  125. return collections.deque([self._returning_row])
  126. class ReturningParam(object):
  127. """A bindparam value representing a RETURNING parameter.
  128. Specially handled by OracleReturningDataHandler.
  129. """
  130. def __init__(self, type):
  131. self.type = type
  132. def __eq__(self, other):
  133. if isinstance(other, ReturningParam):
  134. return self.type == other.type
  135. return NotImplemented
  136. def __ne__(self, other):
  137. if isinstance(other, ReturningParam):
  138. return self.type != other.type
  139. return NotImplemented
  140. def __repr__(self):
  141. kls = self.__class__
  142. return '<%s.%s object at 0x%x type=%s>' % (
  143. kls.__module__, kls.__name__, id(self), self.type)
  144. class OracleDialect_zxjdbc(ZxJDBCConnector, OracleDialect):
  145. jdbc_db_name = 'oracle'
  146. jdbc_driver_name = 'oracle.jdbc.OracleDriver'
  147. statement_compiler = OracleCompiler_zxjdbc
  148. execution_ctx_cls = OracleExecutionContext_zxjdbc
  149. colspecs = util.update_copy(
  150. OracleDialect.colspecs,
  151. {
  152. sqltypes.Date: _ZxJDBCDate,
  153. sqltypes.Numeric: _ZxJDBCNumeric
  154. }
  155. )
  156. def __init__(self, *args, **kwargs):
  157. super(OracleDialect_zxjdbc, self).__init__(*args, **kwargs)
  158. global SQLException, zxJDBC
  159. from java.sql import SQLException
  160. from com.ziclix.python.sql import zxJDBC
  161. from com.ziclix.python.sql.handler import OracleDataHandler
  162. class OracleReturningDataHandler(OracleDataHandler):
  163. """zxJDBC DataHandler that specially handles ReturningParam."""
  164. def setJDBCObject(self, statement, index, object, dbtype=None):
  165. if type(object) is ReturningParam:
  166. statement.registerReturnParameter(index, object.type)
  167. elif dbtype is None:
  168. OracleDataHandler.setJDBCObject(
  169. self, statement, index, object)
  170. else:
  171. OracleDataHandler.setJDBCObject(
  172. self, statement, index, object, dbtype)
  173. self.DataHandler = OracleReturningDataHandler
  174. def initialize(self, connection):
  175. super(OracleDialect_zxjdbc, self).initialize(connection)
  176. self.implicit_returning = \
  177. connection.connection.driverversion >= '10.2'
  178. def _create_jdbc_url(self, url):
  179. return 'jdbc:oracle:thin:@%s:%s:%s' % (
  180. url.host, url.port or 1521, url.database)
  181. def _get_server_version_info(self, connection):
  182. version = re.search(
  183. r'Release ([\d\.]+)', connection.connection.dbversion).group(1)
  184. return tuple(int(x) for x in version.split('.'))
  185. dialect = OracleDialect_zxjdbc