You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2505 lines
84KB

  1. # oracle/base.py
  2. # Copyright (C) 2005-2021 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. r"""
  8. .. dialect:: oracle
  9. :name: Oracle
  10. :full_support: 11.2, 18c
  11. :normal_support: 11+
  12. :best_effort: 8+
  13. Auto Increment Behavior
  14. -----------------------
  15. SQLAlchemy Table objects which include integer primary keys are usually
  16. assumed to have "autoincrementing" behavior, meaning they can generate their
  17. own primary key values upon INSERT. For use within Oracle, two options are
  18. available, which are the use of IDENTITY columns (Oracle 12 and above only)
  19. or the association of a SEQUENCE with the column.
  20. Specifying GENERATED AS IDENTITY (Oracle 12 and above)
  21. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  22. Starting from version 12 Oracle can make use of identity columns using
  23. the :class:`_sql.Identity` to specify the autoincrementing behavior::
  24. t = Table('mytable', metadata,
  25. Column('id', Integer, Identity(start=3), primary_key=True),
  26. Column(...), ...
  27. )
  28. The CREATE TABLE for the above :class:`_schema.Table` object would be:
  29. .. sourcecode:: sql
  30. CREATE TABLE mytable (
  31. id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 3),
  32. ...,
  33. PRIMARY KEY (id)
  34. )
  35. The :class:`_schema.Identity` object support many options to control the
  36. "autoincrementing" behavior of the column, like the starting value, the
  37. incrementing value, etc.
  38. In addition to the standard options, Oracle supports setting
  39. :paramref:`_schema.Identity.always` to ``None`` to use the default
  40. generated mode, rendering GENERATED AS IDENTITY in the DDL. It also supports
  41. setting :paramref:`_schema.Identity.on_null` to ``True`` to specify ON NULL
  42. in conjunction with a 'BY DEFAULT' identity column.
  43. Using a SEQUENCE (all Oracle versions)
  44. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  45. Older version of Oracle had no "autoincrement"
  46. feature, SQLAlchemy relies upon sequences to produce these values. With the
  47. older Oracle versions, *a sequence must always be explicitly specified to
  48. enable autoincrement*. This is divergent with the majority of documentation
  49. examples which assume the usage of an autoincrement-capable database. To
  50. specify sequences, use the sqlalchemy.schema.Sequence object which is passed
  51. to a Column construct::
  52. t = Table('mytable', metadata,
  53. Column('id', Integer, Sequence('id_seq'), primary_key=True),
  54. Column(...), ...
  55. )
  56. This step is also required when using table reflection, i.e. autoload_with=engine::
  57. t = Table('mytable', metadata,
  58. Column('id', Integer, Sequence('id_seq'), primary_key=True),
  59. autoload_with=engine
  60. )
  61. .. versionchanged:: 1.4 Added :class:`_schema.Identity` construct
  62. in a :class:`_schema.Column` to specify the option of an autoincrementing
  63. column.
  64. .. _oracle_isolation_level:
  65. Transaction Isolation Level / Autocommit
  66. ----------------------------------------
  67. The Oracle database supports "READ COMMITTED" and "SERIALIZABLE" modes of
  68. isolation. The AUTOCOMMIT isolation level is also supported by the cx_Oracle
  69. dialect.
  70. To set using per-connection execution options::
  71. connection = engine.connect()
  72. connection = connection.execution_options(
  73. isolation_level="AUTOCOMMIT"
  74. )
  75. For ``READ COMMITTED`` and ``SERIALIZABLE``, the Oracle dialect sets the
  76. level at the session level using ``ALTER SESSION``, which is reverted back
  77. to its default setting when the connection is returned to the connection
  78. pool.
  79. Valid values for ``isolation_level`` include:
  80. * ``READ COMMITTED``
  81. * ``AUTOCOMMIT``
  82. * ``SERIALIZABLE``
  83. .. note:: The implementation for the
  84. :meth:`_engine.Connection.get_isolation_level` method as implemented by the
  85. Oracle dialect necessarily forces the start of a transaction using the
  86. Oracle LOCAL_TRANSACTION_ID function; otherwise no level is normally
  87. readable.
  88. Additionally, the :meth:`_engine.Connection.get_isolation_level` method will
  89. raise an exception if the ``v$transaction`` view is not available due to
  90. permissions or other reasons, which is a common occurrence in Oracle
  91. installations.
  92. The cx_Oracle dialect attempts to call the
  93. :meth:`_engine.Connection.get_isolation_level` method when the dialect makes
  94. its first connection to the database in order to acquire the
  95. "default"isolation level. This default level is necessary so that the level
  96. can be reset on a connection after it has been temporarily modified using
  97. :meth:`_engine.Connection.execution_options` method. In the common event
  98. that the :meth:`_engine.Connection.get_isolation_level` method raises an
  99. exception due to ``v$transaction`` not being readable as well as any other
  100. database-related failure, the level is assumed to be "READ COMMITTED". No
  101. warning is emitted for this initial first-connect condition as it is
  102. expected to be a common restriction on Oracle databases.
  103. .. versionadded:: 1.3.16 added support for AUTOCOMMIT to the cx_oracle dialect
  104. as well as the notion of a default isolation level
  105. .. versionadded:: 1.3.21 Added support for SERIALIZABLE as well as live
  106. reading of the isolation level.
  107. .. versionchanged:: 1.3.22 In the event that the default isolation
  108. level cannot be read due to permissions on the v$transaction view as
  109. is common in Oracle installations, the default isolation level is hardcoded
  110. to "READ COMMITTED" which was the behavior prior to 1.3.21.
  111. .. seealso::
  112. :ref:`dbapi_autocommit`
  113. Identifier Casing
  114. -----------------
  115. In Oracle, the data dictionary represents all case insensitive identifier
  116. names using UPPERCASE text. SQLAlchemy on the other hand considers an
  117. all-lower case identifier name to be case insensitive. The Oracle dialect
  118. converts all case insensitive identifiers to and from those two formats during
  119. schema level communication, such as reflection of tables and indexes. Using
  120. an UPPERCASE name on the SQLAlchemy side indicates a case sensitive
  121. identifier, and SQLAlchemy will quote the name - this will cause mismatches
  122. against data dictionary data received from Oracle, so unless identifier names
  123. have been truly created as case sensitive (i.e. using quoted names), all
  124. lowercase names should be used on the SQLAlchemy side.
  125. .. _oracle_max_identifier_lengths:
  126. Max Identifier Lengths
  127. ----------------------
  128. Oracle has changed the default max identifier length as of Oracle Server
  129. version 12.2. Prior to this version, the length was 30, and for 12.2 and
  130. greater it is now 128. This change impacts SQLAlchemy in the area of
  131. generated SQL label names as well as the generation of constraint names,
  132. particularly in the case where the constraint naming convention feature
  133. described at :ref:`constraint_naming_conventions` is being used.
  134. To assist with this change and others, Oracle includes the concept of a
  135. "compatibility" version, which is a version number that is independent of the
  136. actual server version in order to assist with migration of Oracle databases,
  137. and may be configured within the Oracle server itself. This compatibility
  138. version is retrieved using the query ``SELECT value FROM v$parameter WHERE
  139. name = 'compatible';``. The SQLAlchemy Oracle dialect, when tasked with
  140. determining the default max identifier length, will attempt to use this query
  141. upon first connect in order to determine the effective compatibility version of
  142. the server, which determines what the maximum allowed identifier length is for
  143. the server. If the table is not available, the server version information is
  144. used instead.
  145. As of SQLAlchemy 1.4, the default max identifier length for the Oracle dialect
  146. is 128 characters. Upon first connect, the compatibility version is detected
  147. and if it is less than Oracle version 12.2, the max identifier length is
  148. changed to be 30 characters. In all cases, setting the
  149. :paramref:`_sa.create_engine.max_identifier_length` parameter will bypass this
  150. change and the value given will be used as is::
  151. engine = create_engine(
  152. "oracle+cx_oracle://scott:tiger@oracle122",
  153. max_identifier_length=30)
  154. The maximum identifier length comes into play both when generating anonymized
  155. SQL labels in SELECT statements, but more crucially when generating constraint
  156. names from a naming convention. It is this area that has created the need for
  157. SQLAlchemy to change this default conservatively. For example, the following
  158. naming convention produces two very different constraint names based on the
  159. identifier length::
  160. from sqlalchemy import Column
  161. from sqlalchemy import Index
  162. from sqlalchemy import Integer
  163. from sqlalchemy import MetaData
  164. from sqlalchemy import Table
  165. from sqlalchemy.dialects import oracle
  166. from sqlalchemy.schema import CreateIndex
  167. m = MetaData(naming_convention={"ix": "ix_%(column_0N_name)s"})
  168. t = Table(
  169. "t",
  170. m,
  171. Column("some_column_name_1", Integer),
  172. Column("some_column_name_2", Integer),
  173. Column("some_column_name_3", Integer),
  174. )
  175. ix = Index(
  176. None,
  177. t.c.some_column_name_1,
  178. t.c.some_column_name_2,
  179. t.c.some_column_name_3,
  180. )
  181. oracle_dialect = oracle.dialect(max_identifier_length=30)
  182. print(CreateIndex(ix).compile(dialect=oracle_dialect))
  183. With an identifier length of 30, the above CREATE INDEX looks like::
  184. CREATE INDEX ix_some_column_name_1s_70cd ON t
  185. (some_column_name_1, some_column_name_2, some_column_name_3)
  186. However with length=128, it becomes::
  187. CREATE INDEX ix_some_column_name_1some_column_name_2some_column_name_3 ON t
  188. (some_column_name_1, some_column_name_2, some_column_name_3)
  189. Applications which have run versions of SQLAlchemy prior to 1.4 on an Oracle
  190. server version 12.2 or greater are therefore subject to the scenario of a
  191. database migration that wishes to "DROP CONSTRAINT" on a name that was
  192. previously generated with the shorter length. This migration will fail when
  193. the identifier length is changed without the name of the index or constraint
  194. first being adjusted. Such applications are strongly advised to make use of
  195. :paramref:`_sa.create_engine.max_identifier_length`
  196. in order to maintain control
  197. of the generation of truncated names, and to fully review and test all database
  198. migrations in a staging environment when changing this value to ensure that the
  199. impact of this change has been mitigated.
  200. .. versionchanged:: 1.4 the default max_identifier_length for Oracle is 128
  201. characters, which is adjusted down to 30 upon first connect if an older
  202. version of Oracle server (compatibility version < 12.2) is detected.
  203. LIMIT/OFFSET Support
  204. --------------------
  205. Oracle has no direct support for LIMIT and OFFSET until version 12c.
  206. To achieve this behavior across all widely used versions of Oracle starting
  207. with the 8 series, SQLAlchemy currently makes use of ROWNUM to achieve
  208. LIMIT/OFFSET; the exact methodology is taken from
  209. https://blogs.oracle.com/oraclemagazine/on-rownum-and-limiting-results .
  210. There is currently a single option to affect its behavior:
  211. * the "FIRST_ROWS()" optimization keyword is not used by default. To enable
  212. the usage of this optimization directive, specify ``optimize_limits=True``
  213. to :func:`_sa.create_engine`.
  214. .. versionchanged:: 1.4
  215. The Oracle dialect renders limit/offset integer values using a "post
  216. compile" scheme which renders the integer directly before passing the
  217. statement to the cursor for execution. The ``use_binds_for_limits`` flag
  218. no longer has an effect.
  219. .. seealso::
  220. :ref:`change_4808`.
  221. Support for changing the row number strategy, which would include one that
  222. makes use of the ``row_number()`` window function as well as one that makes
  223. use of the Oracle 12c "FETCH FIRST N ROW / OFFSET N ROWS" keywords may be
  224. added in a future release.
  225. .. _oracle_returning:
  226. RETURNING Support
  227. -----------------
  228. The Oracle database supports a limited form of RETURNING, in order to retrieve
  229. result sets of matched rows from INSERT, UPDATE and DELETE statements.
  230. Oracle's RETURNING..INTO syntax only supports one row being returned, as it
  231. relies upon OUT parameters in order to function. In addition, supported
  232. DBAPIs have further limitations (see :ref:`cx_oracle_returning`).
  233. SQLAlchemy's "implicit returning" feature, which employs RETURNING within an
  234. INSERT and sometimes an UPDATE statement in order to fetch newly generated
  235. primary key values and other SQL defaults and expressions, is normally enabled
  236. on the Oracle backend. By default, "implicit returning" typically only
  237. fetches the value of a single ``nextval(some_seq)`` expression embedded into
  238. an INSERT in order to increment a sequence within an INSERT statement and get
  239. the value back at the same time. To disable this feature across the board,
  240. specify ``implicit_returning=False`` to :func:`_sa.create_engine`::
  241. engine = create_engine("oracle://scott:tiger@dsn",
  242. implicit_returning=False)
  243. Implicit returning can also be disabled on a table-by-table basis as a table
  244. option::
  245. # Core Table
  246. my_table = Table("my_table", metadata, ..., implicit_returning=False)
  247. # declarative
  248. class MyClass(Base):
  249. __tablename__ = 'my_table'
  250. __table_args__ = {"implicit_returning": False}
  251. .. seealso::
  252. :ref:`cx_oracle_returning` - additional cx_oracle-specific restrictions on
  253. implicit returning.
  254. ON UPDATE CASCADE
  255. -----------------
  256. Oracle doesn't have native ON UPDATE CASCADE functionality. A trigger based
  257. solution is available at
  258. http://asktom.oracle.com/tkyte/update_cascade/index.html .
  259. When using the SQLAlchemy ORM, the ORM has limited ability to manually issue
  260. cascading updates - specify ForeignKey objects using the
  261. "deferrable=True, initially='deferred'" keyword arguments,
  262. and specify "passive_updates=False" on each relationship().
  263. Oracle 8 Compatibility
  264. ----------------------
  265. When Oracle 8 is detected, the dialect internally configures itself to the
  266. following behaviors:
  267. * the use_ansi flag is set to False. This has the effect of converting all
  268. JOIN phrases into the WHERE clause, and in the case of LEFT OUTER JOIN
  269. makes use of Oracle's (+) operator.
  270. * the NVARCHAR2 and NCLOB datatypes are no longer generated as DDL when
  271. the :class:`~sqlalchemy.types.Unicode` is used - VARCHAR2 and CLOB are
  272. issued instead. This because these types don't seem to work correctly on
  273. Oracle 8 even though they are available. The
  274. :class:`~sqlalchemy.types.NVARCHAR` and
  275. :class:`~sqlalchemy.dialects.oracle.NCLOB` types will always generate
  276. NVARCHAR2 and NCLOB.
  277. * the "native unicode" mode is disabled when using cx_oracle, i.e. SQLAlchemy
  278. encodes all Python unicode objects to "string" before passing in as bind
  279. parameters.
  280. Synonym/DBLINK Reflection
  281. -------------------------
  282. When using reflection with Table objects, the dialect can optionally search
  283. for tables indicated by synonyms, either in local or remote schemas or
  284. accessed over DBLINK, by passing the flag ``oracle_resolve_synonyms=True`` as
  285. a keyword argument to the :class:`_schema.Table` construct::
  286. some_table = Table('some_table', autoload_with=some_engine,
  287. oracle_resolve_synonyms=True)
  288. When this flag is set, the given name (such as ``some_table`` above) will
  289. be searched not just in the ``ALL_TABLES`` view, but also within the
  290. ``ALL_SYNONYMS`` view to see if this name is actually a synonym to another
  291. name. If the synonym is located and refers to a DBLINK, the oracle dialect
  292. knows how to locate the table's information using DBLINK syntax(e.g.
  293. ``@dblink``).
  294. ``oracle_resolve_synonyms`` is accepted wherever reflection arguments are
  295. accepted, including methods such as :meth:`_schema.MetaData.reflect` and
  296. :meth:`_reflection.Inspector.get_columns`.
  297. If synonyms are not in use, this flag should be left disabled.
  298. .. _oracle_constraint_reflection:
  299. Constraint Reflection
  300. ---------------------
  301. The Oracle dialect can return information about foreign key, unique, and
  302. CHECK constraints, as well as indexes on tables.
  303. Raw information regarding these constraints can be acquired using
  304. :meth:`_reflection.Inspector.get_foreign_keys`,
  305. :meth:`_reflection.Inspector.get_unique_constraints`,
  306. :meth:`_reflection.Inspector.get_check_constraints`, and
  307. :meth:`_reflection.Inspector.get_indexes`.
  308. .. versionchanged:: 1.2 The Oracle dialect can now reflect UNIQUE and
  309. CHECK constraints.
  310. When using reflection at the :class:`_schema.Table` level, the
  311. :class:`_schema.Table`
  312. will also include these constraints.
  313. Note the following caveats:
  314. * When using the :meth:`_reflection.Inspector.get_check_constraints` method,
  315. Oracle
  316. builds a special "IS NOT NULL" constraint for columns that specify
  317. "NOT NULL". This constraint is **not** returned by default; to include
  318. the "IS NOT NULL" constraints, pass the flag ``include_all=True``::
  319. from sqlalchemy import create_engine, inspect
  320. engine = create_engine("oracle+cx_oracle://s:t@dsn")
  321. inspector = inspect(engine)
  322. all_check_constraints = inspector.get_check_constraints(
  323. "some_table", include_all=True)
  324. * in most cases, when reflecting a :class:`_schema.Table`,
  325. a UNIQUE constraint will
  326. **not** be available as a :class:`.UniqueConstraint` object, as Oracle
  327. mirrors unique constraints with a UNIQUE index in most cases (the exception
  328. seems to be when two or more unique constraints represent the same columns);
  329. the :class:`_schema.Table` will instead represent these using
  330. :class:`.Index`
  331. with the ``unique=True`` flag set.
  332. * Oracle creates an implicit index for the primary key of a table; this index
  333. is **excluded** from all index results.
  334. * the list of columns reflected for an index will not include column names
  335. that start with SYS_NC.
  336. Table names with SYSTEM/SYSAUX tablespaces
  337. -------------------------------------------
  338. The :meth:`_reflection.Inspector.get_table_names` and
  339. :meth:`_reflection.Inspector.get_temp_table_names`
  340. methods each return a list of table names for the current engine. These methods
  341. are also part of the reflection which occurs within an operation such as
  342. :meth:`_schema.MetaData.reflect`. By default,
  343. these operations exclude the ``SYSTEM``
  344. and ``SYSAUX`` tablespaces from the operation. In order to change this, the
  345. default list of tablespaces excluded can be changed at the engine level using
  346. the ``exclude_tablespaces`` parameter::
  347. # exclude SYSAUX and SOME_TABLESPACE, but not SYSTEM
  348. e = create_engine(
  349. "oracle://scott:tiger@xe",
  350. exclude_tablespaces=["SYSAUX", "SOME_TABLESPACE"])
  351. .. versionadded:: 1.1
  352. DateTime Compatibility
  353. ----------------------
  354. Oracle has no datatype known as ``DATETIME``, it instead has only ``DATE``,
  355. which can actually store a date and time value. For this reason, the Oracle
  356. dialect provides a type :class:`_oracle.DATE` which is a subclass of
  357. :class:`.DateTime`. This type has no special behavior, and is only
  358. present as a "marker" for this type; additionally, when a database column
  359. is reflected and the type is reported as ``DATE``, the time-supporting
  360. :class:`_oracle.DATE` type is used.
  361. .. versionchanged:: 0.9.4 Added :class:`_oracle.DATE` to subclass
  362. :class:`.DateTime`. This is a change as previous versions
  363. would reflect a ``DATE`` column as :class:`_types.DATE`, which subclasses
  364. :class:`.Date`. The only significance here is for schemes that are
  365. examining the type of column for use in special Python translations or
  366. for migrating schemas to other database backends.
  367. .. _oracle_table_options:
  368. Oracle Table Options
  369. -------------------------
  370. The CREATE TABLE phrase supports the following options with Oracle
  371. in conjunction with the :class:`_schema.Table` construct:
  372. * ``ON COMMIT``::
  373. Table(
  374. "some_table", metadata, ...,
  375. prefixes=['GLOBAL TEMPORARY'], oracle_on_commit='PRESERVE ROWS')
  376. .. versionadded:: 1.0.0
  377. * ``COMPRESS``::
  378. Table('mytable', metadata, Column('data', String(32)),
  379. oracle_compress=True)
  380. Table('mytable', metadata, Column('data', String(32)),
  381. oracle_compress=6)
  382. The ``oracle_compress`` parameter accepts either an integer compression
  383. level, or ``True`` to use the default compression level.
  384. .. versionadded:: 1.0.0
  385. .. _oracle_index_options:
  386. Oracle Specific Index Options
  387. -----------------------------
  388. Bitmap Indexes
  389. ~~~~~~~~~~~~~~
  390. You can specify the ``oracle_bitmap`` parameter to create a bitmap index
  391. instead of a B-tree index::
  392. Index('my_index', my_table.c.data, oracle_bitmap=True)
  393. Bitmap indexes cannot be unique and cannot be compressed. SQLAlchemy will not
  394. check for such limitations, only the database will.
  395. .. versionadded:: 1.0.0
  396. Index compression
  397. ~~~~~~~~~~~~~~~~~
  398. Oracle has a more efficient storage mode for indexes containing lots of
  399. repeated values. Use the ``oracle_compress`` parameter to turn on key
  400. compression::
  401. Index('my_index', my_table.c.data, oracle_compress=True)
  402. Index('my_index', my_table.c.data1, my_table.c.data2, unique=True,
  403. oracle_compress=1)
  404. The ``oracle_compress`` parameter accepts either an integer specifying the
  405. number of prefix columns to compress, or ``True`` to use the default (all
  406. columns for non-unique indexes, all but the last column for unique indexes).
  407. .. versionadded:: 1.0.0
  408. """ # noqa
  409. from itertools import groupby
  410. import re
  411. from ... import Computed
  412. from ... import exc
  413. from ... import schema as sa_schema
  414. from ... import sql
  415. from ... import util
  416. from ...engine import default
  417. from ...engine import reflection
  418. from ...sql import compiler
  419. from ...sql import expression
  420. from ...sql import sqltypes
  421. from ...sql import util as sql_util
  422. from ...sql import visitors
  423. from ...types import BLOB
  424. from ...types import CHAR
  425. from ...types import CLOB
  426. from ...types import FLOAT
  427. from ...types import INTEGER
  428. from ...types import NCHAR
  429. from ...types import NVARCHAR
  430. from ...types import TIMESTAMP
  431. from ...types import VARCHAR
  432. from ...util import compat
  433. RESERVED_WORDS = set(
  434. "SHARE RAW DROP BETWEEN FROM DESC OPTION PRIOR LONG THEN "
  435. "DEFAULT ALTER IS INTO MINUS INTEGER NUMBER GRANT IDENTIFIED "
  436. "ALL TO ORDER ON FLOAT DATE HAVING CLUSTER NOWAIT RESOURCE "
  437. "ANY TABLE INDEX FOR UPDATE WHERE CHECK SMALLINT WITH DELETE "
  438. "BY ASC REVOKE LIKE SIZE RENAME NOCOMPRESS NULL GROUP VALUES "
  439. "AS IN VIEW EXCLUSIVE COMPRESS SYNONYM SELECT INSERT EXISTS "
  440. "NOT TRIGGER ELSE CREATE INTERSECT PCTFREE DISTINCT USER "
  441. "CONNECT SET MODE OF UNIQUE VARCHAR2 VARCHAR LOCK OR CHAR "
  442. "DECIMAL UNION PUBLIC AND START UID COMMENT CURRENT LEVEL".split()
  443. )
  444. NO_ARG_FNS = set(
  445. "UID CURRENT_DATE SYSDATE USER " "CURRENT_TIME CURRENT_TIMESTAMP".split()
  446. )
  447. class RAW(sqltypes._Binary):
  448. __visit_name__ = "RAW"
  449. OracleRaw = RAW
  450. class NCLOB(sqltypes.Text):
  451. __visit_name__ = "NCLOB"
  452. class VARCHAR2(VARCHAR):
  453. __visit_name__ = "VARCHAR2"
  454. NVARCHAR2 = NVARCHAR
  455. class NUMBER(sqltypes.Numeric, sqltypes.Integer):
  456. __visit_name__ = "NUMBER"
  457. def __init__(self, precision=None, scale=None, asdecimal=None):
  458. if asdecimal is None:
  459. asdecimal = bool(scale and scale > 0)
  460. super(NUMBER, self).__init__(
  461. precision=precision, scale=scale, asdecimal=asdecimal
  462. )
  463. def adapt(self, impltype):
  464. ret = super(NUMBER, self).adapt(impltype)
  465. # leave a hint for the DBAPI handler
  466. ret._is_oracle_number = True
  467. return ret
  468. @property
  469. def _type_affinity(self):
  470. if bool(self.scale and self.scale > 0):
  471. return sqltypes.Numeric
  472. else:
  473. return sqltypes.Integer
  474. class DOUBLE_PRECISION(sqltypes.Float):
  475. __visit_name__ = "DOUBLE_PRECISION"
  476. class BINARY_DOUBLE(sqltypes.Float):
  477. __visit_name__ = "BINARY_DOUBLE"
  478. class BINARY_FLOAT(sqltypes.Float):
  479. __visit_name__ = "BINARY_FLOAT"
  480. class BFILE(sqltypes.LargeBinary):
  481. __visit_name__ = "BFILE"
  482. class LONG(sqltypes.Text):
  483. __visit_name__ = "LONG"
  484. class DATE(sqltypes.DateTime):
  485. """Provide the oracle DATE type.
  486. This type has no special Python behavior, except that it subclasses
  487. :class:`_types.DateTime`; this is to suit the fact that the Oracle
  488. ``DATE`` type supports a time value.
  489. .. versionadded:: 0.9.4
  490. """
  491. __visit_name__ = "DATE"
  492. def _compare_type_affinity(self, other):
  493. return other._type_affinity in (sqltypes.DateTime, sqltypes.Date)
  494. class INTERVAL(sqltypes.NativeForEmulated, sqltypes._AbstractInterval):
  495. __visit_name__ = "INTERVAL"
  496. def __init__(self, day_precision=None, second_precision=None):
  497. """Construct an INTERVAL.
  498. Note that only DAY TO SECOND intervals are currently supported.
  499. This is due to a lack of support for YEAR TO MONTH intervals
  500. within available DBAPIs.
  501. :param day_precision: the day precision value. this is the number of
  502. digits to store for the day field. Defaults to "2"
  503. :param second_precision: the second precision value. this is the
  504. number of digits to store for the fractional seconds field.
  505. Defaults to "6".
  506. """
  507. self.day_precision = day_precision
  508. self.second_precision = second_precision
  509. @classmethod
  510. def _adapt_from_generic_interval(cls, interval):
  511. return INTERVAL(
  512. day_precision=interval.day_precision,
  513. second_precision=interval.second_precision,
  514. )
  515. @property
  516. def _type_affinity(self):
  517. return sqltypes.Interval
  518. def as_generic(self, allow_nulltype=False):
  519. return sqltypes.Interval(
  520. native=True,
  521. second_precision=self.second_precision,
  522. day_precision=self.day_precision,
  523. )
  524. def coerce_compared_value(self, op, value):
  525. return self
  526. class ROWID(sqltypes.TypeEngine):
  527. """Oracle ROWID type.
  528. When used in a cast() or similar, generates ROWID.
  529. """
  530. __visit_name__ = "ROWID"
  531. class _OracleBoolean(sqltypes.Boolean):
  532. def get_dbapi_type(self, dbapi):
  533. return dbapi.NUMBER
  534. colspecs = {
  535. sqltypes.Boolean: _OracleBoolean,
  536. sqltypes.Interval: INTERVAL,
  537. sqltypes.DateTime: DATE,
  538. }
  539. ischema_names = {
  540. "VARCHAR2": VARCHAR,
  541. "NVARCHAR2": NVARCHAR,
  542. "CHAR": CHAR,
  543. "NCHAR": NCHAR,
  544. "DATE": DATE,
  545. "NUMBER": NUMBER,
  546. "BLOB": BLOB,
  547. "BFILE": BFILE,
  548. "CLOB": CLOB,
  549. "NCLOB": NCLOB,
  550. "TIMESTAMP": TIMESTAMP,
  551. "TIMESTAMP WITH TIME ZONE": TIMESTAMP,
  552. "INTERVAL DAY TO SECOND": INTERVAL,
  553. "RAW": RAW,
  554. "FLOAT": FLOAT,
  555. "DOUBLE PRECISION": DOUBLE_PRECISION,
  556. "LONG": LONG,
  557. "BINARY_DOUBLE": BINARY_DOUBLE,
  558. "BINARY_FLOAT": BINARY_FLOAT,
  559. }
  560. class OracleTypeCompiler(compiler.GenericTypeCompiler):
  561. # Note:
  562. # Oracle DATE == DATETIME
  563. # Oracle does not allow milliseconds in DATE
  564. # Oracle does not support TIME columns
  565. def visit_datetime(self, type_, **kw):
  566. return self.visit_DATE(type_, **kw)
  567. def visit_float(self, type_, **kw):
  568. return self.visit_FLOAT(type_, **kw)
  569. def visit_unicode(self, type_, **kw):
  570. if self.dialect._use_nchar_for_unicode:
  571. return self.visit_NVARCHAR2(type_, **kw)
  572. else:
  573. return self.visit_VARCHAR2(type_, **kw)
  574. def visit_INTERVAL(self, type_, **kw):
  575. return "INTERVAL DAY%s TO SECOND%s" % (
  576. type_.day_precision is not None
  577. and "(%d)" % type_.day_precision
  578. or "",
  579. type_.second_precision is not None
  580. and "(%d)" % type_.second_precision
  581. or "",
  582. )
  583. def visit_LONG(self, type_, **kw):
  584. return "LONG"
  585. def visit_TIMESTAMP(self, type_, **kw):
  586. if type_.timezone:
  587. return "TIMESTAMP WITH TIME ZONE"
  588. else:
  589. return "TIMESTAMP"
  590. def visit_DOUBLE_PRECISION(self, type_, **kw):
  591. return self._generate_numeric(type_, "DOUBLE PRECISION", **kw)
  592. def visit_BINARY_DOUBLE(self, type_, **kw):
  593. return self._generate_numeric(type_, "BINARY_DOUBLE", **kw)
  594. def visit_BINARY_FLOAT(self, type_, **kw):
  595. return self._generate_numeric(type_, "BINARY_FLOAT", **kw)
  596. def visit_FLOAT(self, type_, **kw):
  597. # don't support conversion between decimal/binary
  598. # precision yet
  599. kw["no_precision"] = True
  600. return self._generate_numeric(type_, "FLOAT", **kw)
  601. def visit_NUMBER(self, type_, **kw):
  602. return self._generate_numeric(type_, "NUMBER", **kw)
  603. def _generate_numeric(
  604. self, type_, name, precision=None, scale=None, no_precision=False, **kw
  605. ):
  606. if precision is None:
  607. precision = type_.precision
  608. if scale is None:
  609. scale = getattr(type_, "scale", None)
  610. if no_precision or precision is None:
  611. return name
  612. elif scale is None:
  613. n = "%(name)s(%(precision)s)"
  614. return n % {"name": name, "precision": precision}
  615. else:
  616. n = "%(name)s(%(precision)s, %(scale)s)"
  617. return n % {"name": name, "precision": precision, "scale": scale}
  618. def visit_string(self, type_, **kw):
  619. return self.visit_VARCHAR2(type_, **kw)
  620. def visit_VARCHAR2(self, type_, **kw):
  621. return self._visit_varchar(type_, "", "2")
  622. def visit_NVARCHAR2(self, type_, **kw):
  623. return self._visit_varchar(type_, "N", "2")
  624. visit_NVARCHAR = visit_NVARCHAR2
  625. def visit_VARCHAR(self, type_, **kw):
  626. return self._visit_varchar(type_, "", "")
  627. def _visit_varchar(self, type_, n, num):
  628. if not type_.length:
  629. return "%(n)sVARCHAR%(two)s" % {"two": num, "n": n}
  630. elif not n and self.dialect._supports_char_length:
  631. varchar = "VARCHAR%(two)s(%(length)s CHAR)"
  632. return varchar % {"length": type_.length, "two": num}
  633. else:
  634. varchar = "%(n)sVARCHAR%(two)s(%(length)s)"
  635. return varchar % {"length": type_.length, "two": num, "n": n}
  636. def visit_text(self, type_, **kw):
  637. return self.visit_CLOB(type_, **kw)
  638. def visit_unicode_text(self, type_, **kw):
  639. if self.dialect._use_nchar_for_unicode:
  640. return self.visit_NCLOB(type_, **kw)
  641. else:
  642. return self.visit_CLOB(type_, **kw)
  643. def visit_large_binary(self, type_, **kw):
  644. return self.visit_BLOB(type_, **kw)
  645. def visit_big_integer(self, type_, **kw):
  646. return self.visit_NUMBER(type_, precision=19, **kw)
  647. def visit_boolean(self, type_, **kw):
  648. return self.visit_SMALLINT(type_, **kw)
  649. def visit_RAW(self, type_, **kw):
  650. if type_.length:
  651. return "RAW(%(length)s)" % {"length": type_.length}
  652. else:
  653. return "RAW"
  654. def visit_ROWID(self, type_, **kw):
  655. return "ROWID"
  656. class OracleCompiler(compiler.SQLCompiler):
  657. """Oracle compiler modifies the lexical structure of Select
  658. statements to work under non-ANSI configured Oracle databases, if
  659. the use_ansi flag is False.
  660. """
  661. compound_keywords = util.update_copy(
  662. compiler.SQLCompiler.compound_keywords,
  663. {expression.CompoundSelect.EXCEPT: "MINUS"},
  664. )
  665. def __init__(self, *args, **kwargs):
  666. self.__wheres = {}
  667. super(OracleCompiler, self).__init__(*args, **kwargs)
  668. def visit_mod_binary(self, binary, operator, **kw):
  669. return "mod(%s, %s)" % (
  670. self.process(binary.left, **kw),
  671. self.process(binary.right, **kw),
  672. )
  673. def visit_now_func(self, fn, **kw):
  674. return "CURRENT_TIMESTAMP"
  675. def visit_char_length_func(self, fn, **kw):
  676. return "LENGTH" + self.function_argspec(fn, **kw)
  677. def visit_match_op_binary(self, binary, operator, **kw):
  678. return "CONTAINS (%s, %s)" % (
  679. self.process(binary.left),
  680. self.process(binary.right),
  681. )
  682. def visit_true(self, expr, **kw):
  683. return "1"
  684. def visit_false(self, expr, **kw):
  685. return "0"
  686. def get_cte_preamble(self, recursive):
  687. return "WITH"
  688. def get_select_hint_text(self, byfroms):
  689. return " ".join("/*+ %s */" % text for table, text in byfroms.items())
  690. def function_argspec(self, fn, **kw):
  691. if len(fn.clauses) > 0 or fn.name.upper() not in NO_ARG_FNS:
  692. return compiler.SQLCompiler.function_argspec(self, fn, **kw)
  693. else:
  694. return ""
  695. def visit_function(self, func, **kw):
  696. text = super(OracleCompiler, self).visit_function(func, **kw)
  697. if kw.get("asfrom", False):
  698. text = "TABLE (%s)" % func
  699. return text
  700. def visit_table_valued_column(self, element, **kw):
  701. text = super(OracleCompiler, self).visit_table_valued_column(
  702. element, **kw
  703. )
  704. text = "COLUMN_VALUE " + text
  705. return text
  706. def default_from(self):
  707. """Called when a ``SELECT`` statement has no froms,
  708. and no ``FROM`` clause is to be appended.
  709. The Oracle compiler tacks a "FROM DUAL" to the statement.
  710. """
  711. return " FROM DUAL"
  712. def visit_join(self, join, from_linter=None, **kwargs):
  713. if self.dialect.use_ansi:
  714. return compiler.SQLCompiler.visit_join(
  715. self, join, from_linter=from_linter, **kwargs
  716. )
  717. else:
  718. if from_linter:
  719. from_linter.edges.add((join.left, join.right))
  720. kwargs["asfrom"] = True
  721. if isinstance(join.right, expression.FromGrouping):
  722. right = join.right.element
  723. else:
  724. right = join.right
  725. return (
  726. self.process(join.left, from_linter=from_linter, **kwargs)
  727. + ", "
  728. + self.process(right, from_linter=from_linter, **kwargs)
  729. )
  730. def _get_nonansi_join_whereclause(self, froms):
  731. clauses = []
  732. def visit_join(join):
  733. if join.isouter:
  734. # https://docs.oracle.com/database/121/SQLRF/queries006.htm#SQLRF52354
  735. # "apply the outer join operator (+) to all columns of B in
  736. # the join condition in the WHERE clause" - that is,
  737. # unconditionally regardless of operator or the other side
  738. def visit_binary(binary):
  739. if isinstance(
  740. binary.left, expression.ColumnClause
  741. ) and join.right.is_derived_from(binary.left.table):
  742. binary.left = _OuterJoinColumn(binary.left)
  743. elif isinstance(
  744. binary.right, expression.ColumnClause
  745. ) and join.right.is_derived_from(binary.right.table):
  746. binary.right = _OuterJoinColumn(binary.right)
  747. clauses.append(
  748. visitors.cloned_traverse(
  749. join.onclause, {}, {"binary": visit_binary}
  750. )
  751. )
  752. else:
  753. clauses.append(join.onclause)
  754. for j in join.left, join.right:
  755. if isinstance(j, expression.Join):
  756. visit_join(j)
  757. elif isinstance(j, expression.FromGrouping):
  758. visit_join(j.element)
  759. for f in froms:
  760. if isinstance(f, expression.Join):
  761. visit_join(f)
  762. if not clauses:
  763. return None
  764. else:
  765. return sql.and_(*clauses)
  766. def visit_outer_join_column(self, vc, **kw):
  767. return self.process(vc.column, **kw) + "(+)"
  768. def visit_sequence(self, seq, **kw):
  769. return self.preparer.format_sequence(seq) + ".nextval"
  770. def get_render_as_alias_suffix(self, alias_name_text):
  771. """Oracle doesn't like ``FROM table AS alias``"""
  772. return " " + alias_name_text
  773. def returning_clause(self, stmt, returning_cols):
  774. columns = []
  775. binds = []
  776. for i, column in enumerate(
  777. expression._select_iterables(returning_cols)
  778. ):
  779. if (
  780. self.isupdate
  781. and isinstance(column, sa_schema.Column)
  782. and isinstance(column.server_default, Computed)
  783. and not self.dialect._supports_update_returning_computed_cols
  784. ):
  785. util.warn(
  786. "Computed columns don't work with Oracle UPDATE "
  787. "statements that use RETURNING; the value of the column "
  788. "*before* the UPDATE takes place is returned. It is "
  789. "advised to not use RETURNING with an Oracle computed "
  790. "column. Consider setting implicit_returning to False on "
  791. "the Table object in order to avoid implicit RETURNING "
  792. "clauses from being generated for this Table."
  793. )
  794. if column.type._has_column_expression:
  795. col_expr = column.type.column_expression(column)
  796. else:
  797. col_expr = column
  798. outparam = sql.outparam("ret_%d" % i, type_=column.type)
  799. self.binds[outparam.key] = outparam
  800. binds.append(
  801. self.bindparam_string(self._truncate_bindparam(outparam))
  802. )
  803. # ensure the ExecutionContext.get_out_parameters() method is
  804. # *not* called; the cx_Oracle dialect wants to handle these
  805. # parameters separately
  806. self.has_out_parameters = False
  807. columns.append(self.process(col_expr, within_columns_clause=False))
  808. self._add_to_result_map(
  809. getattr(col_expr, "name", col_expr._anon_name_label),
  810. getattr(col_expr, "name", col_expr._anon_name_label),
  811. (
  812. column,
  813. getattr(column, "name", None),
  814. getattr(column, "key", None),
  815. ),
  816. column.type,
  817. )
  818. return "RETURNING " + ", ".join(columns) + " INTO " + ", ".join(binds)
  819. def translate_select_structure(self, select_stmt, **kwargs):
  820. select = select_stmt
  821. if not getattr(select, "_oracle_visit", None):
  822. if not self.dialect.use_ansi:
  823. froms = self._display_froms_for_select(
  824. select, kwargs.get("asfrom", False)
  825. )
  826. whereclause = self._get_nonansi_join_whereclause(froms)
  827. if whereclause is not None:
  828. select = select.where(whereclause)
  829. select._oracle_visit = True
  830. # if fetch is used this is not needed
  831. if (
  832. select._has_row_limiting_clause
  833. and select._fetch_clause is None
  834. ):
  835. limit_clause = select._limit_clause
  836. offset_clause = select._offset_clause
  837. if select._simple_int_clause(limit_clause):
  838. limit_clause = limit_clause.render_literal_execute()
  839. if select._simple_int_clause(offset_clause):
  840. offset_clause = offset_clause.render_literal_execute()
  841. # currently using form at:
  842. # https://blogs.oracle.com/oraclemagazine/\
  843. # on-rownum-and-limiting-results
  844. orig_select = select
  845. select = select._generate()
  846. select._oracle_visit = True
  847. # add expressions to accommodate FOR UPDATE OF
  848. for_update = select._for_update_arg
  849. if for_update is not None and for_update.of:
  850. for_update = for_update._clone()
  851. for_update._copy_internals()
  852. for elem in for_update.of:
  853. if not select.selected_columns.contains_column(elem):
  854. select = select.add_columns(elem)
  855. # Wrap the middle select and add the hint
  856. inner_subquery = select.alias()
  857. limitselect = sql.select(
  858. *[
  859. c
  860. for c in inner_subquery.c
  861. if orig_select.selected_columns.corresponding_column(c)
  862. is not None
  863. ]
  864. )
  865. if (
  866. limit_clause is not None
  867. and self.dialect.optimize_limits
  868. and select._simple_int_clause(limit_clause)
  869. ):
  870. limitselect = limitselect.prefix_with(
  871. expression.text(
  872. "/*+ FIRST_ROWS(%s) */"
  873. % self.process(limit_clause, **kwargs)
  874. )
  875. )
  876. limitselect._oracle_visit = True
  877. limitselect._is_wrapper = True
  878. # add expressions to accommodate FOR UPDATE OF
  879. if for_update is not None and for_update.of:
  880. adapter = sql_util.ClauseAdapter(inner_subquery)
  881. for_update.of = [
  882. adapter.traverse(elem) for elem in for_update.of
  883. ]
  884. # If needed, add the limiting clause
  885. if limit_clause is not None:
  886. if select._simple_int_clause(limit_clause) and (
  887. offset_clause is None
  888. or select._simple_int_clause(offset_clause)
  889. ):
  890. max_row = limit_clause
  891. if offset_clause is not None:
  892. max_row = max_row + offset_clause
  893. else:
  894. max_row = limit_clause
  895. if offset_clause is not None:
  896. max_row = max_row + offset_clause
  897. limitselect = limitselect.where(
  898. sql.literal_column("ROWNUM") <= max_row
  899. )
  900. # If needed, add the ora_rn, and wrap again with offset.
  901. if offset_clause is None:
  902. limitselect._for_update_arg = for_update
  903. select = limitselect
  904. else:
  905. limitselect = limitselect.add_columns(
  906. sql.literal_column("ROWNUM").label("ora_rn")
  907. )
  908. limitselect._oracle_visit = True
  909. limitselect._is_wrapper = True
  910. if for_update is not None and for_update.of:
  911. limitselect_cols = limitselect.selected_columns
  912. for elem in for_update.of:
  913. if (
  914. limitselect_cols.corresponding_column(elem)
  915. is None
  916. ):
  917. limitselect = limitselect.add_columns(elem)
  918. limit_subquery = limitselect.alias()
  919. origselect_cols = orig_select.selected_columns
  920. offsetselect = sql.select(
  921. *[
  922. c
  923. for c in limit_subquery.c
  924. if origselect_cols.corresponding_column(c)
  925. is not None
  926. ]
  927. )
  928. offsetselect._oracle_visit = True
  929. offsetselect._is_wrapper = True
  930. if for_update is not None and for_update.of:
  931. adapter = sql_util.ClauseAdapter(limit_subquery)
  932. for_update.of = [
  933. adapter.traverse(elem) for elem in for_update.of
  934. ]
  935. offsetselect = offsetselect.where(
  936. sql.literal_column("ora_rn") > offset_clause
  937. )
  938. offsetselect._for_update_arg = for_update
  939. select = offsetselect
  940. return select
  941. def limit_clause(self, select, **kw):
  942. return ""
  943. def visit_empty_set_expr(self, type_):
  944. return "SELECT 1 FROM DUAL WHERE 1!=1"
  945. def for_update_clause(self, select, **kw):
  946. if self.is_subquery():
  947. return ""
  948. tmp = " FOR UPDATE"
  949. if select._for_update_arg.of:
  950. tmp += " OF " + ", ".join(
  951. self.process(elem, **kw) for elem in select._for_update_arg.of
  952. )
  953. if select._for_update_arg.nowait:
  954. tmp += " NOWAIT"
  955. if select._for_update_arg.skip_locked:
  956. tmp += " SKIP LOCKED"
  957. return tmp
  958. def visit_is_distinct_from_binary(self, binary, operator, **kw):
  959. return "DECODE(%s, %s, 0, 1) = 1" % (
  960. self.process(binary.left),
  961. self.process(binary.right),
  962. )
  963. def visit_is_not_distinct_from_binary(self, binary, operator, **kw):
  964. return "DECODE(%s, %s, 0, 1) = 0" % (
  965. self.process(binary.left),
  966. self.process(binary.right),
  967. )
  968. def _get_regexp_args(self, binary, kw):
  969. string = self.process(binary.left, **kw)
  970. pattern = self.process(binary.right, **kw)
  971. flags = binary.modifiers["flags"]
  972. if flags is not None:
  973. flags = self.process(flags, **kw)
  974. return string, pattern, flags
  975. def visit_regexp_match_op_binary(self, binary, operator, **kw):
  976. string, pattern, flags = self._get_regexp_args(binary, kw)
  977. if flags is None:
  978. return "REGEXP_LIKE(%s, %s)" % (string, pattern)
  979. else:
  980. return "REGEXP_LIKE(%s, %s, %s)" % (string, pattern, flags)
  981. def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
  982. return "NOT %s" % self.visit_regexp_match_op_binary(
  983. binary, operator, **kw
  984. )
  985. def visit_regexp_replace_op_binary(self, binary, operator, **kw):
  986. string, pattern, flags = self._get_regexp_args(binary, kw)
  987. replacement = self.process(binary.modifiers["replacement"], **kw)
  988. if flags is None:
  989. return "REGEXP_REPLACE(%s, %s, %s)" % (
  990. string,
  991. pattern,
  992. replacement,
  993. )
  994. else:
  995. return "REGEXP_REPLACE(%s, %s, %s, %s)" % (
  996. string,
  997. pattern,
  998. replacement,
  999. flags,
  1000. )
  1001. class OracleDDLCompiler(compiler.DDLCompiler):
  1002. def define_constraint_cascades(self, constraint):
  1003. text = ""
  1004. if constraint.ondelete is not None:
  1005. text += " ON DELETE %s" % constraint.ondelete
  1006. # oracle has no ON UPDATE CASCADE -
  1007. # its only available via triggers
  1008. # http://asktom.oracle.com/tkyte/update_cascade/index.html
  1009. if constraint.onupdate is not None:
  1010. util.warn(
  1011. "Oracle does not contain native UPDATE CASCADE "
  1012. "functionality - onupdates will not be rendered for foreign "
  1013. "keys. Consider using deferrable=True, initially='deferred' "
  1014. "or triggers."
  1015. )
  1016. return text
  1017. def visit_drop_table_comment(self, drop):
  1018. return "COMMENT ON TABLE %s IS ''" % self.preparer.format_table(
  1019. drop.element
  1020. )
  1021. def visit_create_index(self, create):
  1022. index = create.element
  1023. self._verify_index_table(index)
  1024. preparer = self.preparer
  1025. text = "CREATE "
  1026. if index.unique:
  1027. text += "UNIQUE "
  1028. if index.dialect_options["oracle"]["bitmap"]:
  1029. text += "BITMAP "
  1030. text += "INDEX %s ON %s (%s)" % (
  1031. self._prepared_index_name(index, include_schema=True),
  1032. preparer.format_table(index.table, use_schema=True),
  1033. ", ".join(
  1034. self.sql_compiler.process(
  1035. expr, include_table=False, literal_binds=True
  1036. )
  1037. for expr in index.expressions
  1038. ),
  1039. )
  1040. if index.dialect_options["oracle"]["compress"] is not False:
  1041. if index.dialect_options["oracle"]["compress"] is True:
  1042. text += " COMPRESS"
  1043. else:
  1044. text += " COMPRESS %d" % (
  1045. index.dialect_options["oracle"]["compress"]
  1046. )
  1047. return text
  1048. def post_create_table(self, table):
  1049. table_opts = []
  1050. opts = table.dialect_options["oracle"]
  1051. if opts["on_commit"]:
  1052. on_commit_options = opts["on_commit"].replace("_", " ").upper()
  1053. table_opts.append("\n ON COMMIT %s" % on_commit_options)
  1054. if opts["compress"]:
  1055. if opts["compress"] is True:
  1056. table_opts.append("\n COMPRESS")
  1057. else:
  1058. table_opts.append("\n COMPRESS FOR %s" % (opts["compress"]))
  1059. return "".join(table_opts)
  1060. def get_identity_options(self, identity_options):
  1061. text = super(OracleDDLCompiler, self).get_identity_options(
  1062. identity_options
  1063. )
  1064. text = text.replace("NO MINVALUE", "NOMINVALUE")
  1065. text = text.replace("NO MAXVALUE", "NOMAXVALUE")
  1066. text = text.replace("NO CYCLE", "NOCYCLE")
  1067. text = text.replace("NO ORDER", "NOORDER")
  1068. return text
  1069. def visit_computed_column(self, generated):
  1070. text = "GENERATED ALWAYS AS (%s)" % self.sql_compiler.process(
  1071. generated.sqltext, include_table=False, literal_binds=True
  1072. )
  1073. if generated.persisted is True:
  1074. raise exc.CompileError(
  1075. "Oracle computed columns do not support 'stored' persistence; "
  1076. "set the 'persisted' flag to None or False for Oracle support."
  1077. )
  1078. elif generated.persisted is False:
  1079. text += " VIRTUAL"
  1080. return text
  1081. def visit_identity_column(self, identity, **kw):
  1082. if identity.always is None:
  1083. kind = ""
  1084. else:
  1085. kind = "ALWAYS" if identity.always else "BY DEFAULT"
  1086. text = "GENERATED %s" % kind
  1087. if identity.on_null:
  1088. text += " ON NULL"
  1089. text += " AS IDENTITY"
  1090. options = self.get_identity_options(identity)
  1091. if options:
  1092. text += " (%s)" % options
  1093. return text
  1094. class OracleIdentifierPreparer(compiler.IdentifierPreparer):
  1095. reserved_words = {x.lower() for x in RESERVED_WORDS}
  1096. illegal_initial_characters = {str(dig) for dig in range(0, 10)}.union(
  1097. ["_", "$"]
  1098. )
  1099. def _bindparam_requires_quotes(self, value):
  1100. """Return True if the given identifier requires quoting."""
  1101. lc_value = value.lower()
  1102. return (
  1103. lc_value in self.reserved_words
  1104. or value[0] in self.illegal_initial_characters
  1105. or not self.legal_characters.match(util.text_type(value))
  1106. )
  1107. def format_savepoint(self, savepoint):
  1108. name = savepoint.ident.lstrip("_")
  1109. return super(OracleIdentifierPreparer, self).format_savepoint(
  1110. savepoint, name
  1111. )
  1112. class OracleExecutionContext(default.DefaultExecutionContext):
  1113. def fire_sequence(self, seq, type_):
  1114. return self._execute_scalar(
  1115. "SELECT "
  1116. + self.identifier_preparer.format_sequence(seq)
  1117. + ".nextval FROM DUAL",
  1118. type_,
  1119. )
  1120. class OracleDialect(default.DefaultDialect):
  1121. name = "oracle"
  1122. supports_statement_cache = True
  1123. supports_alter = True
  1124. supports_unicode_statements = False
  1125. supports_unicode_binds = False
  1126. max_identifier_length = 128
  1127. supports_simple_order_by_label = False
  1128. cte_follows_insert = True
  1129. supports_sequences = True
  1130. sequences_optional = False
  1131. postfetch_lastrowid = False
  1132. default_paramstyle = "named"
  1133. colspecs = colspecs
  1134. ischema_names = ischema_names
  1135. requires_name_normalize = True
  1136. supports_comments = True
  1137. supports_default_values = False
  1138. supports_default_metavalue = True
  1139. supports_empty_insert = False
  1140. supports_identity_columns = True
  1141. statement_compiler = OracleCompiler
  1142. ddl_compiler = OracleDDLCompiler
  1143. type_compiler = OracleTypeCompiler
  1144. preparer = OracleIdentifierPreparer
  1145. execution_ctx_cls = OracleExecutionContext
  1146. reflection_options = ("oracle_resolve_synonyms",)
  1147. _use_nchar_for_unicode = False
  1148. construct_arguments = [
  1149. (
  1150. sa_schema.Table,
  1151. {"resolve_synonyms": False, "on_commit": None, "compress": False},
  1152. ),
  1153. (sa_schema.Index, {"bitmap": False, "compress": False}),
  1154. ]
  1155. @util.deprecated_params(
  1156. use_binds_for_limits=(
  1157. "1.4",
  1158. "The ``use_binds_for_limits`` Oracle dialect parameter is "
  1159. "deprecated. The dialect now renders LIMIT /OFFSET integers "
  1160. "inline in all cases using a post-compilation hook, so that the "
  1161. "value is still represented by a 'bound parameter' on the Core "
  1162. "Expression side.",
  1163. )
  1164. )
  1165. def __init__(
  1166. self,
  1167. use_ansi=True,
  1168. optimize_limits=False,
  1169. use_binds_for_limits=None,
  1170. use_nchar_for_unicode=False,
  1171. exclude_tablespaces=("SYSTEM", "SYSAUX"),
  1172. **kwargs
  1173. ):
  1174. default.DefaultDialect.__init__(self, **kwargs)
  1175. self._use_nchar_for_unicode = use_nchar_for_unicode
  1176. self.use_ansi = use_ansi
  1177. self.optimize_limits = optimize_limits
  1178. self.exclude_tablespaces = exclude_tablespaces
  1179. def initialize(self, connection):
  1180. super(OracleDialect, self).initialize(connection)
  1181. self.implicit_returning = self.__dict__.get(
  1182. "implicit_returning", self.server_version_info > (10,)
  1183. )
  1184. if self._is_oracle_8:
  1185. self.colspecs = self.colspecs.copy()
  1186. self.colspecs.pop(sqltypes.Interval)
  1187. self.use_ansi = False
  1188. self.supports_identity_columns = self.server_version_info >= (12,)
  1189. def _get_effective_compat_server_version_info(self, connection):
  1190. # dialect does not need compat levels below 12.2, so don't query
  1191. # in those cases
  1192. if self.server_version_info < (12, 2):
  1193. return self.server_version_info
  1194. try:
  1195. compat = connection.exec_driver_sql(
  1196. "SELECT value FROM v$parameter WHERE name = 'compatible'"
  1197. ).scalar()
  1198. except exc.DBAPIError:
  1199. compat = None
  1200. if compat:
  1201. try:
  1202. return tuple(int(x) for x in compat.split("."))
  1203. except:
  1204. return self.server_version_info
  1205. else:
  1206. return self.server_version_info
  1207. @property
  1208. def _is_oracle_8(self):
  1209. return self.server_version_info and self.server_version_info < (9,)
  1210. @property
  1211. def _supports_table_compression(self):
  1212. return self.server_version_info and self.server_version_info >= (10, 1)
  1213. @property
  1214. def _supports_table_compress_for(self):
  1215. return self.server_version_info and self.server_version_info >= (11,)
  1216. @property
  1217. def _supports_char_length(self):
  1218. return not self._is_oracle_8
  1219. @property
  1220. def _supports_update_returning_computed_cols(self):
  1221. # on version 18 this error is no longet present while it happens on 11
  1222. # it may work also on versions before the 18
  1223. return self.server_version_info and self.server_version_info >= (18,)
  1224. def do_release_savepoint(self, connection, name):
  1225. # Oracle does not support RELEASE SAVEPOINT
  1226. pass
  1227. def _check_max_identifier_length(self, connection):
  1228. if self._get_effective_compat_server_version_info(connection) < (
  1229. 12,
  1230. 2,
  1231. ):
  1232. return 30
  1233. else:
  1234. # use the default
  1235. return None
  1236. def _check_unicode_returns(self, connection):
  1237. additional_tests = [
  1238. expression.cast(
  1239. expression.literal_column("'test nvarchar2 returns'"),
  1240. sqltypes.NVARCHAR(60),
  1241. )
  1242. ]
  1243. return super(OracleDialect, self)._check_unicode_returns(
  1244. connection, additional_tests
  1245. )
  1246. _isolation_lookup = ["READ COMMITTED", "SERIALIZABLE"]
  1247. def get_isolation_level(self, connection):
  1248. raise NotImplementedError("implemented by cx_Oracle dialect")
  1249. def get_default_isolation_level(self, dbapi_conn):
  1250. try:
  1251. return self.get_isolation_level(dbapi_conn)
  1252. except NotImplementedError:
  1253. raise
  1254. except:
  1255. return "READ COMMITTED"
  1256. def set_isolation_level(self, connection, level):
  1257. raise NotImplementedError("implemented by cx_Oracle dialect")
  1258. def has_table(self, connection, table_name, schema=None):
  1259. self._ensure_has_table_connection(connection)
  1260. if not schema:
  1261. schema = self.default_schema_name
  1262. cursor = connection.execute(
  1263. sql.text(
  1264. "SELECT table_name FROM all_tables "
  1265. "WHERE table_name = :name AND owner = :schema_name"
  1266. ),
  1267. dict(
  1268. name=self.denormalize_name(table_name),
  1269. schema_name=self.denormalize_name(schema),
  1270. ),
  1271. )
  1272. return cursor.first() is not None
  1273. def has_sequence(self, connection, sequence_name, schema=None):
  1274. if not schema:
  1275. schema = self.default_schema_name
  1276. cursor = connection.execute(
  1277. sql.text(
  1278. "SELECT sequence_name FROM all_sequences "
  1279. "WHERE sequence_name = :name AND "
  1280. "sequence_owner = :schema_name"
  1281. ),
  1282. dict(
  1283. name=self.denormalize_name(sequence_name),
  1284. schema_name=self.denormalize_name(schema),
  1285. ),
  1286. )
  1287. return cursor.first() is not None
  1288. def _get_default_schema_name(self, connection):
  1289. return self.normalize_name(
  1290. connection.exec_driver_sql(
  1291. "select sys_context( 'userenv', 'current_schema' ) from dual"
  1292. ).scalar()
  1293. )
  1294. def _resolve_synonym(
  1295. self,
  1296. connection,
  1297. desired_owner=None,
  1298. desired_synonym=None,
  1299. desired_table=None,
  1300. ):
  1301. """search for a local synonym matching the given desired owner/name.
  1302. if desired_owner is None, attempts to locate a distinct owner.
  1303. returns the actual name, owner, dblink name, and synonym name if
  1304. found.
  1305. """
  1306. q = (
  1307. "SELECT owner, table_owner, table_name, db_link, "
  1308. "synonym_name FROM all_synonyms WHERE "
  1309. )
  1310. clauses = []
  1311. params = {}
  1312. if desired_synonym:
  1313. clauses.append("synonym_name = :synonym_name")
  1314. params["synonym_name"] = desired_synonym
  1315. if desired_owner:
  1316. clauses.append("owner = :desired_owner")
  1317. params["desired_owner"] = desired_owner
  1318. if desired_table:
  1319. clauses.append("table_name = :tname")
  1320. params["tname"] = desired_table
  1321. q += " AND ".join(clauses)
  1322. result = connection.execution_options(future_result=True).execute(
  1323. sql.text(q), params
  1324. )
  1325. if desired_owner:
  1326. row = result.mappings().first()
  1327. if row:
  1328. return (
  1329. row["table_name"],
  1330. row["table_owner"],
  1331. row["db_link"],
  1332. row["synonym_name"],
  1333. )
  1334. else:
  1335. return None, None, None, None
  1336. else:
  1337. rows = result.mappings().all()
  1338. if len(rows) > 1:
  1339. raise AssertionError(
  1340. "There are multiple tables visible to the schema, you "
  1341. "must specify owner"
  1342. )
  1343. elif len(rows) == 1:
  1344. row = rows[0]
  1345. return (
  1346. row["table_name"],
  1347. row["table_owner"],
  1348. row["db_link"],
  1349. row["synonym_name"],
  1350. )
  1351. else:
  1352. return None, None, None, None
  1353. @reflection.cache
  1354. def _prepare_reflection_args(
  1355. self,
  1356. connection,
  1357. table_name,
  1358. schema=None,
  1359. resolve_synonyms=False,
  1360. dblink="",
  1361. **kw
  1362. ):
  1363. if resolve_synonyms:
  1364. actual_name, owner, dblink, synonym = self._resolve_synonym(
  1365. connection,
  1366. desired_owner=self.denormalize_name(schema),
  1367. desired_synonym=self.denormalize_name(table_name),
  1368. )
  1369. else:
  1370. actual_name, owner, dblink, synonym = None, None, None, None
  1371. if not actual_name:
  1372. actual_name = self.denormalize_name(table_name)
  1373. if dblink:
  1374. # using user_db_links here since all_db_links appears
  1375. # to have more restricted permissions.
  1376. # http://docs.oracle.com/cd/B28359_01/server.111/b28310/ds_admin005.htm
  1377. # will need to hear from more users if we are doing
  1378. # the right thing here. See [ticket:2619]
  1379. owner = connection.scalar(
  1380. sql.text(
  1381. "SELECT username FROM user_db_links " "WHERE db_link=:link"
  1382. ),
  1383. dict(link=dblink),
  1384. )
  1385. dblink = "@" + dblink
  1386. elif not owner:
  1387. owner = self.denormalize_name(schema or self.default_schema_name)
  1388. return (actual_name, owner, dblink or "", synonym)
  1389. @reflection.cache
  1390. def get_schema_names(self, connection, **kw):
  1391. s = "SELECT username FROM all_users ORDER BY username"
  1392. cursor = connection.exec_driver_sql(s)
  1393. return [self.normalize_name(row[0]) for row in cursor]
  1394. @reflection.cache
  1395. def get_table_names(self, connection, schema=None, **kw):
  1396. schema = self.denormalize_name(schema or self.default_schema_name)
  1397. # note that table_names() isn't loading DBLINKed or synonym'ed tables
  1398. if schema is None:
  1399. schema = self.default_schema_name
  1400. sql_str = "SELECT table_name FROM all_tables WHERE "
  1401. if self.exclude_tablespaces:
  1402. sql_str += (
  1403. "nvl(tablespace_name, 'no tablespace') "
  1404. "NOT IN (%s) AND "
  1405. % (", ".join(["'%s'" % ts for ts in self.exclude_tablespaces]))
  1406. )
  1407. sql_str += (
  1408. "OWNER = :owner " "AND IOT_NAME IS NULL " "AND DURATION IS NULL"
  1409. )
  1410. cursor = connection.execute(sql.text(sql_str), dict(owner=schema))
  1411. return [self.normalize_name(row[0]) for row in cursor]
  1412. @reflection.cache
  1413. def get_temp_table_names(self, connection, **kw):
  1414. schema = self.denormalize_name(self.default_schema_name)
  1415. sql_str = "SELECT table_name FROM all_tables WHERE "
  1416. if self.exclude_tablespaces:
  1417. sql_str += (
  1418. "nvl(tablespace_name, 'no tablespace') "
  1419. "NOT IN (%s) AND "
  1420. % (", ".join(["'%s'" % ts for ts in self.exclude_tablespaces]))
  1421. )
  1422. sql_str += (
  1423. "OWNER = :owner "
  1424. "AND IOT_NAME IS NULL "
  1425. "AND DURATION IS NOT NULL"
  1426. )
  1427. cursor = connection.execute(sql.text(sql_str), dict(owner=schema))
  1428. return [self.normalize_name(row[0]) for row in cursor]
  1429. @reflection.cache
  1430. def get_view_names(self, connection, schema=None, **kw):
  1431. schema = self.denormalize_name(schema or self.default_schema_name)
  1432. s = sql.text("SELECT view_name FROM all_views WHERE owner = :owner")
  1433. cursor = connection.execute(
  1434. s, dict(owner=self.denormalize_name(schema))
  1435. )
  1436. return [self.normalize_name(row[0]) for row in cursor]
  1437. @reflection.cache
  1438. def get_sequence_names(self, connection, schema=None, **kw):
  1439. if not schema:
  1440. schema = self.default_schema_name
  1441. cursor = connection.execute(
  1442. sql.text(
  1443. "SELECT sequence_name FROM all_sequences "
  1444. "WHERE sequence_owner = :schema_name"
  1445. ),
  1446. dict(schema_name=self.denormalize_name(schema)),
  1447. )
  1448. return [self.normalize_name(row[0]) for row in cursor]
  1449. @reflection.cache
  1450. def get_table_options(self, connection, table_name, schema=None, **kw):
  1451. options = {}
  1452. resolve_synonyms = kw.get("oracle_resolve_synonyms", False)
  1453. dblink = kw.get("dblink", "")
  1454. info_cache = kw.get("info_cache")
  1455. (table_name, schema, dblink, synonym) = self._prepare_reflection_args(
  1456. connection,
  1457. table_name,
  1458. schema,
  1459. resolve_synonyms,
  1460. dblink,
  1461. info_cache=info_cache,
  1462. )
  1463. params = {"table_name": table_name}
  1464. columns = ["table_name"]
  1465. if self._supports_table_compression:
  1466. columns.append("compression")
  1467. if self._supports_table_compress_for:
  1468. columns.append("compress_for")
  1469. text = (
  1470. "SELECT %(columns)s "
  1471. "FROM ALL_TABLES%(dblink)s "
  1472. "WHERE table_name = :table_name"
  1473. )
  1474. if schema is not None:
  1475. params["owner"] = schema
  1476. text += " AND owner = :owner "
  1477. text = text % {"dblink": dblink, "columns": ", ".join(columns)}
  1478. result = connection.execute(sql.text(text), params)
  1479. enabled = dict(DISABLED=False, ENABLED=True)
  1480. row = result.first()
  1481. if row:
  1482. if "compression" in row._fields and enabled.get(
  1483. row.compression, False
  1484. ):
  1485. if "compress_for" in row._fields:
  1486. options["oracle_compress"] = row.compress_for
  1487. else:
  1488. options["oracle_compress"] = True
  1489. return options
  1490. @reflection.cache
  1491. def get_columns(self, connection, table_name, schema=None, **kw):
  1492. """
  1493. kw arguments can be:
  1494. oracle_resolve_synonyms
  1495. dblink
  1496. """
  1497. resolve_synonyms = kw.get("oracle_resolve_synonyms", False)
  1498. dblink = kw.get("dblink", "")
  1499. info_cache = kw.get("info_cache")
  1500. (table_name, schema, dblink, synonym) = self._prepare_reflection_args(
  1501. connection,
  1502. table_name,
  1503. schema,
  1504. resolve_synonyms,
  1505. dblink,
  1506. info_cache=info_cache,
  1507. )
  1508. columns = []
  1509. if self._supports_char_length:
  1510. char_length_col = "char_length"
  1511. else:
  1512. char_length_col = "data_length"
  1513. if self.server_version_info >= (12,):
  1514. identity_cols = """\
  1515. col.default_on_null,
  1516. (
  1517. SELECT id.generation_type || ',' || id.IDENTITY_OPTIONS
  1518. FROM ALL_TAB_IDENTITY_COLS%(dblink)s id
  1519. WHERE col.table_name = id.table_name
  1520. AND col.column_name = id.column_name
  1521. AND col.owner = id.owner
  1522. ) AS identity_options""" % {
  1523. "dblink": dblink
  1524. }
  1525. else:
  1526. identity_cols = "NULL as default_on_null, NULL as identity_options"
  1527. params = {"table_name": table_name}
  1528. text = """
  1529. SELECT
  1530. col.column_name,
  1531. col.data_type,
  1532. col.%(char_length_col)s,
  1533. col.data_precision,
  1534. col.data_scale,
  1535. col.nullable,
  1536. col.data_default,
  1537. com.comments,
  1538. col.virtual_column,
  1539. %(identity_cols)s
  1540. FROM all_tab_cols%(dblink)s col
  1541. LEFT JOIN all_col_comments%(dblink)s com
  1542. ON col.table_name = com.table_name
  1543. AND col.column_name = com.column_name
  1544. AND col.owner = com.owner
  1545. WHERE col.table_name = :table_name
  1546. AND col.hidden_column = 'NO'
  1547. """
  1548. if schema is not None:
  1549. params["owner"] = schema
  1550. text += " AND col.owner = :owner "
  1551. text += " ORDER BY col.column_id"
  1552. text = text % {
  1553. "dblink": dblink,
  1554. "char_length_col": char_length_col,
  1555. "identity_cols": identity_cols,
  1556. }
  1557. c = connection.execute(sql.text(text), params)
  1558. for row in c:
  1559. colname = self.normalize_name(row[0])
  1560. orig_colname = row[0]
  1561. coltype = row[1]
  1562. length = row[2]
  1563. precision = row[3]
  1564. scale = row[4]
  1565. nullable = row[5] == "Y"
  1566. default = row[6]
  1567. comment = row[7]
  1568. generated = row[8]
  1569. default_on_nul = row[9]
  1570. identity_options = row[10]
  1571. if coltype == "NUMBER":
  1572. if precision is None and scale == 0:
  1573. coltype = INTEGER()
  1574. else:
  1575. coltype = NUMBER(precision, scale)
  1576. elif coltype == "FLOAT":
  1577. # TODO: support "precision" here as "binary_precision"
  1578. coltype = FLOAT()
  1579. elif coltype in ("VARCHAR2", "NVARCHAR2", "CHAR", "NCHAR"):
  1580. coltype = self.ischema_names.get(coltype)(length)
  1581. elif "WITH TIME ZONE" in coltype:
  1582. coltype = TIMESTAMP(timezone=True)
  1583. else:
  1584. coltype = re.sub(r"\(\d+\)", "", coltype)
  1585. try:
  1586. coltype = self.ischema_names[coltype]
  1587. except KeyError:
  1588. util.warn(
  1589. "Did not recognize type '%s' of column '%s'"
  1590. % (coltype, colname)
  1591. )
  1592. coltype = sqltypes.NULLTYPE
  1593. if generated == "YES":
  1594. computed = dict(sqltext=default)
  1595. default = None
  1596. else:
  1597. computed = None
  1598. if identity_options is not None:
  1599. identity = self._parse_identity_options(
  1600. identity_options, default_on_nul
  1601. )
  1602. default = None
  1603. else:
  1604. identity = None
  1605. cdict = {
  1606. "name": colname,
  1607. "type": coltype,
  1608. "nullable": nullable,
  1609. "default": default,
  1610. "autoincrement": "auto",
  1611. "comment": comment,
  1612. }
  1613. if orig_colname.lower() == orig_colname:
  1614. cdict["quote"] = True
  1615. if computed is not None:
  1616. cdict["computed"] = computed
  1617. if identity is not None:
  1618. cdict["identity"] = identity
  1619. columns.append(cdict)
  1620. return columns
  1621. def _parse_identity_options(self, identity_options, default_on_nul):
  1622. # identity_options is a string that starts with 'ALWAYS,' or
  1623. # 'BY DEFAULT,' and continues with
  1624. # START WITH: 1, INCREMENT BY: 1, MAX_VALUE: 123, MIN_VALUE: 1,
  1625. # CYCLE_FLAG: N, CACHE_SIZE: 1, ORDER_FLAG: N, SCALE_FLAG: N,
  1626. # EXTEND_FLAG: N, SESSION_FLAG: N, KEEP_VALUE: N
  1627. parts = [p.strip() for p in identity_options.split(",")]
  1628. identity = {
  1629. "always": parts[0] == "ALWAYS",
  1630. "on_null": default_on_nul == "YES",
  1631. }
  1632. for part in parts[1:]:
  1633. option, value = part.split(":")
  1634. value = value.strip()
  1635. if "START WITH" in option:
  1636. identity["start"] = compat.long_type(value)
  1637. elif "INCREMENT BY" in option:
  1638. identity["increment"] = compat.long_type(value)
  1639. elif "MAX_VALUE" in option:
  1640. identity["maxvalue"] = compat.long_type(value)
  1641. elif "MIN_VALUE" in option:
  1642. identity["minvalue"] = compat.long_type(value)
  1643. elif "CYCLE_FLAG" in option:
  1644. identity["cycle"] = value == "Y"
  1645. elif "CACHE_SIZE" in option:
  1646. identity["cache"] = compat.long_type(value)
  1647. elif "ORDER_FLAG" in option:
  1648. identity["order"] = value == "Y"
  1649. return identity
  1650. @reflection.cache
  1651. def get_table_comment(
  1652. self,
  1653. connection,
  1654. table_name,
  1655. schema=None,
  1656. resolve_synonyms=False,
  1657. dblink="",
  1658. **kw
  1659. ):
  1660. info_cache = kw.get("info_cache")
  1661. (table_name, schema, dblink, synonym) = self._prepare_reflection_args(
  1662. connection,
  1663. table_name,
  1664. schema,
  1665. resolve_synonyms,
  1666. dblink,
  1667. info_cache=info_cache,
  1668. )
  1669. if not schema:
  1670. schema = self.default_schema_name
  1671. COMMENT_SQL = """
  1672. SELECT comments
  1673. FROM all_tab_comments
  1674. WHERE table_name = :table_name AND owner = :schema_name
  1675. """
  1676. c = connection.execute(
  1677. sql.text(COMMENT_SQL),
  1678. dict(table_name=table_name, schema_name=schema),
  1679. )
  1680. return {"text": c.scalar()}
  1681. @reflection.cache
  1682. def get_indexes(
  1683. self,
  1684. connection,
  1685. table_name,
  1686. schema=None,
  1687. resolve_synonyms=False,
  1688. dblink="",
  1689. **kw
  1690. ):
  1691. info_cache = kw.get("info_cache")
  1692. (table_name, schema, dblink, synonym) = self._prepare_reflection_args(
  1693. connection,
  1694. table_name,
  1695. schema,
  1696. resolve_synonyms,
  1697. dblink,
  1698. info_cache=info_cache,
  1699. )
  1700. indexes = []
  1701. params = {"table_name": table_name}
  1702. text = (
  1703. "SELECT a.index_name, a.column_name, "
  1704. "\nb.index_type, b.uniqueness, b.compression, b.prefix_length "
  1705. "\nFROM ALL_IND_COLUMNS%(dblink)s a, "
  1706. "\nALL_INDEXES%(dblink)s b "
  1707. "\nWHERE "
  1708. "\na.index_name = b.index_name "
  1709. "\nAND a.table_owner = b.table_owner "
  1710. "\nAND a.table_name = b.table_name "
  1711. "\nAND a.table_name = :table_name "
  1712. )
  1713. if schema is not None:
  1714. params["schema"] = schema
  1715. text += "AND a.table_owner = :schema "
  1716. text += "ORDER BY a.index_name, a.column_position"
  1717. text = text % {"dblink": dblink}
  1718. q = sql.text(text)
  1719. rp = connection.execute(q, params)
  1720. indexes = []
  1721. last_index_name = None
  1722. pk_constraint = self.get_pk_constraint(
  1723. connection,
  1724. table_name,
  1725. schema,
  1726. resolve_synonyms=resolve_synonyms,
  1727. dblink=dblink,
  1728. info_cache=kw.get("info_cache"),
  1729. )
  1730. uniqueness = dict(NONUNIQUE=False, UNIQUE=True)
  1731. enabled = dict(DISABLED=False, ENABLED=True)
  1732. oracle_sys_col = re.compile(r"SYS_NC\d+\$", re.IGNORECASE)
  1733. index = None
  1734. for rset in rp:
  1735. index_name_normalized = self.normalize_name(rset.index_name)
  1736. # skip primary key index. This is refined as of
  1737. # [ticket:5421]. Note that ALL_INDEXES.GENERATED will by "Y"
  1738. # if the name of this index was generated by Oracle, however
  1739. # if a named primary key constraint was created then this flag
  1740. # is false.
  1741. if (
  1742. pk_constraint
  1743. and index_name_normalized == pk_constraint["name"]
  1744. ):
  1745. continue
  1746. if rset.index_name != last_index_name:
  1747. index = dict(
  1748. name=index_name_normalized,
  1749. column_names=[],
  1750. dialect_options={},
  1751. )
  1752. indexes.append(index)
  1753. index["unique"] = uniqueness.get(rset.uniqueness, False)
  1754. if rset.index_type in ("BITMAP", "FUNCTION-BASED BITMAP"):
  1755. index["dialect_options"]["oracle_bitmap"] = True
  1756. if enabled.get(rset.compression, False):
  1757. index["dialect_options"][
  1758. "oracle_compress"
  1759. ] = rset.prefix_length
  1760. # filter out Oracle SYS_NC names. could also do an outer join
  1761. # to the all_tab_columns table and check for real col names there.
  1762. if not oracle_sys_col.match(rset.column_name):
  1763. index["column_names"].append(
  1764. self.normalize_name(rset.column_name)
  1765. )
  1766. last_index_name = rset.index_name
  1767. return indexes
  1768. @reflection.cache
  1769. def _get_constraint_data(
  1770. self, connection, table_name, schema=None, dblink="", **kw
  1771. ):
  1772. params = {"table_name": table_name}
  1773. text = (
  1774. "SELECT"
  1775. "\nac.constraint_name," # 0
  1776. "\nac.constraint_type," # 1
  1777. "\nloc.column_name AS local_column," # 2
  1778. "\nrem.table_name AS remote_table," # 3
  1779. "\nrem.column_name AS remote_column," # 4
  1780. "\nrem.owner AS remote_owner," # 5
  1781. "\nloc.position as loc_pos," # 6
  1782. "\nrem.position as rem_pos," # 7
  1783. "\nac.search_condition," # 8
  1784. "\nac.delete_rule" # 9
  1785. "\nFROM all_constraints%(dblink)s ac,"
  1786. "\nall_cons_columns%(dblink)s loc,"
  1787. "\nall_cons_columns%(dblink)s rem"
  1788. "\nWHERE ac.table_name = :table_name"
  1789. "\nAND ac.constraint_type IN ('R','P', 'U', 'C')"
  1790. )
  1791. if schema is not None:
  1792. params["owner"] = schema
  1793. text += "\nAND ac.owner = :owner"
  1794. text += (
  1795. "\nAND ac.owner = loc.owner"
  1796. "\nAND ac.constraint_name = loc.constraint_name"
  1797. "\nAND ac.r_owner = rem.owner(+)"
  1798. "\nAND ac.r_constraint_name = rem.constraint_name(+)"
  1799. "\nAND (rem.position IS NULL or loc.position=rem.position)"
  1800. "\nORDER BY ac.constraint_name, loc.position"
  1801. )
  1802. text = text % {"dblink": dblink}
  1803. rp = connection.execute(sql.text(text), params)
  1804. constraint_data = rp.fetchall()
  1805. return constraint_data
  1806. @reflection.cache
  1807. def get_pk_constraint(self, connection, table_name, schema=None, **kw):
  1808. resolve_synonyms = kw.get("oracle_resolve_synonyms", False)
  1809. dblink = kw.get("dblink", "")
  1810. info_cache = kw.get("info_cache")
  1811. (table_name, schema, dblink, synonym) = self._prepare_reflection_args(
  1812. connection,
  1813. table_name,
  1814. schema,
  1815. resolve_synonyms,
  1816. dblink,
  1817. info_cache=info_cache,
  1818. )
  1819. pkeys = []
  1820. constraint_name = None
  1821. constraint_data = self._get_constraint_data(
  1822. connection,
  1823. table_name,
  1824. schema,
  1825. dblink,
  1826. info_cache=kw.get("info_cache"),
  1827. )
  1828. for row in constraint_data:
  1829. (
  1830. cons_name,
  1831. cons_type,
  1832. local_column,
  1833. remote_table,
  1834. remote_column,
  1835. remote_owner,
  1836. ) = row[0:2] + tuple([self.normalize_name(x) for x in row[2:6]])
  1837. if cons_type == "P":
  1838. if constraint_name is None:
  1839. constraint_name = self.normalize_name(cons_name)
  1840. pkeys.append(local_column)
  1841. return {"constrained_columns": pkeys, "name": constraint_name}
  1842. @reflection.cache
  1843. def get_foreign_keys(self, connection, table_name, schema=None, **kw):
  1844. """
  1845. kw arguments can be:
  1846. oracle_resolve_synonyms
  1847. dblink
  1848. """
  1849. requested_schema = schema # to check later on
  1850. resolve_synonyms = kw.get("oracle_resolve_synonyms", False)
  1851. dblink = kw.get("dblink", "")
  1852. info_cache = kw.get("info_cache")
  1853. (table_name, schema, dblink, synonym) = self._prepare_reflection_args(
  1854. connection,
  1855. table_name,
  1856. schema,
  1857. resolve_synonyms,
  1858. dblink,
  1859. info_cache=info_cache,
  1860. )
  1861. constraint_data = self._get_constraint_data(
  1862. connection,
  1863. table_name,
  1864. schema,
  1865. dblink,
  1866. info_cache=kw.get("info_cache"),
  1867. )
  1868. def fkey_rec():
  1869. return {
  1870. "name": None,
  1871. "constrained_columns": [],
  1872. "referred_schema": None,
  1873. "referred_table": None,
  1874. "referred_columns": [],
  1875. "options": {},
  1876. }
  1877. fkeys = util.defaultdict(fkey_rec)
  1878. for row in constraint_data:
  1879. (
  1880. cons_name,
  1881. cons_type,
  1882. local_column,
  1883. remote_table,
  1884. remote_column,
  1885. remote_owner,
  1886. ) = row[0:2] + tuple([self.normalize_name(x) for x in row[2:6]])
  1887. cons_name = self.normalize_name(cons_name)
  1888. if cons_type == "R":
  1889. if remote_table is None:
  1890. # ticket 363
  1891. util.warn(
  1892. (
  1893. "Got 'None' querying 'table_name' from "
  1894. "all_cons_columns%(dblink)s - does the user have "
  1895. "proper rights to the table?"
  1896. )
  1897. % {"dblink": dblink}
  1898. )
  1899. continue
  1900. rec = fkeys[cons_name]
  1901. rec["name"] = cons_name
  1902. local_cols, remote_cols = (
  1903. rec["constrained_columns"],
  1904. rec["referred_columns"],
  1905. )
  1906. if not rec["referred_table"]:
  1907. if resolve_synonyms:
  1908. (
  1909. ref_remote_name,
  1910. ref_remote_owner,
  1911. ref_dblink,
  1912. ref_synonym,
  1913. ) = self._resolve_synonym(
  1914. connection,
  1915. desired_owner=self.denormalize_name(remote_owner),
  1916. desired_table=self.denormalize_name(remote_table),
  1917. )
  1918. if ref_synonym:
  1919. remote_table = self.normalize_name(ref_synonym)
  1920. remote_owner = self.normalize_name(
  1921. ref_remote_owner
  1922. )
  1923. rec["referred_table"] = remote_table
  1924. if (
  1925. requested_schema is not None
  1926. or self.denormalize_name(remote_owner) != schema
  1927. ):
  1928. rec["referred_schema"] = remote_owner
  1929. if row[9] != "NO ACTION":
  1930. rec["options"]["ondelete"] = row[9]
  1931. local_cols.append(local_column)
  1932. remote_cols.append(remote_column)
  1933. return list(fkeys.values())
  1934. @reflection.cache
  1935. def get_unique_constraints(
  1936. self, connection, table_name, schema=None, **kw
  1937. ):
  1938. resolve_synonyms = kw.get("oracle_resolve_synonyms", False)
  1939. dblink = kw.get("dblink", "")
  1940. info_cache = kw.get("info_cache")
  1941. (table_name, schema, dblink, synonym) = self._prepare_reflection_args(
  1942. connection,
  1943. table_name,
  1944. schema,
  1945. resolve_synonyms,
  1946. dblink,
  1947. info_cache=info_cache,
  1948. )
  1949. constraint_data = self._get_constraint_data(
  1950. connection,
  1951. table_name,
  1952. schema,
  1953. dblink,
  1954. info_cache=kw.get("info_cache"),
  1955. )
  1956. unique_keys = filter(lambda x: x[1] == "U", constraint_data)
  1957. uniques_group = groupby(unique_keys, lambda x: x[0])
  1958. index_names = {
  1959. ix["name"]
  1960. for ix in self.get_indexes(connection, table_name, schema=schema)
  1961. }
  1962. return [
  1963. {
  1964. "name": name,
  1965. "column_names": cols,
  1966. "duplicates_index": name if name in index_names else None,
  1967. }
  1968. for name, cols in [
  1969. [
  1970. self.normalize_name(i[0]),
  1971. [self.normalize_name(x[2]) for x in i[1]],
  1972. ]
  1973. for i in uniques_group
  1974. ]
  1975. ]
  1976. @reflection.cache
  1977. def get_view_definition(
  1978. self,
  1979. connection,
  1980. view_name,
  1981. schema=None,
  1982. resolve_synonyms=False,
  1983. dblink="",
  1984. **kw
  1985. ):
  1986. info_cache = kw.get("info_cache")
  1987. (view_name, schema, dblink, synonym) = self._prepare_reflection_args(
  1988. connection,
  1989. view_name,
  1990. schema,
  1991. resolve_synonyms,
  1992. dblink,
  1993. info_cache=info_cache,
  1994. )
  1995. params = {"view_name": view_name}
  1996. text = "SELECT text FROM all_views WHERE view_name=:view_name"
  1997. if schema is not None:
  1998. text += " AND owner = :schema"
  1999. params["schema"] = schema
  2000. rp = connection.execute(sql.text(text), params).scalar()
  2001. if rp:
  2002. if util.py2k:
  2003. rp = rp.decode(self.encoding)
  2004. return rp
  2005. else:
  2006. return None
  2007. @reflection.cache
  2008. def get_check_constraints(
  2009. self, connection, table_name, schema=None, include_all=False, **kw
  2010. ):
  2011. resolve_synonyms = kw.get("oracle_resolve_synonyms", False)
  2012. dblink = kw.get("dblink", "")
  2013. info_cache = kw.get("info_cache")
  2014. (table_name, schema, dblink, synonym) = self._prepare_reflection_args(
  2015. connection,
  2016. table_name,
  2017. schema,
  2018. resolve_synonyms,
  2019. dblink,
  2020. info_cache=info_cache,
  2021. )
  2022. constraint_data = self._get_constraint_data(
  2023. connection,
  2024. table_name,
  2025. schema,
  2026. dblink,
  2027. info_cache=kw.get("info_cache"),
  2028. )
  2029. check_constraints = filter(lambda x: x[1] == "C", constraint_data)
  2030. return [
  2031. {"name": self.normalize_name(cons[0]), "sqltext": cons[8]}
  2032. for cons in check_constraints
  2033. if include_all or not re.match(r"..+?. IS NOT NULL$", cons[8])
  2034. ]
  2035. class _OuterJoinColumn(sql.ClauseElement):
  2036. __visit_name__ = "outer_join_column"
  2037. def __init__(self, column):
  2038. self.column = column