base.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. """
  2. Oracle database backend for Django.
  3. Requires oracledb: https://oracle.github.io/python-oracledb/
  4. """
  5. import datetime
  6. import decimal
  7. import os
  8. import platform
  9. from contextlib import contextmanager
  10. from django.conf import settings
  11. from django.core.exceptions import ImproperlyConfigured
  12. from django.db import IntegrityError
  13. from django.db.backends.base.base import BaseDatabaseWrapper
  14. from django.db.backends.oracle.oracledb_any import oracledb as Database
  15. from django.db.backends.utils import debug_transaction
  16. from django.utils.asyncio import async_unsafe
  17. from django.utils.encoding import force_bytes, force_str
  18. from django.utils.functional import cached_property
  19. from django.utils.version import get_version_tuple
  20. def _setup_environment(environ):
  21. # Cygwin requires some special voodoo to set the environment variables
  22. # properly so that Oracle will see them.
  23. if platform.system().upper().startswith("CYGWIN"):
  24. try:
  25. import ctypes
  26. except ImportError as e:
  27. raise ImproperlyConfigured(
  28. "Error loading ctypes: %s; "
  29. "the Oracle backend requires ctypes to "
  30. "operate correctly under Cygwin." % e
  31. )
  32. kernel32 = ctypes.CDLL("kernel32")
  33. for name, value in environ:
  34. kernel32.SetEnvironmentVariableA(name, value)
  35. else:
  36. os.environ.update(environ)
  37. _setup_environment(
  38. [
  39. # Oracle takes client-side character set encoding from the environment.
  40. ("NLS_LANG", ".AL32UTF8"),
  41. # This prevents Unicode from getting mangled by getting encoded into the
  42. # potentially non-Unicode database character set.
  43. ("ORA_NCHAR_LITERAL_REPLACE", "TRUE"),
  44. ]
  45. )
  46. # Some of these import oracledb, so import them after checking if it's
  47. # installed.
  48. from .client import DatabaseClient # NOQA
  49. from .creation import DatabaseCreation # NOQA
  50. from .features import DatabaseFeatures # NOQA
  51. from .introspection import DatabaseIntrospection # NOQA
  52. from .operations import DatabaseOperations # NOQA
  53. from .schema import DatabaseSchemaEditor # NOQA
  54. from .utils import Oracle_datetime, dsn # NOQA
  55. from .validation import DatabaseValidation # NOQA
  56. @contextmanager
  57. def wrap_oracle_errors():
  58. try:
  59. yield
  60. except Database.DatabaseError as e:
  61. # oracledb raises a oracledb.DatabaseError exception with the
  62. # following attributes and values:
  63. # code = 2091
  64. # message = 'ORA-02091: transaction rolled back
  65. # 'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS
  66. # _C00102056) violated - parent key not found'
  67. # or:
  68. # 'ORA-00001: unique constraint (DJANGOTEST.DEFERRABLE_
  69. # PINK_CONSTRAINT) violated
  70. # Convert that case to Django's IntegrityError exception.
  71. x = e.args[0]
  72. if (
  73. hasattr(x, "code")
  74. and hasattr(x, "message")
  75. and x.code == 2091
  76. and ("ORA-02291" in x.message or "ORA-00001" in x.message)
  77. ):
  78. raise IntegrityError(*tuple(e.args))
  79. raise
  80. class _UninitializedOperatorsDescriptor:
  81. def __get__(self, instance, cls=None):
  82. # If connection.operators is looked up before a connection has been
  83. # created, transparently initialize connection.operators to avert an
  84. # AttributeError.
  85. if instance is None:
  86. raise AttributeError("operators not available as class attribute")
  87. # Creating a cursor will initialize the operators.
  88. instance.cursor().close()
  89. return instance.__dict__["operators"]
  90. class DatabaseWrapper(BaseDatabaseWrapper):
  91. vendor = "oracle"
  92. display_name = "Oracle"
  93. # This dictionary maps Field objects to their associated Oracle column
  94. # types, as strings. Column-type strings can contain format strings; they'll
  95. # be interpolated against the values of Field.__dict__ before being output.
  96. # If a column type is set to None, it won't be included in the output.
  97. #
  98. # Any format strings starting with "qn_" are quoted before being used in the
  99. # output (the "qn_" prefix is stripped before the lookup is performed.
  100. data_types = {
  101. "AutoField": "NUMBER(11) GENERATED BY DEFAULT ON NULL AS IDENTITY",
  102. "BigAutoField": "NUMBER(19) GENERATED BY DEFAULT ON NULL AS IDENTITY",
  103. "BinaryField": "BLOB",
  104. "BooleanField": "NUMBER(1)",
  105. "CharField": "NVARCHAR2(%(max_length)s)",
  106. "DateField": "DATE",
  107. "DateTimeField": "TIMESTAMP",
  108. "DecimalField": "NUMBER(%(max_digits)s, %(decimal_places)s)",
  109. "DurationField": "INTERVAL DAY(9) TO SECOND(6)",
  110. "FileField": "NVARCHAR2(%(max_length)s)",
  111. "FilePathField": "NVARCHAR2(%(max_length)s)",
  112. "FloatField": "DOUBLE PRECISION",
  113. "IntegerField": "NUMBER(11)",
  114. "JSONField": "NCLOB",
  115. "BigIntegerField": "NUMBER(19)",
  116. "IPAddressField": "VARCHAR2(15)",
  117. "GenericIPAddressField": "VARCHAR2(39)",
  118. "OneToOneField": "NUMBER(11)",
  119. "PositiveBigIntegerField": "NUMBER(19)",
  120. "PositiveIntegerField": "NUMBER(11)",
  121. "PositiveSmallIntegerField": "NUMBER(11)",
  122. "SlugField": "NVARCHAR2(%(max_length)s)",
  123. "SmallAutoField": "NUMBER(5) GENERATED BY DEFAULT ON NULL AS IDENTITY",
  124. "SmallIntegerField": "NUMBER(11)",
  125. "TextField": "NCLOB",
  126. "TimeField": "TIMESTAMP",
  127. "URLField": "VARCHAR2(%(max_length)s)",
  128. "UUIDField": "VARCHAR2(32)",
  129. }
  130. data_type_check_constraints = {
  131. "BooleanField": "%(qn_column)s IN (0,1)",
  132. "JSONField": "%(qn_column)s IS JSON",
  133. "PositiveBigIntegerField": "%(qn_column)s >= 0",
  134. "PositiveIntegerField": "%(qn_column)s >= 0",
  135. "PositiveSmallIntegerField": "%(qn_column)s >= 0",
  136. }
  137. # Oracle doesn't support a database index on these columns.
  138. _limited_data_types = ("clob", "nclob", "blob")
  139. operators = _UninitializedOperatorsDescriptor()
  140. _standard_operators = {
  141. "exact": "= %s",
  142. "iexact": "= UPPER(%s)",
  143. "contains": (
  144. "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)"
  145. ),
  146. "icontains": (
  147. "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) "
  148. "ESCAPE TRANSLATE('\\' USING NCHAR_CS)"
  149. ),
  150. "gt": "> %s",
  151. "gte": ">= %s",
  152. "lt": "< %s",
  153. "lte": "<= %s",
  154. "startswith": (
  155. "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)"
  156. ),
  157. "endswith": (
  158. "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)"
  159. ),
  160. "istartswith": (
  161. "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) "
  162. "ESCAPE TRANSLATE('\\' USING NCHAR_CS)"
  163. ),
  164. "iendswith": (
  165. "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) "
  166. "ESCAPE TRANSLATE('\\' USING NCHAR_CS)"
  167. ),
  168. }
  169. _likec_operators = {
  170. **_standard_operators,
  171. "contains": "LIKEC %s ESCAPE '\\'",
  172. "icontains": "LIKEC UPPER(%s) ESCAPE '\\'",
  173. "startswith": "LIKEC %s ESCAPE '\\'",
  174. "endswith": "LIKEC %s ESCAPE '\\'",
  175. "istartswith": "LIKEC UPPER(%s) ESCAPE '\\'",
  176. "iendswith": "LIKEC UPPER(%s) ESCAPE '\\'",
  177. }
  178. # The patterns below are used to generate SQL pattern lookup clauses when
  179. # the right-hand side of the lookup isn't a raw string (it might be an expression
  180. # or the result of a bilateral transformation).
  181. # In those cases, special characters for LIKE operators (e.g. \, %, _)
  182. # should be escaped on the database side.
  183. #
  184. # Note: we use str.format() here for readability as '%' is used as a wildcard for
  185. # the LIKE operator.
  186. pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\', '\\'), '%%', '\%%'), '_', '\_')"
  187. _pattern_ops = {
  188. "contains": "'%%' || {} || '%%'",
  189. "icontains": "'%%' || UPPER({}) || '%%'",
  190. "startswith": "{} || '%%'",
  191. "istartswith": "UPPER({}) || '%%'",
  192. "endswith": "'%%' || {}",
  193. "iendswith": "'%%' || UPPER({})",
  194. }
  195. _standard_pattern_ops = {
  196. k: "LIKE TRANSLATE( " + v + " USING NCHAR_CS)"
  197. " ESCAPE TRANSLATE('\\' USING NCHAR_CS)"
  198. for k, v in _pattern_ops.items()
  199. }
  200. _likec_pattern_ops = {
  201. k: "LIKEC " + v + " ESCAPE '\\'" for k, v in _pattern_ops.items()
  202. }
  203. Database = Database
  204. SchemaEditorClass = DatabaseSchemaEditor
  205. # Classes instantiated in __init__().
  206. client_class = DatabaseClient
  207. creation_class = DatabaseCreation
  208. features_class = DatabaseFeatures
  209. introspection_class = DatabaseIntrospection
  210. ops_class = DatabaseOperations
  211. validation_class = DatabaseValidation
  212. def __init__(self, *args, **kwargs):
  213. super().__init__(*args, **kwargs)
  214. use_returning_into = self.settings_dict["OPTIONS"].get(
  215. "use_returning_into", True
  216. )
  217. self.features.can_return_columns_from_insert = use_returning_into
  218. def get_database_version(self):
  219. return self.oracle_version
  220. def get_connection_params(self):
  221. conn_params = self.settings_dict["OPTIONS"].copy()
  222. if "use_returning_into" in conn_params:
  223. del conn_params["use_returning_into"]
  224. return conn_params
  225. @async_unsafe
  226. def get_new_connection(self, conn_params):
  227. return Database.connect(
  228. user=self.settings_dict["USER"],
  229. password=self.settings_dict["PASSWORD"],
  230. dsn=dsn(self.settings_dict),
  231. **conn_params,
  232. )
  233. def init_connection_state(self):
  234. super().init_connection_state()
  235. cursor = self.create_cursor()
  236. # Set the territory first. The territory overrides NLS_DATE_FORMAT
  237. # and NLS_TIMESTAMP_FORMAT to the territory default. When all of
  238. # these are set in single statement it isn't clear what is supposed
  239. # to happen.
  240. cursor.execute("ALTER SESSION SET NLS_TERRITORY = 'AMERICA'")
  241. # Set Oracle date to ANSI date format. This only needs to execute
  242. # once when we create a new connection. We also set the Territory
  243. # to 'AMERICA' which forces Sunday to evaluate to a '1' in
  244. # TO_CHAR().
  245. cursor.execute(
  246. "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'"
  247. " NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'"
  248. + (" TIME_ZONE = 'UTC'" if settings.USE_TZ else "")
  249. )
  250. cursor.close()
  251. if "operators" not in self.__dict__:
  252. # Ticket #14149: Check whether our LIKE implementation will
  253. # work for this connection or we need to fall back on LIKEC.
  254. # This check is performed only once per DatabaseWrapper
  255. # instance per thread, since subsequent connections will use
  256. # the same settings.
  257. cursor = self.create_cursor()
  258. try:
  259. cursor.execute(
  260. "SELECT 1 FROM DUAL WHERE DUMMY %s"
  261. % self._standard_operators["contains"],
  262. ["X"],
  263. )
  264. except Database.DatabaseError:
  265. self.operators = self._likec_operators
  266. self.pattern_ops = self._likec_pattern_ops
  267. else:
  268. self.operators = self._standard_operators
  269. self.pattern_ops = self._standard_pattern_ops
  270. cursor.close()
  271. self.connection.stmtcachesize = 20
  272. # Ensure all changes are preserved even when AUTOCOMMIT is False.
  273. if not self.get_autocommit():
  274. self.commit()
  275. @async_unsafe
  276. def create_cursor(self, name=None):
  277. return FormatStylePlaceholderCursor(self.connection, self)
  278. def _commit(self):
  279. if self.connection is not None:
  280. with debug_transaction(self, "COMMIT"), wrap_oracle_errors():
  281. return self.connection.commit()
  282. # Oracle doesn't support releasing savepoints. But we fake them when query
  283. # logging is enabled to keep query counts consistent with other backends.
  284. def _savepoint_commit(self, sid):
  285. if self.queries_logged:
  286. self.queries_log.append(
  287. {
  288. "sql": "-- RELEASE SAVEPOINT %s (faked)" % self.ops.quote_name(sid),
  289. "time": "0.000",
  290. }
  291. )
  292. def _set_autocommit(self, autocommit):
  293. with self.wrap_database_errors:
  294. self.connection.autocommit = autocommit
  295. def check_constraints(self, table_names=None):
  296. """
  297. Check constraints by setting them to immediate. Return them to deferred
  298. afterward.
  299. """
  300. with self.cursor() as cursor:
  301. cursor.execute("SET CONSTRAINTS ALL IMMEDIATE")
  302. cursor.execute("SET CONSTRAINTS ALL DEFERRED")
  303. def is_usable(self):
  304. try:
  305. self.connection.ping()
  306. except Database.Error:
  307. return False
  308. else:
  309. return True
  310. @cached_property
  311. def oracle_version(self):
  312. with self.temporary_connection():
  313. return tuple(int(x) for x in self.connection.version.split("."))
  314. @cached_property
  315. def oracledb_version(self):
  316. return get_version_tuple(Database.__version__)
  317. class OracleParam:
  318. """
  319. Wrapper object for formatting parameters for Oracle. If the string
  320. representation of the value is large enough (greater than 4000 characters)
  321. the input size needs to be set as CLOB. Alternatively, if the parameter
  322. has an `input_size` attribute, then the value of the `input_size` attribute
  323. will be used instead. Otherwise, no input size will be set for the
  324. parameter when executing the query.
  325. """
  326. def __init__(self, param, cursor, strings_only=False):
  327. # With raw SQL queries, datetimes can reach this function
  328. # without being converted by DateTimeField.get_db_prep_value.
  329. if settings.USE_TZ and (
  330. isinstance(param, datetime.datetime)
  331. and not isinstance(param, Oracle_datetime)
  332. ):
  333. param = Oracle_datetime.from_datetime(param)
  334. string_size = 0
  335. has_boolean_data_type = (
  336. cursor.database.features.supports_boolean_expr_in_select_clause
  337. )
  338. if not has_boolean_data_type:
  339. # Oracle < 23c doesn't recognize True and False correctly.
  340. if param is True:
  341. param = 1
  342. elif param is False:
  343. param = 0
  344. if hasattr(param, "bind_parameter"):
  345. self.force_bytes = param.bind_parameter(cursor)
  346. elif isinstance(param, (Database.Binary, datetime.timedelta)):
  347. self.force_bytes = param
  348. else:
  349. # To transmit to the database, we need Unicode if supported
  350. # To get size right, we must consider bytes.
  351. self.force_bytes = force_str(param, cursor.charset, strings_only)
  352. if isinstance(self.force_bytes, str):
  353. # We could optimize by only converting up to 4000 bytes here
  354. string_size = len(force_bytes(param, cursor.charset, strings_only))
  355. if hasattr(param, "input_size"):
  356. # If parameter has `input_size` attribute, use that.
  357. self.input_size = param.input_size
  358. elif string_size > 4000:
  359. # Mark any string param greater than 4000 characters as a CLOB.
  360. self.input_size = Database.DB_TYPE_CLOB
  361. elif isinstance(param, datetime.datetime):
  362. self.input_size = Database.DB_TYPE_TIMESTAMP
  363. elif has_boolean_data_type and isinstance(param, bool):
  364. self.input_size = Database.DB_TYPE_BOOLEAN
  365. else:
  366. self.input_size = None
  367. class VariableWrapper:
  368. """
  369. An adapter class for cursor variables that prevents the wrapped object
  370. from being converted into a string when used to instantiate an OracleParam.
  371. This can be used generally for any other object that should be passed into
  372. Cursor.execute as-is.
  373. """
  374. def __init__(self, var):
  375. self.var = var
  376. def bind_parameter(self, cursor):
  377. return self.var
  378. def __getattr__(self, key):
  379. return getattr(self.var, key)
  380. def __setattr__(self, key, value):
  381. if key == "var":
  382. self.__dict__[key] = value
  383. else:
  384. setattr(self.var, key, value)
  385. class FormatStylePlaceholderCursor:
  386. """
  387. Django uses "format" (e.g. '%s') style placeholders, but Oracle uses ":var"
  388. style. This fixes it -- but note that if you want to use a literal "%s" in
  389. a query, you'll need to use "%%s".
  390. """
  391. charset = "utf-8"
  392. def __init__(self, connection, database):
  393. self.cursor = connection.cursor()
  394. self.cursor.outputtypehandler = self._output_type_handler
  395. self.database = database
  396. @staticmethod
  397. def _output_number_converter(value):
  398. return decimal.Decimal(value) if "." in value else int(value)
  399. @staticmethod
  400. def _get_decimal_converter(precision, scale):
  401. if scale == 0:
  402. return int
  403. context = decimal.Context(prec=precision)
  404. quantize_value = decimal.Decimal(1).scaleb(-scale)
  405. return lambda v: decimal.Decimal(v).quantize(quantize_value, context=context)
  406. @staticmethod
  407. def _output_type_handler(cursor, name, defaultType, length, precision, scale):
  408. """
  409. Called for each db column fetched from cursors. Return numbers as the
  410. appropriate Python type, and NCLOB with JSON as strings.
  411. """
  412. if defaultType == Database.NUMBER:
  413. if scale == -127:
  414. if precision == 0:
  415. # NUMBER column: decimal-precision floating point.
  416. # This will normally be an integer from a sequence,
  417. # but it could be a decimal value.
  418. outconverter = FormatStylePlaceholderCursor._output_number_converter
  419. else:
  420. # FLOAT column: binary-precision floating point.
  421. # This comes from FloatField columns.
  422. outconverter = float
  423. elif precision > 0:
  424. # NUMBER(p,s) column: decimal-precision fixed point.
  425. # This comes from IntegerField and DecimalField columns.
  426. outconverter = FormatStylePlaceholderCursor._get_decimal_converter(
  427. precision, scale
  428. )
  429. else:
  430. # No type information. This normally comes from a
  431. # mathematical expression in the SELECT list. Guess int
  432. # or Decimal based on whether it has a decimal point.
  433. outconverter = FormatStylePlaceholderCursor._output_number_converter
  434. return cursor.var(
  435. Database.STRING,
  436. size=255,
  437. arraysize=cursor.arraysize,
  438. outconverter=outconverter,
  439. )
  440. # oracledb 2.0.0+ returns NLOB columns with IS JSON constraints as
  441. # dicts. Use a no-op converter to avoid this.
  442. elif defaultType == Database.DB_TYPE_NCLOB:
  443. return cursor.var(Database.DB_TYPE_NCLOB, arraysize=cursor.arraysize)
  444. def _format_params(self, params):
  445. try:
  446. return {k: OracleParam(v, self, True) for k, v in params.items()}
  447. except AttributeError:
  448. return tuple(OracleParam(p, self, True) for p in params)
  449. def _guess_input_sizes(self, params_list):
  450. # Try dict handling; if that fails, treat as sequence
  451. if hasattr(params_list[0], "keys"):
  452. sizes = {}
  453. for params in params_list:
  454. for k, value in params.items():
  455. if value.input_size:
  456. sizes[k] = value.input_size
  457. if sizes:
  458. self.setinputsizes(**sizes)
  459. else:
  460. # It's not a list of dicts; it's a list of sequences
  461. sizes = [None] * len(params_list[0])
  462. for params in params_list:
  463. for i, value in enumerate(params):
  464. if value.input_size:
  465. sizes[i] = value.input_size
  466. if sizes:
  467. self.setinputsizes(*sizes)
  468. def _param_generator(self, params):
  469. # Try dict handling; if that fails, treat as sequence
  470. if hasattr(params, "items"):
  471. return {k: v.force_bytes for k, v in params.items()}
  472. else:
  473. return [p.force_bytes for p in params]
  474. def _fix_for_params(self, query, params, unify_by_values=False):
  475. # oracledb wants no trailing ';' for SQL statements. For PL/SQL, it
  476. # it does want a trailing ';' but not a trailing '/'. However, these
  477. # characters must be included in the original query in case the query
  478. # is being passed to SQL*Plus.
  479. if query.endswith(";") or query.endswith("/"):
  480. query = query[:-1]
  481. if params is None:
  482. params = []
  483. elif hasattr(params, "keys"):
  484. # Handle params as dict
  485. args = {k: ":%s" % k for k in params}
  486. query %= args
  487. elif unify_by_values and params:
  488. # Handle params as a dict with unified query parameters by their
  489. # values. It can be used only in single query execute() because
  490. # executemany() shares the formatted query with each of the params
  491. # list. e.g. for input params = [0.75, 2, 0.75, 'sth', 0.75]
  492. # params_dict = {
  493. # (float, 0.75): ':arg0',
  494. # (int, 2): ':arg1',
  495. # (str, 'sth'): ':arg2',
  496. # }
  497. # args = [':arg0', ':arg1', ':arg0', ':arg2', ':arg0']
  498. # params = {':arg0': 0.75, ':arg1': 2, ':arg2': 'sth'}
  499. # The type of parameters in param_types keys is necessary to avoid
  500. # unifying 0/1 with False/True.
  501. param_types = [(type(param), param) for param in params]
  502. params_dict = {
  503. param_type: ":arg%d" % i
  504. for i, param_type in enumerate(dict.fromkeys(param_types))
  505. }
  506. args = [params_dict[param_type] for param_type in param_types]
  507. params = {
  508. placeholder: param for (_, param), placeholder in params_dict.items()
  509. }
  510. query %= tuple(args)
  511. else:
  512. # Handle params as sequence
  513. args = [(":arg%d" % i) for i in range(len(params))]
  514. query %= tuple(args)
  515. return query, self._format_params(params)
  516. def execute(self, query, params=None):
  517. query, params = self._fix_for_params(query, params, unify_by_values=True)
  518. self._guess_input_sizes([params])
  519. with wrap_oracle_errors():
  520. return self.cursor.execute(query, self._param_generator(params))
  521. def executemany(self, query, params=None):
  522. if not params:
  523. # No params given, nothing to do
  524. return None
  525. # uniform treatment for sequences and iterables
  526. params_iter = iter(params)
  527. query, firstparams = self._fix_for_params(query, next(params_iter))
  528. # we build a list of formatted params; as we're going to traverse it
  529. # more than once, we can't make it lazy by using a generator
  530. formatted = [firstparams] + [self._format_params(p) for p in params_iter]
  531. self._guess_input_sizes(formatted)
  532. with wrap_oracle_errors():
  533. return self.cursor.executemany(
  534. query, [self._param_generator(p) for p in formatted]
  535. )
  536. def close(self):
  537. try:
  538. self.cursor.close()
  539. except Database.InterfaceError:
  540. # already closed
  541. pass
  542. def var(self, *args):
  543. return VariableWrapper(self.cursor.var(*args))
  544. def arrayvar(self, *args):
  545. return VariableWrapper(self.cursor.arrayvar(*args))
  546. def __getattr__(self, attr):
  547. return getattr(self.cursor, attr)
  548. def __iter__(self):
  549. return iter(self.cursor)