base.py 86 KB

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