base.py 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232
  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. # mypy: ignore-errors
  8. r"""
  9. .. dialect:: oracle
  10. :name: Oracle
  11. :full_support: 18c
  12. :normal_support: 11+
  13. :best_effort: 9+
  14. Auto Increment Behavior
  15. -----------------------
  16. SQLAlchemy Table objects which include integer primary keys are usually
  17. assumed to have "autoincrementing" behavior, meaning they can generate their
  18. own primary key values upon INSERT. For use within Oracle, two options are
  19. available, which are the use of IDENTITY columns (Oracle 12 and above only)
  20. or the association of a SEQUENCE with the column.
  21. Specifying GENERATED AS IDENTITY (Oracle 12 and above)
  22. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  23. Starting from version 12 Oracle can make use of identity columns using
  24. the :class:`_sql.Identity` to specify the autoincrementing behavior::
  25. t = Table('mytable', metadata,
  26. Column('id', Integer, Identity(start=3), primary_key=True),
  27. Column(...), ...
  28. )
  29. The CREATE TABLE for the above :class:`_schema.Table` object would be:
  30. .. sourcecode:: sql
  31. CREATE TABLE mytable (
  32. id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 3),
  33. ...,
  34. PRIMARY KEY (id)
  35. )
  36. The :class:`_schema.Identity` object support many options to control the
  37. "autoincrementing" behavior of the column, like the starting value, the
  38. incrementing value, etc.
  39. In addition to the standard options, Oracle supports setting
  40. :paramref:`_schema.Identity.always` to ``None`` to use the default
  41. generated mode, rendering GENERATED AS IDENTITY in the DDL. It also supports
  42. setting :paramref:`_schema.Identity.on_null` to ``True`` to specify ON NULL
  43. in conjunction with a 'BY DEFAULT' identity column.
  44. Using a SEQUENCE (all Oracle versions)
  45. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  46. Older version of Oracle had no "autoincrement"
  47. feature, SQLAlchemy relies upon sequences to produce these values. With the
  48. older Oracle versions, *a sequence must always be explicitly specified to
  49. enable autoincrement*. This is divergent with the majority of documentation
  50. examples which assume the usage of an autoincrement-capable database. To
  51. specify sequences, use the sqlalchemy.schema.Sequence object which is passed
  52. to a Column construct::
  53. t = Table('mytable', metadata,
  54. Column('id', Integer, Sequence('id_seq', start=1), primary_key=True),
  55. Column(...), ...
  56. )
  57. This step is also required when using table reflection, i.e. autoload_with=engine::
  58. t = Table('mytable', metadata,
  59. Column('id', Integer, Sequence('id_seq', start=1), primary_key=True),
  60. autoload_with=engine
  61. )
  62. .. versionchanged:: 1.4 Added :class:`_schema.Identity` construct
  63. in a :class:`_schema.Column` to specify the option of an autoincrementing
  64. column.
  65. .. _oracle_isolation_level:
  66. Transaction Isolation Level / Autocommit
  67. ----------------------------------------
  68. The Oracle database supports "READ COMMITTED" and "SERIALIZABLE" modes of
  69. isolation. The AUTOCOMMIT isolation level is also supported by the cx_Oracle
  70. dialect.
  71. To set using per-connection execution options::
  72. connection = engine.connect()
  73. connection = connection.execution_options(
  74. isolation_level="AUTOCOMMIT"
  75. )
  76. For ``READ COMMITTED`` and ``SERIALIZABLE``, the Oracle dialect sets the
  77. level at the session level using ``ALTER SESSION``, which is reverted back
  78. to its default setting when the connection is returned to the connection
  79. pool.
  80. Valid values for ``isolation_level`` include:
  81. * ``READ COMMITTED``
  82. * ``AUTOCOMMIT``
  83. * ``SERIALIZABLE``
  84. .. note:: The implementation for the
  85. :meth:`_engine.Connection.get_isolation_level` method as implemented by the
  86. Oracle dialect necessarily forces the start of a transaction using the
  87. Oracle LOCAL_TRANSACTION_ID function; otherwise no level is normally
  88. readable.
  89. Additionally, the :meth:`_engine.Connection.get_isolation_level` method will
  90. raise an exception if the ``v$transaction`` view is not available due to
  91. permissions or other reasons, which is a common occurrence in Oracle
  92. installations.
  93. The cx_Oracle dialect attempts to call the
  94. :meth:`_engine.Connection.get_isolation_level` method when the dialect makes
  95. its first connection to the database in order to acquire the
  96. "default"isolation level. This default level is necessary so that the level
  97. can be reset on a connection after it has been temporarily modified using
  98. :meth:`_engine.Connection.execution_options` method. In the common event
  99. that the :meth:`_engine.Connection.get_isolation_level` method raises an
  100. exception due to ``v$transaction`` not being readable as well as any other
  101. database-related failure, the level is assumed to be "READ COMMITTED". No
  102. warning is emitted for this initial first-connect condition as it is
  103. expected to be a common restriction on Oracle databases.
  104. .. versionadded:: 1.3.16 added support for AUTOCOMMIT to the cx_oracle dialect
  105. as well as the notion of a default isolation level
  106. .. versionadded:: 1.3.21 Added support for SERIALIZABLE as well as live
  107. reading of the isolation level.
  108. .. versionchanged:: 1.3.22 In the event that the default isolation
  109. level cannot be read due to permissions on the v$transaction view as
  110. is common in Oracle installations, the default isolation level is hardcoded
  111. to "READ COMMITTED" which was the behavior prior to 1.3.21.
  112. .. seealso::
  113. :ref:`dbapi_autocommit`
  114. Identifier Casing
  115. -----------------
  116. In Oracle, the data dictionary represents all case insensitive identifier
  117. names using UPPERCASE text. SQLAlchemy on the other hand considers an
  118. all-lower case identifier name to be case insensitive. The Oracle dialect
  119. converts all case insensitive identifiers to and from those two formats during
  120. schema level communication, such as reflection of tables and indexes. Using
  121. an UPPERCASE name on the SQLAlchemy side indicates a case sensitive
  122. identifier, and SQLAlchemy will quote the name - this will cause mismatches
  123. against data dictionary data received from Oracle, so unless identifier names
  124. have been truly created as case sensitive (i.e. using quoted names), all
  125. lowercase names should be used on the SQLAlchemy side.
  126. .. _oracle_max_identifier_lengths:
  127. Max Identifier Lengths
  128. ----------------------
  129. Oracle has changed the default max identifier length as of Oracle Server
  130. version 12.2. Prior to this version, the length was 30, and for 12.2 and
  131. greater it is now 128. This change impacts SQLAlchemy in the area of
  132. generated SQL label names as well as the generation of constraint names,
  133. particularly in the case where the constraint naming convention feature
  134. described at :ref:`constraint_naming_conventions` is being used.
  135. To assist with this change and others, Oracle includes the concept of a
  136. "compatibility" version, which is a version number that is independent of the
  137. actual server version in order to assist with migration of Oracle databases,
  138. and may be configured within the Oracle server itself. This compatibility
  139. version is retrieved using the query ``SELECT value FROM v$parameter WHERE
  140. name = 'compatible';``. The SQLAlchemy Oracle dialect, when tasked with
  141. determining the default max identifier length, will attempt to use this query
  142. upon first connect in order to determine the effective compatibility version of
  143. the server, which determines what the maximum allowed identifier length is for
  144. the server. If the table is not available, the server version information is
  145. used instead.
  146. As of SQLAlchemy 1.4, the default max identifier length for the Oracle dialect
  147. is 128 characters. Upon first connect, the compatibility version is detected
  148. and if it is less than Oracle version 12.2, the max identifier length is
  149. changed to be 30 characters. In all cases, setting the
  150. :paramref:`_sa.create_engine.max_identifier_length` parameter will bypass this
  151. change and the value given will be used as is::
  152. engine = create_engine(
  153. "oracle+cx_oracle://scott:tiger@oracle122",
  154. max_identifier_length=30)
  155. The maximum identifier length comes into play both when generating anonymized
  156. SQL labels in SELECT statements, but more crucially when generating constraint
  157. names from a naming convention. It is this area that has created the need for
  158. SQLAlchemy to change this default conservatively. For example, the following
  159. naming convention produces two very different constraint names based on the
  160. identifier length::
  161. from sqlalchemy import Column
  162. from sqlalchemy import Index
  163. from sqlalchemy import Integer
  164. from sqlalchemy import MetaData
  165. from sqlalchemy import Table
  166. from sqlalchemy.dialects import oracle
  167. from sqlalchemy.schema import CreateIndex
  168. m = MetaData(naming_convention={"ix": "ix_%(column_0N_name)s"})
  169. t = Table(
  170. "t",
  171. m,
  172. Column("some_column_name_1", Integer),
  173. Column("some_column_name_2", Integer),
  174. Column("some_column_name_3", Integer),
  175. )
  176. ix = Index(
  177. None,
  178. t.c.some_column_name_1,
  179. t.c.some_column_name_2,
  180. t.c.some_column_name_3,
  181. )
  182. oracle_dialect = oracle.dialect(max_identifier_length=30)
  183. print(CreateIndex(ix).compile(dialect=oracle_dialect))
  184. With an identifier length of 30, the above CREATE INDEX looks like::
  185. CREATE INDEX ix_some_column_name_1s_70cd ON t
  186. (some_column_name_1, some_column_name_2, some_column_name_3)
  187. However with length=128, it becomes::
  188. CREATE INDEX ix_some_column_name_1some_column_name_2some_column_name_3 ON t
  189. (some_column_name_1, some_column_name_2, some_column_name_3)
  190. Applications which have run versions of SQLAlchemy prior to 1.4 on an Oracle
  191. server version 12.2 or greater are therefore subject to the scenario of a
  192. database migration that wishes to "DROP CONSTRAINT" on a name that was
  193. previously generated with the shorter length. This migration will fail when
  194. the identifier length is changed without the name of the index or constraint
  195. first being adjusted. Such applications are strongly advised to make use of
  196. :paramref:`_sa.create_engine.max_identifier_length`
  197. in order to maintain control
  198. of the generation of truncated names, and to fully review and test all database
  199. migrations in a staging environment when changing this value to ensure that the
  200. impact of this change has been mitigated.
  201. .. versionchanged:: 1.4 the default max_identifier_length for Oracle is 128
  202. characters, which is adjusted down to 30 upon first connect if an older
  203. version of Oracle server (compatibility version < 12.2) is detected.
  204. LIMIT/OFFSET/FETCH Support
  205. --------------------------
  206. Methods like :meth:`_sql.Select.limit` and :meth:`_sql.Select.offset` make
  207. use of ``FETCH FIRST N ROW / OFFSET N ROWS`` syntax assuming
  208. Oracle 12c or above, and assuming the SELECT statement is not embedded within
  209. a compound statement like UNION. This syntax is also available directly by using
  210. the :meth:`_sql.Select.fetch` method.
  211. .. versionchanged:: 2.0 the Oracle dialect now uses
  212. ``FETCH FIRST N ROW / OFFSET N ROWS`` for all
  213. :meth:`_sql.Select.limit` and :meth:`_sql.Select.offset` usage including
  214. within the ORM and legacy :class:`_orm.Query`. To force the legacy
  215. behavior using window functions, specify the ``enable_offset_fetch=False``
  216. dialect parameter to :func:`_sa.create_engine`.
  217. The use of ``FETCH FIRST / OFFSET`` may be disabled on any Oracle version
  218. by passing ``enable_offset_fetch=False`` to :func:`_sa.create_engine`, which
  219. will force the use of "legacy" mode that makes use of window functions.
  220. This mode is also selected automatically when using a version of Oracle
  221. prior to 12c.
  222. When using legacy mode, or when a :class:`.Select` statement
  223. with limit/offset is embedded in a compound statement, an emulated approach for
  224. LIMIT / OFFSET based on window functions is used, which involves creation of a
  225. subquery using ``ROW_NUMBER`` that is prone to performance issues as well as
  226. SQL construction issues for complex statements. However, this approach is
  227. supported by all Oracle versions. See notes below.
  228. Notes on LIMIT / OFFSET emulation (when fetch() method cannot be used)
  229. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  230. If using :meth:`_sql.Select.limit` and :meth:`_sql.Select.offset`, or with the
  231. ORM the :meth:`_orm.Query.limit` and :meth:`_orm.Query.offset` methods on an
  232. Oracle version prior to 12c, the following notes apply:
  233. * SQLAlchemy currently makes use of ROWNUM to achieve
  234. LIMIT/OFFSET; the exact methodology is taken from
  235. https://blogs.oracle.com/oraclemagazine/on-rownum-and-limiting-results .
  236. * the "FIRST_ROWS()" optimization keyword is not used by default. To enable
  237. the usage of this optimization directive, specify ``optimize_limits=True``
  238. to :func:`_sa.create_engine`.
  239. .. versionchanged:: 1.4
  240. The Oracle dialect renders limit/offset integer values using a "post
  241. compile" scheme which renders the integer directly before passing the
  242. statement to the cursor for execution. The ``use_binds_for_limits`` flag
  243. no longer has an effect.
  244. .. seealso::
  245. :ref:`change_4808`.
  246. .. _oracle_returning:
  247. RETURNING Support
  248. -----------------
  249. The Oracle database supports RETURNING fully for INSERT, UPDATE and DELETE
  250. statements that are invoked with a single collection of bound parameters
  251. (that is, a ``cursor.execute()`` style statement; SQLAlchemy does not generally
  252. support RETURNING with :term:`executemany` statements). Multiple rows may be
  253. returned as well.
  254. .. versionchanged:: 2.0 the Oracle backend has full support for RETURNING
  255. on parity with other backends.
  256. ON UPDATE CASCADE
  257. -----------------
  258. Oracle doesn't have native ON UPDATE CASCADE functionality. A trigger based
  259. solution is available at
  260. https://asktom.oracle.com/tkyte/update_cascade/index.html .
  261. When using the SQLAlchemy ORM, the ORM has limited ability to manually issue
  262. cascading updates - specify ForeignKey objects using the
  263. "deferrable=True, initially='deferred'" keyword arguments,
  264. and specify "passive_updates=False" on each relationship().
  265. Oracle 8 Compatibility
  266. ----------------------
  267. .. warning:: The status of Oracle 8 compatibility is not known for SQLAlchemy
  268. 2.0.
  269. When Oracle 8 is detected, the dialect internally configures itself to the
  270. following behaviors:
  271. * the use_ansi flag is set to False. This has the effect of converting all
  272. JOIN phrases into the WHERE clause, and in the case of LEFT OUTER JOIN
  273. makes use of Oracle's (+) operator.
  274. * the NVARCHAR2 and NCLOB datatypes are no longer generated as DDL when
  275. the :class:`~sqlalchemy.types.Unicode` is used - VARCHAR2 and CLOB are issued
  276. instead. This because these types don't seem to work correctly on Oracle 8
  277. even though they are available. The :class:`~sqlalchemy.types.NVARCHAR` and
  278. :class:`~sqlalchemy.dialects.oracle.NCLOB` types will always generate
  279. NVARCHAR2 and NCLOB.
  280. Synonym/DBLINK Reflection
  281. -------------------------
  282. When using reflection with Table objects, the dialect can optionally search
  283. for tables indicated by synonyms, either in local or remote schemas or
  284. accessed over DBLINK, by passing the flag ``oracle_resolve_synonyms=True`` as
  285. a keyword argument to the :class:`_schema.Table` construct::
  286. some_table = Table('some_table', autoload_with=some_engine,
  287. oracle_resolve_synonyms=True)
  288. When this flag is set, the given name (such as ``some_table`` above) will
  289. be searched not just in the ``ALL_TABLES`` view, but also within the
  290. ``ALL_SYNONYMS`` view to see if this name is actually a synonym to another
  291. name. If the synonym is located and refers to a DBLINK, the oracle dialect
  292. knows how to locate the table's information using DBLINK syntax(e.g.
  293. ``@dblink``).
  294. ``oracle_resolve_synonyms`` is accepted wherever reflection arguments are
  295. accepted, including methods such as :meth:`_schema.MetaData.reflect` and
  296. :meth:`_reflection.Inspector.get_columns`.
  297. If synonyms are not in use, this flag should be left disabled.
  298. .. _oracle_constraint_reflection:
  299. Constraint Reflection
  300. ---------------------
  301. The Oracle dialect can return information about foreign key, unique, and
  302. CHECK constraints, as well as indexes on tables.
  303. Raw information regarding these constraints can be acquired using
  304. :meth:`_reflection.Inspector.get_foreign_keys`,
  305. :meth:`_reflection.Inspector.get_unique_constraints`,
  306. :meth:`_reflection.Inspector.get_check_constraints`, and
  307. :meth:`_reflection.Inspector.get_indexes`.
  308. .. versionchanged:: 1.2 The Oracle dialect can now reflect UNIQUE and
  309. CHECK constraints.
  310. When using reflection at the :class:`_schema.Table` level, the
  311. :class:`_schema.Table`
  312. will also include these constraints.
  313. Note the following caveats:
  314. * When using the :meth:`_reflection.Inspector.get_check_constraints` method,
  315. Oracle
  316. builds a special "IS NOT NULL" constraint for columns that specify
  317. "NOT NULL". This constraint is **not** returned by default; to include
  318. the "IS NOT NULL" constraints, pass the flag ``include_all=True``::
  319. from sqlalchemy import create_engine, inspect
  320. engine = create_engine("oracle+cx_oracle://s:t@dsn")
  321. inspector = inspect(engine)
  322. all_check_constraints = inspector.get_check_constraints(
  323. "some_table", include_all=True)
  324. * in most cases, when reflecting a :class:`_schema.Table`,
  325. a UNIQUE constraint will
  326. **not** be available as a :class:`.UniqueConstraint` object, as Oracle
  327. mirrors unique constraints with a UNIQUE index in most cases (the exception
  328. seems to be when two or more unique constraints represent the same columns);
  329. the :class:`_schema.Table` will instead represent these using
  330. :class:`.Index`
  331. with the ``unique=True`` flag set.
  332. * Oracle creates an implicit index for the primary key of a table; this index
  333. is **excluded** from all index results.
  334. * the list of columns reflected for an index will not include column names
  335. that start with SYS_NC.
  336. Table names with SYSTEM/SYSAUX tablespaces
  337. -------------------------------------------
  338. The :meth:`_reflection.Inspector.get_table_names` and
  339. :meth:`_reflection.Inspector.get_temp_table_names`
  340. methods each return a list of table names for the current engine. These methods
  341. are also part of the reflection which occurs within an operation such as
  342. :meth:`_schema.MetaData.reflect`. By default,
  343. these operations exclude the ``SYSTEM``
  344. and ``SYSAUX`` tablespaces from the operation. In order to change this, the
  345. default list of tablespaces excluded can be changed at the engine level using
  346. the ``exclude_tablespaces`` parameter::
  347. # exclude SYSAUX and SOME_TABLESPACE, but not SYSTEM
  348. e = create_engine(
  349. "oracle+cx_oracle://scott:tiger@xe",
  350. exclude_tablespaces=["SYSAUX", "SOME_TABLESPACE"])
  351. DateTime Compatibility
  352. ----------------------
  353. Oracle has no datatype known as ``DATETIME``, it instead has only ``DATE``,
  354. which can actually store a date and time value. For this reason, the Oracle
  355. dialect provides a type :class:`_oracle.DATE` which is a subclass of
  356. :class:`.DateTime`. This type has no special behavior, and is only
  357. present as a "marker" for this type; additionally, when a database column
  358. is reflected and the type is reported as ``DATE``, the time-supporting
  359. :class:`_oracle.DATE` type is used.
  360. .. _oracle_table_options:
  361. Oracle Table Options
  362. -------------------------
  363. The CREATE TABLE phrase supports the following options with Oracle
  364. in conjunction with the :class:`_schema.Table` construct:
  365. * ``ON COMMIT``::
  366. Table(
  367. "some_table", metadata, ...,
  368. prefixes=['GLOBAL TEMPORARY'], oracle_on_commit='PRESERVE ROWS')
  369. * ``COMPRESS``::
  370. Table('mytable', metadata, Column('data', String(32)),
  371. oracle_compress=True)
  372. Table('mytable', metadata, Column('data', String(32)),
  373. oracle_compress=6)
  374. The ``oracle_compress`` parameter accepts either an integer compression
  375. level, or ``True`` to use the default compression level.
  376. .. _oracle_index_options:
  377. Oracle Specific Index Options
  378. -----------------------------
  379. Bitmap Indexes
  380. ~~~~~~~~~~~~~~
  381. You can specify the ``oracle_bitmap`` parameter to create a bitmap index
  382. instead of a B-tree index::
  383. Index('my_index', my_table.c.data, oracle_bitmap=True)
  384. Bitmap indexes cannot be unique and cannot be compressed. SQLAlchemy will not
  385. check for such limitations, only the database will.
  386. Index compression
  387. ~~~~~~~~~~~~~~~~~
  388. Oracle has a more efficient storage mode for indexes containing lots of
  389. repeated values. Use the ``oracle_compress`` parameter to turn on key
  390. compression::
  391. Index('my_index', my_table.c.data, oracle_compress=True)
  392. Index('my_index', my_table.c.data1, my_table.c.data2, unique=True,
  393. oracle_compress=1)
  394. The ``oracle_compress`` parameter accepts either an integer specifying the
  395. number of prefix columns to compress, or ``True`` to use the default (all
  396. columns for non-unique indexes, all but the last column for unique indexes).
  397. """ # noqa
  398. from __future__ import annotations
  399. from collections import defaultdict
  400. from functools import lru_cache
  401. from functools import wraps
  402. import re
  403. from . import dictionary
  404. from .types import _OracleBoolean
  405. from .types import _OracleDate
  406. from .types import BFILE
  407. from .types import BINARY_DOUBLE
  408. from .types import BINARY_FLOAT
  409. from .types import DATE
  410. from .types import FLOAT
  411. from .types import INTERVAL
  412. from .types import LONG
  413. from .types import NCLOB
  414. from .types import NUMBER
  415. from .types import NVARCHAR2 # noqa
  416. from .types import OracleRaw # noqa
  417. from .types import RAW
  418. from .types import ROWID # noqa
  419. from .types import TIMESTAMP
  420. from .types import VARCHAR2 # noqa
  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 ObjectKind
  428. from ...engine import ObjectScope
  429. from ...engine import reflection
  430. from ...engine.reflection import ReflectionDefaults
  431. from ...sql import and_
  432. from ...sql import bindparam
  433. from ...sql import compiler
  434. from ...sql import expression
  435. from ...sql import func
  436. from ...sql import null
  437. from ...sql import or_
  438. from ...sql import select
  439. from ...sql import sqltypes
  440. from ...sql import util as sql_util
  441. from ...sql import visitors
  442. from ...sql.visitors import InternalTraversal
  443. from ...types import BLOB
  444. from ...types import CHAR
  445. from ...types import CLOB
  446. from ...types import DOUBLE_PRECISION
  447. from ...types import INTEGER
  448. from ...types import NCHAR
  449. from ...types import NVARCHAR
  450. from ...types import REAL
  451. from ...types import VARCHAR
  452. RESERVED_WORDS = set(
  453. "SHARE RAW DROP BETWEEN FROM DESC OPTION PRIOR LONG THEN "
  454. "DEFAULT ALTER IS INTO MINUS INTEGER NUMBER GRANT IDENTIFIED "
  455. "ALL TO ORDER ON FLOAT DATE HAVING CLUSTER NOWAIT RESOURCE "
  456. "ANY TABLE INDEX FOR UPDATE WHERE CHECK SMALLINT WITH DELETE "
  457. "BY ASC REVOKE LIKE SIZE RENAME NOCOMPRESS NULL GROUP VALUES "
  458. "AS IN VIEW EXCLUSIVE COMPRESS SYNONYM SELECT INSERT EXISTS "
  459. "NOT TRIGGER ELSE CREATE INTERSECT PCTFREE DISTINCT USER "
  460. "CONNECT SET MODE OF UNIQUE VARCHAR2 VARCHAR LOCK OR CHAR "
  461. "DECIMAL UNION PUBLIC AND START UID COMMENT CURRENT LEVEL".split()
  462. )
  463. NO_ARG_FNS = set(
  464. "UID CURRENT_DATE SYSDATE USER " "CURRENT_TIME CURRENT_TIMESTAMP".split()
  465. )
  466. colspecs = {
  467. sqltypes.Boolean: _OracleBoolean,
  468. sqltypes.Interval: INTERVAL,
  469. sqltypes.DateTime: DATE,
  470. sqltypes.Date: _OracleDate,
  471. }
  472. ischema_names = {
  473. "VARCHAR2": VARCHAR,
  474. "NVARCHAR2": NVARCHAR,
  475. "CHAR": CHAR,
  476. "NCHAR": NCHAR,
  477. "DATE": DATE,
  478. "NUMBER": NUMBER,
  479. "BLOB": BLOB,
  480. "BFILE": BFILE,
  481. "CLOB": CLOB,
  482. "NCLOB": NCLOB,
  483. "TIMESTAMP": TIMESTAMP,
  484. "TIMESTAMP WITH TIME ZONE": TIMESTAMP,
  485. "TIMESTAMP WITH LOCAL TIME ZONE": TIMESTAMP,
  486. "INTERVAL DAY TO SECOND": INTERVAL,
  487. "RAW": RAW,
  488. "FLOAT": FLOAT,
  489. "DOUBLE PRECISION": DOUBLE_PRECISION,
  490. "REAL": REAL,
  491. "LONG": LONG,
  492. "BINARY_DOUBLE": BINARY_DOUBLE,
  493. "BINARY_FLOAT": BINARY_FLOAT,
  494. "ROWID": ROWID,
  495. }
  496. class OracleTypeCompiler(compiler.GenericTypeCompiler):
  497. # Note:
  498. # Oracle DATE == DATETIME
  499. # Oracle does not allow milliseconds in DATE
  500. # Oracle does not support TIME columns
  501. def visit_datetime(self, type_, **kw):
  502. return self.visit_DATE(type_, **kw)
  503. def visit_float(self, type_, **kw):
  504. return self.visit_FLOAT(type_, **kw)
  505. def visit_double(self, type_, **kw):
  506. return self.visit_DOUBLE_PRECISION(type_, **kw)
  507. def visit_unicode(self, type_, **kw):
  508. if self.dialect._use_nchar_for_unicode:
  509. return self.visit_NVARCHAR2(type_, **kw)
  510. else:
  511. return self.visit_VARCHAR2(type_, **kw)
  512. def visit_INTERVAL(self, type_, **kw):
  513. return "INTERVAL DAY%s TO SECOND%s" % (
  514. type_.day_precision is not None
  515. and "(%d)" % type_.day_precision
  516. or "",
  517. type_.second_precision is not None
  518. and "(%d)" % type_.second_precision
  519. or "",
  520. )
  521. def visit_LONG(self, type_, **kw):
  522. return "LONG"
  523. def visit_TIMESTAMP(self, type_, **kw):
  524. if getattr(type_, "local_timezone", False):
  525. return "TIMESTAMP WITH LOCAL TIME ZONE"
  526. elif type_.timezone:
  527. return "TIMESTAMP WITH TIME ZONE"
  528. else:
  529. return "TIMESTAMP"
  530. def visit_DOUBLE_PRECISION(self, type_, **kw):
  531. return self._generate_numeric(type_, "DOUBLE PRECISION", **kw)
  532. def visit_BINARY_DOUBLE(self, type_, **kw):
  533. return self._generate_numeric(type_, "BINARY_DOUBLE", **kw)
  534. def visit_BINARY_FLOAT(self, type_, **kw):
  535. return self._generate_numeric(type_, "BINARY_FLOAT", **kw)
  536. def visit_FLOAT(self, type_, **kw):
  537. kw["_requires_binary_precision"] = True
  538. return self._generate_numeric(type_, "FLOAT", **kw)
  539. def visit_NUMBER(self, type_, **kw):
  540. return self._generate_numeric(type_, "NUMBER", **kw)
  541. def _generate_numeric(
  542. self,
  543. type_,
  544. name,
  545. precision=None,
  546. scale=None,
  547. _requires_binary_precision=False,
  548. **kw,
  549. ):
  550. if precision is None:
  551. precision = getattr(type_, "precision", None)
  552. if _requires_binary_precision:
  553. binary_precision = getattr(type_, "binary_precision", None)
  554. if precision and binary_precision is None:
  555. # https://www.oracletutorial.com/oracle-basics/oracle-float/
  556. estimated_binary_precision = int(precision / 0.30103)
  557. raise exc.ArgumentError(
  558. "Oracle FLOAT types use 'binary precision', which does "
  559. "not convert cleanly from decimal 'precision'. Please "
  560. "specify "
  561. f"this type with a separate Oracle variant, such as "
  562. f"{type_.__class__.__name__}(precision={precision})."
  563. f"with_variant(oracle.FLOAT"
  564. f"(binary_precision="
  565. f"{estimated_binary_precision}), 'oracle'), so that the "
  566. "Oracle specific 'binary_precision' may be specified "
  567. "accurately."
  568. )
  569. else:
  570. precision = binary_precision
  571. if scale is None:
  572. scale = getattr(type_, "scale", None)
  573. if precision is None:
  574. return name
  575. elif scale is None:
  576. n = "%(name)s(%(precision)s)"
  577. return n % {"name": name, "precision": precision}
  578. else:
  579. n = "%(name)s(%(precision)s, %(scale)s)"
  580. return n % {"name": name, "precision": precision, "scale": scale}
  581. def visit_string(self, type_, **kw):
  582. return self.visit_VARCHAR2(type_, **kw)
  583. def visit_VARCHAR2(self, type_, **kw):
  584. return self._visit_varchar(type_, "", "2")
  585. def visit_NVARCHAR2(self, type_, **kw):
  586. return self._visit_varchar(type_, "N", "2")
  587. visit_NVARCHAR = visit_NVARCHAR2
  588. def visit_VARCHAR(self, type_, **kw):
  589. return self._visit_varchar(type_, "", "")
  590. def _visit_varchar(self, type_, n, num):
  591. if not type_.length:
  592. return "%(n)sVARCHAR%(two)s" % {"two": num, "n": n}
  593. elif not n and self.dialect._supports_char_length:
  594. varchar = "VARCHAR%(two)s(%(length)s CHAR)"
  595. return varchar % {"length": type_.length, "two": num}
  596. else:
  597. varchar = "%(n)sVARCHAR%(two)s(%(length)s)"
  598. return varchar % {"length": type_.length, "two": num, "n": n}
  599. def visit_text(self, type_, **kw):
  600. return self.visit_CLOB(type_, **kw)
  601. def visit_unicode_text(self, type_, **kw):
  602. if self.dialect._use_nchar_for_unicode:
  603. return self.visit_NCLOB(type_, **kw)
  604. else:
  605. return self.visit_CLOB(type_, **kw)
  606. def visit_large_binary(self, type_, **kw):
  607. return self.visit_BLOB(type_, **kw)
  608. def visit_big_integer(self, type_, **kw):
  609. return self.visit_NUMBER(type_, precision=19, **kw)
  610. def visit_boolean(self, type_, **kw):
  611. return self.visit_SMALLINT(type_, **kw)
  612. def visit_RAW(self, type_, **kw):
  613. if type_.length:
  614. return "RAW(%(length)s)" % {"length": type_.length}
  615. else:
  616. return "RAW"
  617. def visit_ROWID(self, type_, **kw):
  618. return "ROWID"
  619. class OracleCompiler(compiler.SQLCompiler):
  620. """Oracle compiler modifies the lexical structure of Select
  621. statements to work under non-ANSI configured Oracle databases, if
  622. the use_ansi flag is False.
  623. """
  624. compound_keywords = util.update_copy(
  625. compiler.SQLCompiler.compound_keywords,
  626. {expression.CompoundSelect.EXCEPT: "MINUS"},
  627. )
  628. def __init__(self, *args, **kwargs):
  629. self.__wheres = {}
  630. super().__init__(*args, **kwargs)
  631. def visit_mod_binary(self, binary, operator, **kw):
  632. return "mod(%s, %s)" % (
  633. self.process(binary.left, **kw),
  634. self.process(binary.right, **kw),
  635. )
  636. def visit_now_func(self, fn, **kw):
  637. return "CURRENT_TIMESTAMP"
  638. def visit_char_length_func(self, fn, **kw):
  639. return "LENGTH" + self.function_argspec(fn, **kw)
  640. def visit_match_op_binary(self, binary, operator, **kw):
  641. return "CONTAINS (%s, %s)" % (
  642. self.process(binary.left),
  643. self.process(binary.right),
  644. )
  645. def visit_true(self, expr, **kw):
  646. return "1"
  647. def visit_false(self, expr, **kw):
  648. return "0"
  649. def get_cte_preamble(self, recursive):
  650. return "WITH"
  651. def get_select_hint_text(self, byfroms):
  652. return " ".join("/*+ %s */" % text for table, text in byfroms.items())
  653. def function_argspec(self, fn, **kw):
  654. if len(fn.clauses) > 0 or fn.name.upper() not in NO_ARG_FNS:
  655. return compiler.SQLCompiler.function_argspec(self, fn, **kw)
  656. else:
  657. return ""
  658. def visit_function(self, func, **kw):
  659. text = super().visit_function(func, **kw)
  660. if kw.get("asfrom", False):
  661. text = "TABLE (%s)" % text
  662. return text
  663. def visit_table_valued_column(self, element, **kw):
  664. text = super().visit_table_valued_column(element, **kw)
  665. text = text + ".COLUMN_VALUE"
  666. return text
  667. def default_from(self):
  668. """Called when a ``SELECT`` statement has no froms,
  669. and no ``FROM`` clause is to be appended.
  670. The Oracle compiler tacks a "FROM DUAL" to the statement.
  671. """
  672. return " FROM DUAL"
  673. def visit_join(self, join, from_linter=None, **kwargs):
  674. if self.dialect.use_ansi:
  675. return compiler.SQLCompiler.visit_join(
  676. self, join, from_linter=from_linter, **kwargs
  677. )
  678. else:
  679. if from_linter:
  680. from_linter.edges.add((join.left, join.right))
  681. kwargs["asfrom"] = True
  682. if isinstance(join.right, expression.FromGrouping):
  683. right = join.right.element
  684. else:
  685. right = join.right
  686. return (
  687. self.process(join.left, from_linter=from_linter, **kwargs)
  688. + ", "
  689. + self.process(right, from_linter=from_linter, **kwargs)
  690. )
  691. def _get_nonansi_join_whereclause(self, froms):
  692. clauses = []
  693. def visit_join(join):
  694. if join.isouter:
  695. # https://docs.oracle.com/database/121/SQLRF/queries006.htm#SQLRF52354
  696. # "apply the outer join operator (+) to all columns of B in
  697. # the join condition in the WHERE clause" - that is,
  698. # unconditionally regardless of operator or the other side
  699. def visit_binary(binary):
  700. if isinstance(
  701. binary.left, expression.ColumnClause
  702. ) and join.right.is_derived_from(binary.left.table):
  703. binary.left = _OuterJoinColumn(binary.left)
  704. elif isinstance(
  705. binary.right, expression.ColumnClause
  706. ) and join.right.is_derived_from(binary.right.table):
  707. binary.right = _OuterJoinColumn(binary.right)
  708. clauses.append(
  709. visitors.cloned_traverse(
  710. join.onclause, {}, {"binary": visit_binary}
  711. )
  712. )
  713. else:
  714. clauses.append(join.onclause)
  715. for j in join.left, join.right:
  716. if isinstance(j, expression.Join):
  717. visit_join(j)
  718. elif isinstance(j, expression.FromGrouping):
  719. visit_join(j.element)
  720. for f in froms:
  721. if isinstance(f, expression.Join):
  722. visit_join(f)
  723. if not clauses:
  724. return None
  725. else:
  726. return sql.and_(*clauses)
  727. def visit_outer_join_column(self, vc, **kw):
  728. return self.process(vc.column, **kw) + "(+)"
  729. def visit_sequence(self, seq, **kw):
  730. return self.preparer.format_sequence(seq) + ".nextval"
  731. def get_render_as_alias_suffix(self, alias_name_text):
  732. """Oracle doesn't like ``FROM table AS alias``"""
  733. return " " + alias_name_text
  734. def returning_clause(
  735. self, stmt, returning_cols, *, populate_result_map, **kw
  736. ):
  737. columns = []
  738. binds = []
  739. for i, column in enumerate(
  740. expression._select_iterables(returning_cols)
  741. ):
  742. if (
  743. self.isupdate
  744. and isinstance(column, sa_schema.Column)
  745. and isinstance(column.server_default, Computed)
  746. and not self.dialect._supports_update_returning_computed_cols
  747. ):
  748. util.warn(
  749. "Computed columns don't work with Oracle UPDATE "
  750. "statements that use RETURNING; the value of the column "
  751. "*before* the UPDATE takes place is returned. It is "
  752. "advised to not use RETURNING with an Oracle computed "
  753. "column. Consider setting implicit_returning to False on "
  754. "the Table object in order to avoid implicit RETURNING "
  755. "clauses from being generated for this Table."
  756. )
  757. if column.type._has_column_expression:
  758. col_expr = column.type.column_expression(column)
  759. else:
  760. col_expr = column
  761. outparam = sql.outparam("ret_%d" % i, type_=column.type)
  762. self.binds[outparam.key] = outparam
  763. binds.append(
  764. self.bindparam_string(self._truncate_bindparam(outparam))
  765. )
  766. # has_out_parameters would in a normal case be set to True
  767. # as a result of the compiler visiting an outparam() object.
  768. # in this case, the above outparam() objects are not being
  769. # visited. Ensure the statement itself didn't have other
  770. # outparam() objects independently.
  771. # technically, this could be supported, but as it would be
  772. # a very strange use case without a clear rationale, disallow it
  773. if self.has_out_parameters:
  774. raise exc.InvalidRequestError(
  775. "Using explicit outparam() objects with "
  776. "UpdateBase.returning() in the same Core DML statement "
  777. "is not supported in the Oracle dialect."
  778. )
  779. self._oracle_returning = True
  780. columns.append(self.process(col_expr, within_columns_clause=False))
  781. if populate_result_map:
  782. self._add_to_result_map(
  783. getattr(col_expr, "name", col_expr._anon_name_label),
  784. getattr(col_expr, "name", col_expr._anon_name_label),
  785. (
  786. column,
  787. getattr(column, "name", None),
  788. getattr(column, "key", None),
  789. ),
  790. column.type,
  791. )
  792. return "RETURNING " + ", ".join(columns) + " INTO " + ", ".join(binds)
  793. def _row_limit_clause(self, select, **kw):
  794. """ORacle 12c supports OFFSET/FETCH operators
  795. Use it instead subquery with row_number
  796. """
  797. if (
  798. select._fetch_clause is not None
  799. or not self.dialect._supports_offset_fetch
  800. ):
  801. return super()._row_limit_clause(
  802. select, use_literal_execute_for_simple_int=True, **kw
  803. )
  804. else:
  805. return self.fetch_clause(
  806. select,
  807. fetch_clause=self._get_limit_or_fetch(select),
  808. use_literal_execute_for_simple_int=True,
  809. **kw,
  810. )
  811. def _get_limit_or_fetch(self, select):
  812. if select._fetch_clause is None:
  813. return select._limit_clause
  814. else:
  815. return select._fetch_clause
  816. def translate_select_structure(self, select_stmt, **kwargs):
  817. select = select_stmt
  818. if not getattr(select, "_oracle_visit", None):
  819. if not self.dialect.use_ansi:
  820. froms = self._display_froms_for_select(
  821. select, kwargs.get("asfrom", False)
  822. )
  823. whereclause = self._get_nonansi_join_whereclause(froms)
  824. if whereclause is not None:
  825. select = select.where(whereclause)
  826. select._oracle_visit = True
  827. # if fetch is used this is not needed
  828. if (
  829. select._has_row_limiting_clause
  830. and not self.dialect._supports_offset_fetch
  831. and select._fetch_clause is None
  832. ):
  833. limit_clause = select._limit_clause
  834. offset_clause = select._offset_clause
  835. if select._simple_int_clause(limit_clause):
  836. limit_clause = limit_clause.render_literal_execute()
  837. if select._simple_int_clause(offset_clause):
  838. offset_clause = offset_clause.render_literal_execute()
  839. # currently using form at:
  840. # https://blogs.oracle.com/oraclemagazine/\
  841. # on-rownum-and-limiting-results
  842. orig_select = select
  843. select = select._generate()
  844. select._oracle_visit = True
  845. # add expressions to accommodate FOR UPDATE OF
  846. for_update = select._for_update_arg
  847. if for_update is not None and for_update.of:
  848. for_update = for_update._clone()
  849. for_update._copy_internals()
  850. for elem in for_update.of:
  851. if not select.selected_columns.contains_column(elem):
  852. select = select.add_columns(elem)
  853. # Wrap the middle select and add the hint
  854. inner_subquery = select.alias()
  855. limitselect = sql.select(
  856. *[
  857. c
  858. for c in inner_subquery.c
  859. if orig_select.selected_columns.corresponding_column(c)
  860. is not None
  861. ]
  862. )
  863. if (
  864. limit_clause is not None
  865. and self.dialect.optimize_limits
  866. and select._simple_int_clause(limit_clause)
  867. ):
  868. limitselect = limitselect.prefix_with(
  869. expression.text(
  870. "/*+ FIRST_ROWS(%s) */"
  871. % self.process(limit_clause, **kwargs)
  872. )
  873. )
  874. limitselect._oracle_visit = True
  875. limitselect._is_wrapper = True
  876. # add expressions to accommodate FOR UPDATE OF
  877. if for_update is not None and for_update.of:
  878. adapter = sql_util.ClauseAdapter(inner_subquery)
  879. for_update.of = [
  880. adapter.traverse(elem) for elem in for_update.of
  881. ]
  882. # If needed, add the limiting clause
  883. if limit_clause is not None:
  884. if select._simple_int_clause(limit_clause) and (
  885. offset_clause is None
  886. or select._simple_int_clause(offset_clause)
  887. ):
  888. max_row = limit_clause
  889. if offset_clause is not None:
  890. max_row = max_row + offset_clause
  891. else:
  892. max_row = limit_clause
  893. if offset_clause is not None:
  894. max_row = max_row + offset_clause
  895. limitselect = limitselect.where(
  896. sql.literal_column("ROWNUM") <= max_row
  897. )
  898. # If needed, add the ora_rn, and wrap again with offset.
  899. if offset_clause is None:
  900. limitselect._for_update_arg = for_update
  901. select = limitselect
  902. else:
  903. limitselect = limitselect.add_columns(
  904. sql.literal_column("ROWNUM").label("ora_rn")
  905. )
  906. limitselect._oracle_visit = True
  907. limitselect._is_wrapper = True
  908. if for_update is not None and for_update.of:
  909. limitselect_cols = limitselect.selected_columns
  910. for elem in for_update.of:
  911. if (
  912. limitselect_cols.corresponding_column(elem)
  913. is None
  914. ):
  915. limitselect = limitselect.add_columns(elem)
  916. limit_subquery = limitselect.alias()
  917. origselect_cols = orig_select.selected_columns
  918. offsetselect = sql.select(
  919. *[
  920. c
  921. for c in limit_subquery.c
  922. if origselect_cols.corresponding_column(c)
  923. is not None
  924. ]
  925. )
  926. offsetselect._oracle_visit = True
  927. offsetselect._is_wrapper = True
  928. if for_update is not None and for_update.of:
  929. adapter = sql_util.ClauseAdapter(limit_subquery)
  930. for_update.of = [
  931. adapter.traverse(elem) for elem in for_update.of
  932. ]
  933. offsetselect = offsetselect.where(
  934. sql.literal_column("ora_rn") > offset_clause
  935. )
  936. offsetselect._for_update_arg = for_update
  937. select = offsetselect
  938. return select
  939. def limit_clause(self, select, **kw):
  940. return ""
  941. def visit_empty_set_expr(self, type_, **kw):
  942. return "SELECT 1 FROM DUAL WHERE 1!=1"
  943. def for_update_clause(self, select, **kw):
  944. if self.is_subquery():
  945. return ""
  946. tmp = " FOR UPDATE"
  947. if select._for_update_arg.of:
  948. tmp += " OF " + ", ".join(
  949. self.process(elem, **kw) for elem in select._for_update_arg.of
  950. )
  951. if select._for_update_arg.nowait:
  952. tmp += " NOWAIT"
  953. if select._for_update_arg.skip_locked:
  954. tmp += " SKIP LOCKED"
  955. return tmp
  956. def visit_is_distinct_from_binary(self, binary, operator, **kw):
  957. return "DECODE(%s, %s, 0, 1) = 1" % (
  958. self.process(binary.left),
  959. self.process(binary.right),
  960. )
  961. def visit_is_not_distinct_from_binary(self, binary, operator, **kw):
  962. return "DECODE(%s, %s, 0, 1) = 0" % (
  963. self.process(binary.left),
  964. self.process(binary.right),
  965. )
  966. def visit_regexp_match_op_binary(self, binary, operator, **kw):
  967. string = self.process(binary.left, **kw)
  968. pattern = self.process(binary.right, **kw)
  969. flags = binary.modifiers["flags"]
  970. if flags is None:
  971. return "REGEXP_LIKE(%s, %s)" % (string, pattern)
  972. else:
  973. return "REGEXP_LIKE(%s, %s, %s)" % (
  974. string,
  975. pattern,
  976. self.render_literal_value(flags, sqltypes.STRINGTYPE),
  977. )
  978. def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
  979. return "NOT %s" % self.visit_regexp_match_op_binary(
  980. binary, operator, **kw
  981. )
  982. def visit_regexp_replace_op_binary(self, binary, operator, **kw):
  983. string = self.process(binary.left, **kw)
  984. pattern_replace = self.process(binary.right, **kw)
  985. flags = binary.modifiers["flags"]
  986. if flags is None:
  987. return "REGEXP_REPLACE(%s, %s)" % (
  988. string,
  989. pattern_replace,
  990. )
  991. else:
  992. return "REGEXP_REPLACE(%s, %s, %s)" % (
  993. string,
  994. pattern_replace,
  995. self.render_literal_value(flags, sqltypes.STRINGTYPE),
  996. )
  997. def visit_aggregate_strings_func(self, fn, **kw):
  998. return "LISTAGG%s" % self.function_argspec(fn, **kw)
  999. class OracleDDLCompiler(compiler.DDLCompiler):
  1000. def define_constraint_cascades(self, constraint):
  1001. text = ""
  1002. if constraint.ondelete is not None:
  1003. text += " ON DELETE %s" % constraint.ondelete
  1004. # oracle has no ON UPDATE CASCADE -
  1005. # its only available via triggers
  1006. # https://asktom.oracle.com/tkyte/update_cascade/index.html
  1007. if constraint.onupdate is not None:
  1008. util.warn(
  1009. "Oracle does not contain native UPDATE CASCADE "
  1010. "functionality - onupdates will not be rendered for foreign "
  1011. "keys. Consider using deferrable=True, initially='deferred' "
  1012. "or triggers."
  1013. )
  1014. return text
  1015. def visit_drop_table_comment(self, drop, **kw):
  1016. return "COMMENT ON TABLE %s IS ''" % self.preparer.format_table(
  1017. drop.element
  1018. )
  1019. def visit_create_index(self, create, **kw):
  1020. index = create.element
  1021. self._verify_index_table(index)
  1022. preparer = self.preparer
  1023. text = "CREATE "
  1024. if index.unique:
  1025. text += "UNIQUE "
  1026. if index.dialect_options["oracle"]["bitmap"]:
  1027. text += "BITMAP "
  1028. text += "INDEX %s ON %s (%s)" % (
  1029. self._prepared_index_name(index, include_schema=True),
  1030. preparer.format_table(index.table, use_schema=True),
  1031. ", ".join(
  1032. self.sql_compiler.process(
  1033. expr, include_table=False, literal_binds=True
  1034. )
  1035. for expr in index.expressions
  1036. ),
  1037. )
  1038. if index.dialect_options["oracle"]["compress"] is not False:
  1039. if index.dialect_options["oracle"]["compress"] is True:
  1040. text += " COMPRESS"
  1041. else:
  1042. text += " COMPRESS %d" % (
  1043. index.dialect_options["oracle"]["compress"]
  1044. )
  1045. return text
  1046. def post_create_table(self, table):
  1047. table_opts = []
  1048. opts = table.dialect_options["oracle"]
  1049. if opts["on_commit"]:
  1050. on_commit_options = opts["on_commit"].replace("_", " ").upper()
  1051. table_opts.append("\n ON COMMIT %s" % on_commit_options)
  1052. if opts["compress"]:
  1053. if opts["compress"] is True:
  1054. table_opts.append("\n COMPRESS")
  1055. else:
  1056. table_opts.append("\n COMPRESS FOR %s" % (opts["compress"]))
  1057. return "".join(table_opts)
  1058. def get_identity_options(self, identity_options):
  1059. text = super().get_identity_options(identity_options)
  1060. text = text.replace("NO MINVALUE", "NOMINVALUE")
  1061. text = text.replace("NO MAXVALUE", "NOMAXVALUE")
  1062. text = text.replace("NO CYCLE", "NOCYCLE")
  1063. if identity_options.order is not None:
  1064. text += " ORDER" if identity_options.order else " NOORDER"
  1065. return text.strip()
  1066. def visit_computed_column(self, generated, **kw):
  1067. text = "GENERATED ALWAYS AS (%s)" % self.sql_compiler.process(
  1068. generated.sqltext, include_table=False, literal_binds=True
  1069. )
  1070. if generated.persisted is True:
  1071. raise exc.CompileError(
  1072. "Oracle computed columns do not support 'stored' persistence; "
  1073. "set the 'persisted' flag to None or False for Oracle support."
  1074. )
  1075. elif generated.persisted is False:
  1076. text += " VIRTUAL"
  1077. return text
  1078. def visit_identity_column(self, identity, **kw):
  1079. if identity.always is None:
  1080. kind = ""
  1081. else:
  1082. kind = "ALWAYS" if identity.always else "BY DEFAULT"
  1083. text = "GENERATED %s" % kind
  1084. if identity.on_null:
  1085. text += " ON NULL"
  1086. text += " AS IDENTITY"
  1087. options = self.get_identity_options(identity)
  1088. if options:
  1089. text += " (%s)" % options
  1090. return text
  1091. class OracleIdentifierPreparer(compiler.IdentifierPreparer):
  1092. reserved_words = {x.lower() for x in RESERVED_WORDS}
  1093. illegal_initial_characters = {str(dig) for dig in range(0, 10)}.union(
  1094. ["_", "$"]
  1095. )
  1096. def _bindparam_requires_quotes(self, value):
  1097. """Return True if the given identifier requires quoting."""
  1098. lc_value = value.lower()
  1099. return (
  1100. lc_value in self.reserved_words
  1101. or value[0] in self.illegal_initial_characters
  1102. or not self.legal_characters.match(str(value))
  1103. )
  1104. def format_savepoint(self, savepoint):
  1105. name = savepoint.ident.lstrip("_")
  1106. return super().format_savepoint(savepoint, name)
  1107. class OracleExecutionContext(default.DefaultExecutionContext):
  1108. def fire_sequence(self, seq, type_):
  1109. return self._execute_scalar(
  1110. "SELECT "
  1111. + self.identifier_preparer.format_sequence(seq)
  1112. + ".nextval FROM DUAL",
  1113. type_,
  1114. )
  1115. def pre_exec(self):
  1116. if self.statement and "_oracle_dblink" in self.execution_options:
  1117. self.statement = self.statement.replace(
  1118. dictionary.DB_LINK_PLACEHOLDER,
  1119. self.execution_options["_oracle_dblink"],
  1120. )
  1121. class OracleDialect(default.DefaultDialect):
  1122. name = "oracle"
  1123. supports_statement_cache = True
  1124. supports_alter = True
  1125. max_identifier_length = 128
  1126. _supports_offset_fetch = True
  1127. insert_returning = True
  1128. update_returning = True
  1129. delete_returning = True
  1130. div_is_floordiv = False
  1131. supports_simple_order_by_label = False
  1132. cte_follows_insert = True
  1133. returns_native_bytes = True
  1134. supports_sequences = True
  1135. sequences_optional = False
  1136. postfetch_lastrowid = False
  1137. default_paramstyle = "named"
  1138. colspecs = colspecs
  1139. ischema_names = ischema_names
  1140. requires_name_normalize = True
  1141. supports_comments = True
  1142. supports_default_values = False
  1143. supports_default_metavalue = True
  1144. supports_empty_insert = False
  1145. supports_identity_columns = True
  1146. statement_compiler = OracleCompiler
  1147. ddl_compiler = OracleDDLCompiler
  1148. type_compiler_cls = OracleTypeCompiler
  1149. preparer = OracleIdentifierPreparer
  1150. execution_ctx_cls = OracleExecutionContext
  1151. reflection_options = ("oracle_resolve_synonyms",)
  1152. _use_nchar_for_unicode = False
  1153. construct_arguments = [
  1154. (
  1155. sa_schema.Table,
  1156. {"resolve_synonyms": False, "on_commit": None, "compress": False},
  1157. ),
  1158. (sa_schema.Index, {"bitmap": False, "compress": False}),
  1159. ]
  1160. @util.deprecated_params(
  1161. use_binds_for_limits=(
  1162. "1.4",
  1163. "The ``use_binds_for_limits`` Oracle dialect parameter is "
  1164. "deprecated. The dialect now renders LIMIT /OFFSET integers "
  1165. "inline in all cases using a post-compilation hook, so that the "
  1166. "value is still represented by a 'bound parameter' on the Core "
  1167. "Expression side.",
  1168. )
  1169. )
  1170. def __init__(
  1171. self,
  1172. use_ansi=True,
  1173. optimize_limits=False,
  1174. use_binds_for_limits=None,
  1175. use_nchar_for_unicode=False,
  1176. exclude_tablespaces=("SYSTEM", "SYSAUX"),
  1177. enable_offset_fetch=True,
  1178. **kwargs,
  1179. ):
  1180. default.DefaultDialect.__init__(self, **kwargs)
  1181. self._use_nchar_for_unicode = use_nchar_for_unicode
  1182. self.use_ansi = use_ansi
  1183. self.optimize_limits = optimize_limits
  1184. self.exclude_tablespaces = exclude_tablespaces
  1185. self.enable_offset_fetch = (
  1186. self._supports_offset_fetch
  1187. ) = enable_offset_fetch
  1188. def initialize(self, connection):
  1189. super().initialize(connection)
  1190. # Oracle 8i has RETURNING:
  1191. # https://docs.oracle.com/cd/A87860_01/doc/index.htm
  1192. # so does Oracle8:
  1193. # https://docs.oracle.com/cd/A64702_01/doc/index.htm
  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. self._supports_offset_fetch = (
  1200. self.enable_offset_fetch and self.server_version_info >= (12,)
  1201. )
  1202. def _get_effective_compat_server_version_info(self, connection):
  1203. # dialect does not need compat levels below 12.2, so don't query
  1204. # in those cases
  1205. if self.server_version_info < (12, 2):
  1206. return self.server_version_info
  1207. try:
  1208. compat = connection.exec_driver_sql(
  1209. "SELECT value FROM v$parameter WHERE name = 'compatible'"
  1210. ).scalar()
  1211. except exc.DBAPIError:
  1212. compat = None
  1213. if compat:
  1214. try:
  1215. return tuple(int(x) for x in compat.split("."))
  1216. except:
  1217. return self.server_version_info
  1218. else:
  1219. return self.server_version_info
  1220. @property
  1221. def _is_oracle_8(self):
  1222. return self.server_version_info and self.server_version_info < (9,)
  1223. @property
  1224. def _supports_table_compression(self):
  1225. return self.server_version_info and self.server_version_info >= (10, 1)
  1226. @property
  1227. def _supports_table_compress_for(self):
  1228. return self.server_version_info and self.server_version_info >= (11,)
  1229. @property
  1230. def _supports_char_length(self):
  1231. return not self._is_oracle_8
  1232. @property
  1233. def _supports_update_returning_computed_cols(self):
  1234. # on version 18 this error is no longet present while it happens on 11
  1235. # it may work also on versions before the 18
  1236. return self.server_version_info and self.server_version_info >= (18,)
  1237. @property
  1238. def _supports_except_all(self):
  1239. return self.server_version_info and self.server_version_info >= (21,)
  1240. def do_release_savepoint(self, connection, name):
  1241. # Oracle does not support RELEASE SAVEPOINT
  1242. pass
  1243. def _check_max_identifier_length(self, connection):
  1244. if self._get_effective_compat_server_version_info(connection) < (
  1245. 12,
  1246. 2,
  1247. ):
  1248. return 30
  1249. else:
  1250. # use the default
  1251. return None
  1252. def get_isolation_level_values(self, dbapi_connection):
  1253. return ["READ COMMITTED", "SERIALIZABLE"]
  1254. def get_default_isolation_level(self, dbapi_conn):
  1255. try:
  1256. return self.get_isolation_level(dbapi_conn)
  1257. except NotImplementedError:
  1258. raise
  1259. except:
  1260. return "READ COMMITTED"
  1261. def _execute_reflection(
  1262. self, connection, query, dblink, returns_long, params=None
  1263. ):
  1264. if dblink and not dblink.startswith("@"):
  1265. dblink = f"@{dblink}"
  1266. execution_options = {
  1267. # handle db links
  1268. "_oracle_dblink": dblink or "",
  1269. # override any schema translate map
  1270. "schema_translate_map": None,
  1271. }
  1272. if dblink and returns_long:
  1273. # Oracle seems to error with
  1274. # "ORA-00997: illegal use of LONG datatype" when returning
  1275. # LONG columns via a dblink in a query with bind params
  1276. # This type seems to be very hard to cast into something else
  1277. # so it seems easier to just use bind param in this case
  1278. def visit_bindparam(bindparam):
  1279. bindparam.literal_execute = True
  1280. query = visitors.cloned_traverse(
  1281. query, {}, {"bindparam": visit_bindparam}
  1282. )
  1283. return connection.execute(
  1284. query, params, execution_options=execution_options
  1285. )
  1286. @util.memoized_property
  1287. def _has_table_query(self):
  1288. # materialized views are returned by all_tables
  1289. tables = (
  1290. select(
  1291. dictionary.all_tables.c.table_name,
  1292. dictionary.all_tables.c.owner,
  1293. )
  1294. .union_all(
  1295. select(
  1296. dictionary.all_views.c.view_name.label("table_name"),
  1297. dictionary.all_views.c.owner,
  1298. )
  1299. )
  1300. .subquery("tables_and_views")
  1301. )
  1302. query = select(tables.c.table_name).where(
  1303. tables.c.table_name == bindparam("table_name"),
  1304. tables.c.owner == bindparam("owner"),
  1305. )
  1306. return query
  1307. @reflection.cache
  1308. def has_table(
  1309. self, connection, table_name, schema=None, dblink=None, **kw
  1310. ):
  1311. """Supported kw arguments are: ``dblink`` to reflect via a db link."""
  1312. self._ensure_has_table_connection(connection)
  1313. if not schema:
  1314. schema = self.default_schema_name
  1315. params = {
  1316. "table_name": self.denormalize_name(table_name),
  1317. "owner": self.denormalize_schema_name(schema),
  1318. }
  1319. cursor = self._execute_reflection(
  1320. connection,
  1321. self._has_table_query,
  1322. dblink,
  1323. returns_long=False,
  1324. params=params,
  1325. )
  1326. return bool(cursor.scalar())
  1327. @reflection.cache
  1328. def has_sequence(
  1329. self, connection, sequence_name, schema=None, dblink=None, **kw
  1330. ):
  1331. """Supported kw arguments are: ``dblink`` to reflect via a db link."""
  1332. if not schema:
  1333. schema = self.default_schema_name
  1334. query = select(dictionary.all_sequences.c.sequence_name).where(
  1335. dictionary.all_sequences.c.sequence_name
  1336. == self.denormalize_schema_name(sequence_name),
  1337. dictionary.all_sequences.c.sequence_owner
  1338. == self.denormalize_schema_name(schema),
  1339. )
  1340. cursor = self._execute_reflection(
  1341. connection, query, dblink, returns_long=False
  1342. )
  1343. return bool(cursor.scalar())
  1344. def _get_default_schema_name(self, connection):
  1345. return self.normalize_name(
  1346. connection.exec_driver_sql(
  1347. "select sys_context( 'userenv', 'current_schema' ) from dual"
  1348. ).scalar()
  1349. )
  1350. def denormalize_schema_name(self, name):
  1351. # look for quoted_name
  1352. force = getattr(name, "quote", None)
  1353. if force is None and name == "public":
  1354. # look for case insensitive, no quoting specified, "public"
  1355. return "PUBLIC"
  1356. return super().denormalize_name(name)
  1357. @reflection.flexi_cache(
  1358. ("schema", InternalTraversal.dp_string),
  1359. ("filter_names", InternalTraversal.dp_string_list),
  1360. ("dblink", InternalTraversal.dp_string),
  1361. )
  1362. def _get_synonyms(self, connection, schema, filter_names, dblink, **kw):
  1363. owner = self.denormalize_schema_name(
  1364. schema or self.default_schema_name
  1365. )
  1366. has_filter_names, params = self._prepare_filter_names(filter_names)
  1367. query = select(
  1368. dictionary.all_synonyms.c.synonym_name,
  1369. dictionary.all_synonyms.c.table_name,
  1370. dictionary.all_synonyms.c.table_owner,
  1371. dictionary.all_synonyms.c.db_link,
  1372. ).where(dictionary.all_synonyms.c.owner == owner)
  1373. if has_filter_names:
  1374. query = query.where(
  1375. dictionary.all_synonyms.c.synonym_name.in_(
  1376. params["filter_names"]
  1377. )
  1378. )
  1379. result = self._execute_reflection(
  1380. connection, query, dblink, returns_long=False
  1381. ).mappings()
  1382. return result.all()
  1383. @lru_cache()
  1384. def _all_objects_query(
  1385. self, owner, scope, kind, has_filter_names, has_mat_views
  1386. ):
  1387. query = (
  1388. select(dictionary.all_objects.c.object_name)
  1389. .select_from(dictionary.all_objects)
  1390. .where(dictionary.all_objects.c.owner == owner)
  1391. )
  1392. # NOTE: materialized views are listed in all_objects twice;
  1393. # once as MATERIALIZE VIEW and once as TABLE
  1394. if kind is ObjectKind.ANY:
  1395. # materilaized view are listed also as tables so there is no
  1396. # need to add them to the in_.
  1397. query = query.where(
  1398. dictionary.all_objects.c.object_type.in_(("TABLE", "VIEW"))
  1399. )
  1400. else:
  1401. object_type = []
  1402. if ObjectKind.VIEW in kind:
  1403. object_type.append("VIEW")
  1404. if (
  1405. ObjectKind.MATERIALIZED_VIEW in kind
  1406. and ObjectKind.TABLE not in kind
  1407. ):
  1408. # materilaized view are listed also as tables so there is no
  1409. # need to add them to the in_ if also selecting tables.
  1410. object_type.append("MATERIALIZED VIEW")
  1411. if ObjectKind.TABLE in kind:
  1412. object_type.append("TABLE")
  1413. if has_mat_views and ObjectKind.MATERIALIZED_VIEW not in kind:
  1414. # materialized view are listed also as tables,
  1415. # so they need to be filtered out
  1416. # EXCEPT ALL / MINUS profiles as faster than using
  1417. # NOT EXISTS or NOT IN with a subquery, but it's in
  1418. # general faster to get the mat view names and exclude
  1419. # them only when needed
  1420. query = query.where(
  1421. dictionary.all_objects.c.object_name.not_in(
  1422. bindparam("mat_views")
  1423. )
  1424. )
  1425. query = query.where(
  1426. dictionary.all_objects.c.object_type.in_(object_type)
  1427. )
  1428. # handles scope
  1429. if scope is ObjectScope.DEFAULT:
  1430. query = query.where(dictionary.all_objects.c.temporary == "N")
  1431. elif scope is ObjectScope.TEMPORARY:
  1432. query = query.where(dictionary.all_objects.c.temporary == "Y")
  1433. if has_filter_names:
  1434. query = query.where(
  1435. dictionary.all_objects.c.object_name.in_(
  1436. bindparam("filter_names")
  1437. )
  1438. )
  1439. return query
  1440. @reflection.flexi_cache(
  1441. ("schema", InternalTraversal.dp_string),
  1442. ("scope", InternalTraversal.dp_plain_obj),
  1443. ("kind", InternalTraversal.dp_plain_obj),
  1444. ("filter_names", InternalTraversal.dp_string_list),
  1445. ("dblink", InternalTraversal.dp_string),
  1446. )
  1447. def _get_all_objects(
  1448. self, connection, schema, scope, kind, filter_names, dblink, **kw
  1449. ):
  1450. owner = self.denormalize_schema_name(
  1451. schema or self.default_schema_name
  1452. )
  1453. has_filter_names, params = self._prepare_filter_names(filter_names)
  1454. has_mat_views = False
  1455. if (
  1456. ObjectKind.TABLE in kind
  1457. and ObjectKind.MATERIALIZED_VIEW not in kind
  1458. ):
  1459. # see note in _all_objects_query
  1460. mat_views = self.get_materialized_view_names(
  1461. connection, schema, dblink, _normalize=False, **kw
  1462. )
  1463. if mat_views:
  1464. params["mat_views"] = mat_views
  1465. has_mat_views = True
  1466. query = self._all_objects_query(
  1467. owner, scope, kind, has_filter_names, has_mat_views
  1468. )
  1469. result = self._execute_reflection(
  1470. connection, query, dblink, returns_long=False, params=params
  1471. ).scalars()
  1472. return result.all()
  1473. def _handle_synonyms_decorator(fn):
  1474. @wraps(fn)
  1475. def wrapper(self, *args, **kwargs):
  1476. return self._handle_synonyms(fn, *args, **kwargs)
  1477. return wrapper
  1478. def _handle_synonyms(self, fn, connection, *args, **kwargs):
  1479. if not kwargs.get("oracle_resolve_synonyms", False):
  1480. return fn(self, connection, *args, **kwargs)
  1481. original_kw = kwargs.copy()
  1482. schema = kwargs.pop("schema", None)
  1483. result = self._get_synonyms(
  1484. connection,
  1485. schema=schema,
  1486. filter_names=kwargs.pop("filter_names", None),
  1487. dblink=kwargs.pop("dblink", None),
  1488. info_cache=kwargs.get("info_cache", None),
  1489. )
  1490. dblinks_owners = defaultdict(dict)
  1491. for row in result:
  1492. key = row["db_link"], row["table_owner"]
  1493. tn = self.normalize_name(row["table_name"])
  1494. dblinks_owners[key][tn] = row["synonym_name"]
  1495. if not dblinks_owners:
  1496. # No synonym, do the plain thing
  1497. return fn(self, connection, *args, **original_kw)
  1498. data = {}
  1499. for (dblink, table_owner), mapping in dblinks_owners.items():
  1500. call_kw = {
  1501. **original_kw,
  1502. "schema": table_owner,
  1503. "dblink": self.normalize_name(dblink),
  1504. "filter_names": mapping.keys(),
  1505. }
  1506. call_result = fn(self, connection, *args, **call_kw)
  1507. for (_, tn), value in call_result:
  1508. synonym_name = self.normalize_name(mapping[tn])
  1509. data[(schema, synonym_name)] = value
  1510. return data.items()
  1511. @reflection.cache
  1512. def get_schema_names(self, connection, dblink=None, **kw):
  1513. """Supported kw arguments are: ``dblink`` to reflect via a db link."""
  1514. query = select(dictionary.all_users.c.username).order_by(
  1515. dictionary.all_users.c.username
  1516. )
  1517. result = self._execute_reflection(
  1518. connection, query, dblink, returns_long=False
  1519. ).scalars()
  1520. return [self.normalize_name(row) for row in result]
  1521. @reflection.cache
  1522. def get_table_names(self, connection, schema=None, dblink=None, **kw):
  1523. """Supported kw arguments are: ``dblink`` to reflect via a db link."""
  1524. # note that table_names() isn't loading DBLINKed or synonym'ed tables
  1525. if schema is None:
  1526. schema = self.default_schema_name
  1527. den_schema = self.denormalize_schema_name(schema)
  1528. if kw.get("oracle_resolve_synonyms", False):
  1529. tables = (
  1530. select(
  1531. dictionary.all_tables.c.table_name,
  1532. dictionary.all_tables.c.owner,
  1533. dictionary.all_tables.c.iot_name,
  1534. dictionary.all_tables.c.duration,
  1535. dictionary.all_tables.c.tablespace_name,
  1536. )
  1537. .union_all(
  1538. select(
  1539. dictionary.all_synonyms.c.synonym_name.label(
  1540. "table_name"
  1541. ),
  1542. dictionary.all_synonyms.c.owner,
  1543. dictionary.all_tables.c.iot_name,
  1544. dictionary.all_tables.c.duration,
  1545. dictionary.all_tables.c.tablespace_name,
  1546. )
  1547. .select_from(dictionary.all_tables)
  1548. .join(
  1549. dictionary.all_synonyms,
  1550. and_(
  1551. dictionary.all_tables.c.table_name
  1552. == dictionary.all_synonyms.c.table_name,
  1553. dictionary.all_tables.c.owner
  1554. == func.coalesce(
  1555. dictionary.all_synonyms.c.table_owner,
  1556. dictionary.all_synonyms.c.owner,
  1557. ),
  1558. ),
  1559. )
  1560. )
  1561. .subquery("available_tables")
  1562. )
  1563. else:
  1564. tables = dictionary.all_tables
  1565. query = select(tables.c.table_name)
  1566. if self.exclude_tablespaces:
  1567. query = query.where(
  1568. func.coalesce(
  1569. tables.c.tablespace_name, "no tablespace"
  1570. ).not_in(self.exclude_tablespaces)
  1571. )
  1572. query = query.where(
  1573. tables.c.owner == den_schema,
  1574. tables.c.iot_name.is_(null()),
  1575. tables.c.duration.is_(null()),
  1576. )
  1577. # remove materialized views
  1578. mat_query = select(
  1579. dictionary.all_mviews.c.mview_name.label("table_name")
  1580. ).where(dictionary.all_mviews.c.owner == den_schema)
  1581. query = (
  1582. query.except_all(mat_query)
  1583. if self._supports_except_all
  1584. else query.except_(mat_query)
  1585. )
  1586. result = self._execute_reflection(
  1587. connection, query, dblink, returns_long=False
  1588. ).scalars()
  1589. return [self.normalize_name(row) for row in result]
  1590. @reflection.cache
  1591. def get_temp_table_names(self, connection, dblink=None, **kw):
  1592. """Supported kw arguments are: ``dblink`` to reflect via a db link."""
  1593. schema = self.denormalize_schema_name(self.default_schema_name)
  1594. query = select(dictionary.all_tables.c.table_name)
  1595. if self.exclude_tablespaces:
  1596. query = query.where(
  1597. func.coalesce(
  1598. dictionary.all_tables.c.tablespace_name, "no tablespace"
  1599. ).not_in(self.exclude_tablespaces)
  1600. )
  1601. query = query.where(
  1602. dictionary.all_tables.c.owner == schema,
  1603. dictionary.all_tables.c.iot_name.is_(null()),
  1604. dictionary.all_tables.c.duration.is_not(null()),
  1605. )
  1606. result = self._execute_reflection(
  1607. connection, query, dblink, returns_long=False
  1608. ).scalars()
  1609. return [self.normalize_name(row) for row in result]
  1610. @reflection.cache
  1611. def get_materialized_view_names(
  1612. self, connection, schema=None, dblink=None, _normalize=True, **kw
  1613. ):
  1614. """Supported kw arguments are: ``dblink`` to reflect via a db link."""
  1615. if not schema:
  1616. schema = self.default_schema_name
  1617. query = select(dictionary.all_mviews.c.mview_name).where(
  1618. dictionary.all_mviews.c.owner
  1619. == self.denormalize_schema_name(schema)
  1620. )
  1621. result = self._execute_reflection(
  1622. connection, query, dblink, returns_long=False
  1623. ).scalars()
  1624. if _normalize:
  1625. return [self.normalize_name(row) for row in result]
  1626. else:
  1627. return result.all()
  1628. @reflection.cache
  1629. def get_view_names(self, connection, schema=None, dblink=None, **kw):
  1630. """Supported kw arguments are: ``dblink`` to reflect via a db link."""
  1631. if not schema:
  1632. schema = self.default_schema_name
  1633. query = select(dictionary.all_views.c.view_name).where(
  1634. dictionary.all_views.c.owner
  1635. == self.denormalize_schema_name(schema)
  1636. )
  1637. result = self._execute_reflection(
  1638. connection, query, dblink, returns_long=False
  1639. ).scalars()
  1640. return [self.normalize_name(row) for row in result]
  1641. @reflection.cache
  1642. def get_sequence_names(self, connection, schema=None, dblink=None, **kw):
  1643. """Supported kw arguments are: ``dblink`` to reflect via a db link."""
  1644. if not schema:
  1645. schema = self.default_schema_name
  1646. query = select(dictionary.all_sequences.c.sequence_name).where(
  1647. dictionary.all_sequences.c.sequence_owner
  1648. == self.denormalize_schema_name(schema)
  1649. )
  1650. result = self._execute_reflection(
  1651. connection, query, dblink, returns_long=False
  1652. ).scalars()
  1653. return [self.normalize_name(row) for row in result]
  1654. def _value_or_raise(self, data, table, schema):
  1655. table = self.normalize_name(str(table))
  1656. try:
  1657. return dict(data)[(schema, table)]
  1658. except KeyError:
  1659. raise exc.NoSuchTableError(
  1660. f"{schema}.{table}" if schema else table
  1661. ) from None
  1662. def _prepare_filter_names(self, filter_names):
  1663. if filter_names:
  1664. fn = [self.denormalize_name(name) for name in filter_names]
  1665. return True, {"filter_names": fn}
  1666. else:
  1667. return False, {}
  1668. @reflection.cache
  1669. def get_table_options(self, connection, table_name, schema=None, **kw):
  1670. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  1671. ``oracle_resolve_synonyms`` to resolve names to synonyms
  1672. """
  1673. data = self.get_multi_table_options(
  1674. connection,
  1675. schema=schema,
  1676. filter_names=[table_name],
  1677. scope=ObjectScope.ANY,
  1678. kind=ObjectKind.ANY,
  1679. **kw,
  1680. )
  1681. return self._value_or_raise(data, table_name, schema)
  1682. @lru_cache()
  1683. def _table_options_query(
  1684. self, owner, scope, kind, has_filter_names, has_mat_views
  1685. ):
  1686. query = select(
  1687. dictionary.all_tables.c.table_name,
  1688. dictionary.all_tables.c.compression,
  1689. dictionary.all_tables.c.compress_for,
  1690. ).where(dictionary.all_tables.c.owner == owner)
  1691. if has_filter_names:
  1692. query = query.where(
  1693. dictionary.all_tables.c.table_name.in_(
  1694. bindparam("filter_names")
  1695. )
  1696. )
  1697. if scope is ObjectScope.DEFAULT:
  1698. query = query.where(dictionary.all_tables.c.duration.is_(null()))
  1699. elif scope is ObjectScope.TEMPORARY:
  1700. query = query.where(
  1701. dictionary.all_tables.c.duration.is_not(null())
  1702. )
  1703. if (
  1704. has_mat_views
  1705. and ObjectKind.TABLE in kind
  1706. and ObjectKind.MATERIALIZED_VIEW not in kind
  1707. ):
  1708. # cant use EXCEPT ALL / MINUS here because we don't have an
  1709. # excludable row vs. the query above
  1710. # outerjoin + where null works better on oracle 21 but 11 does
  1711. # not like it at all. this is the next best thing
  1712. query = query.where(
  1713. dictionary.all_tables.c.table_name.not_in(
  1714. bindparam("mat_views")
  1715. )
  1716. )
  1717. elif (
  1718. ObjectKind.TABLE not in kind
  1719. and ObjectKind.MATERIALIZED_VIEW in kind
  1720. ):
  1721. query = query.where(
  1722. dictionary.all_tables.c.table_name.in_(bindparam("mat_views"))
  1723. )
  1724. return query
  1725. @_handle_synonyms_decorator
  1726. def get_multi_table_options(
  1727. self,
  1728. connection,
  1729. *,
  1730. schema,
  1731. filter_names,
  1732. scope,
  1733. kind,
  1734. dblink=None,
  1735. **kw,
  1736. ):
  1737. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  1738. ``oracle_resolve_synonyms`` to resolve names to synonyms
  1739. """
  1740. owner = self.denormalize_schema_name(
  1741. schema or self.default_schema_name
  1742. )
  1743. has_filter_names, params = self._prepare_filter_names(filter_names)
  1744. has_mat_views = False
  1745. if (
  1746. ObjectKind.TABLE in kind
  1747. and ObjectKind.MATERIALIZED_VIEW not in kind
  1748. ):
  1749. # see note in _table_options_query
  1750. mat_views = self.get_materialized_view_names(
  1751. connection, schema, dblink, _normalize=False, **kw
  1752. )
  1753. if mat_views:
  1754. params["mat_views"] = mat_views
  1755. has_mat_views = True
  1756. elif (
  1757. ObjectKind.TABLE not in kind
  1758. and ObjectKind.MATERIALIZED_VIEW in kind
  1759. ):
  1760. mat_views = self.get_materialized_view_names(
  1761. connection, schema, dblink, _normalize=False, **kw
  1762. )
  1763. params["mat_views"] = mat_views
  1764. options = {}
  1765. default = ReflectionDefaults.table_options
  1766. if ObjectKind.TABLE in kind or ObjectKind.MATERIALIZED_VIEW in kind:
  1767. query = self._table_options_query(
  1768. owner, scope, kind, has_filter_names, has_mat_views
  1769. )
  1770. result = self._execute_reflection(
  1771. connection, query, dblink, returns_long=False, params=params
  1772. )
  1773. for table, compression, compress_for in result:
  1774. if compression == "ENABLED":
  1775. data = {"oracle_compress": compress_for}
  1776. else:
  1777. data = default()
  1778. options[(schema, self.normalize_name(table))] = data
  1779. if ObjectKind.VIEW in kind and ObjectScope.DEFAULT in scope:
  1780. # add the views (no temporary views)
  1781. for view in self.get_view_names(connection, schema, dblink, **kw):
  1782. if not filter_names or view in filter_names:
  1783. options[(schema, view)] = default()
  1784. return options.items()
  1785. @reflection.cache
  1786. def get_columns(self, connection, table_name, schema=None, **kw):
  1787. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  1788. ``oracle_resolve_synonyms`` to resolve names to synonyms
  1789. """
  1790. data = self.get_multi_columns(
  1791. connection,
  1792. schema=schema,
  1793. filter_names=[table_name],
  1794. scope=ObjectScope.ANY,
  1795. kind=ObjectKind.ANY,
  1796. **kw,
  1797. )
  1798. return self._value_or_raise(data, table_name, schema)
  1799. def _run_batches(
  1800. self, connection, query, dblink, returns_long, mappings, all_objects
  1801. ):
  1802. each_batch = 500
  1803. batches = list(all_objects)
  1804. while batches:
  1805. batch = batches[0:each_batch]
  1806. batches[0:each_batch] = []
  1807. result = self._execute_reflection(
  1808. connection,
  1809. query,
  1810. dblink,
  1811. returns_long=returns_long,
  1812. params={"all_objects": batch},
  1813. )
  1814. if mappings:
  1815. yield from result.mappings()
  1816. else:
  1817. yield from result
  1818. @lru_cache()
  1819. def _column_query(self, owner):
  1820. all_cols = dictionary.all_tab_cols
  1821. all_comments = dictionary.all_col_comments
  1822. all_ids = dictionary.all_tab_identity_cols
  1823. if self.server_version_info >= (12,):
  1824. add_cols = (
  1825. all_cols.c.default_on_null,
  1826. sql.case(
  1827. (all_ids.c.table_name.is_(None), sql.null()),
  1828. else_=all_ids.c.generation_type
  1829. + ","
  1830. + all_ids.c.identity_options,
  1831. ).label("identity_options"),
  1832. )
  1833. join_identity_cols = True
  1834. else:
  1835. add_cols = (
  1836. sql.null().label("default_on_null"),
  1837. sql.null().label("identity_options"),
  1838. )
  1839. join_identity_cols = False
  1840. # NOTE: on oracle cannot create tables/views without columns and
  1841. # a table cannot have all column hidden:
  1842. # ORA-54039: table must have at least one column that is not invisible
  1843. # all_tab_cols returns data for tables/views/mat-views.
  1844. # all_tab_cols does not return recycled tables
  1845. query = (
  1846. select(
  1847. all_cols.c.table_name,
  1848. all_cols.c.column_name,
  1849. all_cols.c.data_type,
  1850. all_cols.c.char_length,
  1851. all_cols.c.data_precision,
  1852. all_cols.c.data_scale,
  1853. all_cols.c.nullable,
  1854. all_cols.c.data_default,
  1855. all_comments.c.comments,
  1856. all_cols.c.virtual_column,
  1857. *add_cols,
  1858. ).select_from(all_cols)
  1859. # NOTE: all_col_comments has a row for each column even if no
  1860. # comment is present, so a join could be performed, but there
  1861. # seems to be no difference compared to an outer join
  1862. .outerjoin(
  1863. all_comments,
  1864. and_(
  1865. all_cols.c.table_name == all_comments.c.table_name,
  1866. all_cols.c.column_name == all_comments.c.column_name,
  1867. all_cols.c.owner == all_comments.c.owner,
  1868. ),
  1869. )
  1870. )
  1871. if join_identity_cols:
  1872. query = query.outerjoin(
  1873. all_ids,
  1874. and_(
  1875. all_cols.c.table_name == all_ids.c.table_name,
  1876. all_cols.c.column_name == all_ids.c.column_name,
  1877. all_cols.c.owner == all_ids.c.owner,
  1878. ),
  1879. )
  1880. query = query.where(
  1881. all_cols.c.table_name.in_(bindparam("all_objects")),
  1882. all_cols.c.hidden_column == "NO",
  1883. all_cols.c.owner == owner,
  1884. ).order_by(all_cols.c.table_name, all_cols.c.column_id)
  1885. return query
  1886. @_handle_synonyms_decorator
  1887. def get_multi_columns(
  1888. self,
  1889. connection,
  1890. *,
  1891. schema,
  1892. filter_names,
  1893. scope,
  1894. kind,
  1895. dblink=None,
  1896. **kw,
  1897. ):
  1898. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  1899. ``oracle_resolve_synonyms`` to resolve names to synonyms
  1900. """
  1901. owner = self.denormalize_schema_name(
  1902. schema or self.default_schema_name
  1903. )
  1904. query = self._column_query(owner)
  1905. if (
  1906. filter_names
  1907. and kind is ObjectKind.ANY
  1908. and scope is ObjectScope.ANY
  1909. ):
  1910. all_objects = [self.denormalize_name(n) for n in filter_names]
  1911. else:
  1912. all_objects = self._get_all_objects(
  1913. connection, schema, scope, kind, filter_names, dblink, **kw
  1914. )
  1915. columns = defaultdict(list)
  1916. # all_tab_cols.data_default is LONG
  1917. result = self._run_batches(
  1918. connection,
  1919. query,
  1920. dblink,
  1921. returns_long=True,
  1922. mappings=True,
  1923. all_objects=all_objects,
  1924. )
  1925. def maybe_int(value):
  1926. if isinstance(value, float) and value.is_integer():
  1927. return int(value)
  1928. else:
  1929. return value
  1930. remove_size = re.compile(r"\(\d+\)")
  1931. for row_dict in result:
  1932. table_name = self.normalize_name(row_dict["table_name"])
  1933. orig_colname = row_dict["column_name"]
  1934. colname = self.normalize_name(orig_colname)
  1935. coltype = row_dict["data_type"]
  1936. precision = maybe_int(row_dict["data_precision"])
  1937. if coltype == "NUMBER":
  1938. scale = maybe_int(row_dict["data_scale"])
  1939. if precision is None and scale == 0:
  1940. coltype = INTEGER()
  1941. else:
  1942. coltype = NUMBER(precision, scale)
  1943. elif coltype == "FLOAT":
  1944. # https://docs.oracle.com/cd/B14117_01/server.101/b10758/sqlqr06.htm
  1945. if precision == 126:
  1946. # The DOUBLE PRECISION datatype is a floating-point
  1947. # number with binary precision 126.
  1948. coltype = DOUBLE_PRECISION()
  1949. elif precision == 63:
  1950. # The REAL datatype is a floating-point number with a
  1951. # binary precision of 63, or 18 decimal.
  1952. coltype = REAL()
  1953. else:
  1954. # non standard precision
  1955. coltype = FLOAT(binary_precision=precision)
  1956. elif coltype in ("VARCHAR2", "NVARCHAR2", "CHAR", "NCHAR"):
  1957. char_length = maybe_int(row_dict["char_length"])
  1958. coltype = self.ischema_names.get(coltype)(char_length)
  1959. elif "WITH TIME ZONE" in coltype:
  1960. coltype = TIMESTAMP(timezone=True)
  1961. elif "WITH LOCAL TIME ZONE" in coltype:
  1962. coltype = TIMESTAMP(local_timezone=True)
  1963. else:
  1964. coltype = re.sub(remove_size, "", coltype)
  1965. try:
  1966. coltype = self.ischema_names[coltype]
  1967. except KeyError:
  1968. util.warn(
  1969. "Did not recognize type '%s' of column '%s'"
  1970. % (coltype, colname)
  1971. )
  1972. coltype = sqltypes.NULLTYPE
  1973. default = row_dict["data_default"]
  1974. if row_dict["virtual_column"] == "YES":
  1975. computed = dict(sqltext=default)
  1976. default = None
  1977. else:
  1978. computed = None
  1979. identity_options = row_dict["identity_options"]
  1980. if identity_options is not None:
  1981. identity = self._parse_identity_options(
  1982. identity_options, row_dict["default_on_null"]
  1983. )
  1984. default = None
  1985. else:
  1986. identity = None
  1987. cdict = {
  1988. "name": colname,
  1989. "type": coltype,
  1990. "nullable": row_dict["nullable"] == "Y",
  1991. "default": default,
  1992. "comment": row_dict["comments"],
  1993. }
  1994. if orig_colname.lower() == orig_colname:
  1995. cdict["quote"] = True
  1996. if computed is not None:
  1997. cdict["computed"] = computed
  1998. if identity is not None:
  1999. cdict["identity"] = identity
  2000. columns[(schema, table_name)].append(cdict)
  2001. # NOTE: default not needed since all tables have columns
  2002. # default = ReflectionDefaults.columns
  2003. # return (
  2004. # (key, value if value else default())
  2005. # for key, value in columns.items()
  2006. # )
  2007. return columns.items()
  2008. def _parse_identity_options(self, identity_options, default_on_null):
  2009. # identity_options is a string that starts with 'ALWAYS,' or
  2010. # 'BY DEFAULT,' and continues with
  2011. # START WITH: 1, INCREMENT BY: 1, MAX_VALUE: 123, MIN_VALUE: 1,
  2012. # CYCLE_FLAG: N, CACHE_SIZE: 1, ORDER_FLAG: N, SCALE_FLAG: N,
  2013. # EXTEND_FLAG: N, SESSION_FLAG: N, KEEP_VALUE: N
  2014. parts = [p.strip() for p in identity_options.split(",")]
  2015. identity = {
  2016. "always": parts[0] == "ALWAYS",
  2017. "on_null": default_on_null == "YES",
  2018. }
  2019. for part in parts[1:]:
  2020. option, value = part.split(":")
  2021. value = value.strip()
  2022. if "START WITH" in option:
  2023. identity["start"] = int(value)
  2024. elif "INCREMENT BY" in option:
  2025. identity["increment"] = int(value)
  2026. elif "MAX_VALUE" in option:
  2027. identity["maxvalue"] = int(value)
  2028. elif "MIN_VALUE" in option:
  2029. identity["minvalue"] = int(value)
  2030. elif "CYCLE_FLAG" in option:
  2031. identity["cycle"] = value == "Y"
  2032. elif "CACHE_SIZE" in option:
  2033. identity["cache"] = int(value)
  2034. elif "ORDER_FLAG" in option:
  2035. identity["order"] = value == "Y"
  2036. return identity
  2037. @reflection.cache
  2038. def get_table_comment(self, connection, table_name, schema=None, **kw):
  2039. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2040. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2041. """
  2042. data = self.get_multi_table_comment(
  2043. connection,
  2044. schema=schema,
  2045. filter_names=[table_name],
  2046. scope=ObjectScope.ANY,
  2047. kind=ObjectKind.ANY,
  2048. **kw,
  2049. )
  2050. return self._value_or_raise(data, table_name, schema)
  2051. @lru_cache()
  2052. def _comment_query(self, owner, scope, kind, has_filter_names):
  2053. # NOTE: all_tab_comments / all_mview_comments have a row for all
  2054. # object even if they don't have comments
  2055. queries = []
  2056. if ObjectKind.TABLE in kind or ObjectKind.VIEW in kind:
  2057. # all_tab_comments returns also plain views
  2058. tbl_view = select(
  2059. dictionary.all_tab_comments.c.table_name,
  2060. dictionary.all_tab_comments.c.comments,
  2061. ).where(
  2062. dictionary.all_tab_comments.c.owner == owner,
  2063. dictionary.all_tab_comments.c.table_name.not_like("BIN$%"),
  2064. )
  2065. if ObjectKind.VIEW not in kind:
  2066. tbl_view = tbl_view.where(
  2067. dictionary.all_tab_comments.c.table_type == "TABLE"
  2068. )
  2069. elif ObjectKind.TABLE not in kind:
  2070. tbl_view = tbl_view.where(
  2071. dictionary.all_tab_comments.c.table_type == "VIEW"
  2072. )
  2073. queries.append(tbl_view)
  2074. if ObjectKind.MATERIALIZED_VIEW in kind:
  2075. mat_view = select(
  2076. dictionary.all_mview_comments.c.mview_name.label("table_name"),
  2077. dictionary.all_mview_comments.c.comments,
  2078. ).where(
  2079. dictionary.all_mview_comments.c.owner == owner,
  2080. dictionary.all_mview_comments.c.mview_name.not_like("BIN$%"),
  2081. )
  2082. queries.append(mat_view)
  2083. if len(queries) == 1:
  2084. query = queries[0]
  2085. else:
  2086. union = sql.union_all(*queries).subquery("tables_and_views")
  2087. query = select(union.c.table_name, union.c.comments)
  2088. name_col = query.selected_columns.table_name
  2089. if scope in (ObjectScope.DEFAULT, ObjectScope.TEMPORARY):
  2090. temp = "Y" if scope is ObjectScope.TEMPORARY else "N"
  2091. # need distinct since materialized view are listed also
  2092. # as tables in all_objects
  2093. query = query.distinct().join(
  2094. dictionary.all_objects,
  2095. and_(
  2096. dictionary.all_objects.c.owner == owner,
  2097. dictionary.all_objects.c.object_name == name_col,
  2098. dictionary.all_objects.c.temporary == temp,
  2099. ),
  2100. )
  2101. if has_filter_names:
  2102. query = query.where(name_col.in_(bindparam("filter_names")))
  2103. return query
  2104. @_handle_synonyms_decorator
  2105. def get_multi_table_comment(
  2106. self,
  2107. connection,
  2108. *,
  2109. schema,
  2110. filter_names,
  2111. scope,
  2112. kind,
  2113. dblink=None,
  2114. **kw,
  2115. ):
  2116. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2117. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2118. """
  2119. owner = self.denormalize_schema_name(
  2120. schema or self.default_schema_name
  2121. )
  2122. has_filter_names, params = self._prepare_filter_names(filter_names)
  2123. query = self._comment_query(owner, scope, kind, has_filter_names)
  2124. result = self._execute_reflection(
  2125. connection, query, dblink, returns_long=False, params=params
  2126. )
  2127. default = ReflectionDefaults.table_comment
  2128. # materialized views by default seem to have a comment like
  2129. # "snapshot table for snapshot owner.mat_view_name"
  2130. ignore_mat_view = "snapshot table for snapshot "
  2131. return (
  2132. (
  2133. (schema, self.normalize_name(table)),
  2134. {"text": comment}
  2135. if comment is not None
  2136. and not comment.startswith(ignore_mat_view)
  2137. else default(),
  2138. )
  2139. for table, comment in result
  2140. )
  2141. @reflection.cache
  2142. def get_indexes(self, connection, table_name, schema=None, **kw):
  2143. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2144. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2145. """
  2146. data = self.get_multi_indexes(
  2147. connection,
  2148. schema=schema,
  2149. filter_names=[table_name],
  2150. scope=ObjectScope.ANY,
  2151. kind=ObjectKind.ANY,
  2152. **kw,
  2153. )
  2154. return self._value_or_raise(data, table_name, schema)
  2155. @lru_cache()
  2156. def _index_query(self, owner):
  2157. return (
  2158. select(
  2159. dictionary.all_ind_columns.c.table_name,
  2160. dictionary.all_ind_columns.c.index_name,
  2161. dictionary.all_ind_columns.c.column_name,
  2162. dictionary.all_indexes.c.index_type,
  2163. dictionary.all_indexes.c.uniqueness,
  2164. dictionary.all_indexes.c.compression,
  2165. dictionary.all_indexes.c.prefix_length,
  2166. dictionary.all_ind_columns.c.descend,
  2167. dictionary.all_ind_expressions.c.column_expression,
  2168. )
  2169. .select_from(dictionary.all_ind_columns)
  2170. .join(
  2171. dictionary.all_indexes,
  2172. sql.and_(
  2173. dictionary.all_ind_columns.c.index_name
  2174. == dictionary.all_indexes.c.index_name,
  2175. dictionary.all_ind_columns.c.index_owner
  2176. == dictionary.all_indexes.c.owner,
  2177. ),
  2178. )
  2179. .outerjoin(
  2180. # NOTE: this adds about 20% to the query time. Using a
  2181. # case expression with a scalar subquery only when needed
  2182. # with the assumption that most indexes are not expression
  2183. # would be faster but oracle does not like that with
  2184. # LONG datatype. It errors with:
  2185. # ORA-00997: illegal use of LONG datatype
  2186. dictionary.all_ind_expressions,
  2187. sql.and_(
  2188. dictionary.all_ind_expressions.c.index_name
  2189. == dictionary.all_ind_columns.c.index_name,
  2190. dictionary.all_ind_expressions.c.index_owner
  2191. == dictionary.all_ind_columns.c.index_owner,
  2192. dictionary.all_ind_expressions.c.column_position
  2193. == dictionary.all_ind_columns.c.column_position,
  2194. ),
  2195. )
  2196. .where(
  2197. dictionary.all_indexes.c.table_owner == owner,
  2198. dictionary.all_indexes.c.table_name.in_(
  2199. bindparam("all_objects")
  2200. ),
  2201. )
  2202. .order_by(
  2203. dictionary.all_ind_columns.c.index_name,
  2204. dictionary.all_ind_columns.c.column_position,
  2205. )
  2206. )
  2207. @reflection.flexi_cache(
  2208. ("schema", InternalTraversal.dp_string),
  2209. ("dblink", InternalTraversal.dp_string),
  2210. ("all_objects", InternalTraversal.dp_string_list),
  2211. )
  2212. def _get_indexes_rows(self, connection, schema, dblink, all_objects, **kw):
  2213. owner = self.denormalize_schema_name(
  2214. schema or self.default_schema_name
  2215. )
  2216. query = self._index_query(owner)
  2217. pks = {
  2218. row_dict["constraint_name"]
  2219. for row_dict in self._get_all_constraint_rows(
  2220. connection, schema, dblink, all_objects, **kw
  2221. )
  2222. if row_dict["constraint_type"] == "P"
  2223. }
  2224. # all_ind_expressions.column_expression is LONG
  2225. result = self._run_batches(
  2226. connection,
  2227. query,
  2228. dblink,
  2229. returns_long=True,
  2230. mappings=True,
  2231. all_objects=all_objects,
  2232. )
  2233. return [
  2234. row_dict
  2235. for row_dict in result
  2236. if row_dict["index_name"] not in pks
  2237. ]
  2238. @_handle_synonyms_decorator
  2239. def get_multi_indexes(
  2240. self,
  2241. connection,
  2242. *,
  2243. schema,
  2244. filter_names,
  2245. scope,
  2246. kind,
  2247. dblink=None,
  2248. **kw,
  2249. ):
  2250. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2251. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2252. """
  2253. all_objects = self._get_all_objects(
  2254. connection, schema, scope, kind, filter_names, dblink, **kw
  2255. )
  2256. uniqueness = {"NONUNIQUE": False, "UNIQUE": True}
  2257. enabled = {"DISABLED": False, "ENABLED": True}
  2258. is_bitmap = {"BITMAP", "FUNCTION-BASED BITMAP"}
  2259. indexes = defaultdict(dict)
  2260. for row_dict in self._get_indexes_rows(
  2261. connection, schema, dblink, all_objects, **kw
  2262. ):
  2263. index_name = self.normalize_name(row_dict["index_name"])
  2264. table_name = self.normalize_name(row_dict["table_name"])
  2265. table_indexes = indexes[(schema, table_name)]
  2266. if index_name not in table_indexes:
  2267. table_indexes[index_name] = index_dict = {
  2268. "name": index_name,
  2269. "column_names": [],
  2270. "dialect_options": {},
  2271. "unique": uniqueness.get(row_dict["uniqueness"], False),
  2272. }
  2273. do = index_dict["dialect_options"]
  2274. if row_dict["index_type"] in is_bitmap:
  2275. do["oracle_bitmap"] = True
  2276. if enabled.get(row_dict["compression"], False):
  2277. do["oracle_compress"] = row_dict["prefix_length"]
  2278. else:
  2279. index_dict = table_indexes[index_name]
  2280. expr = row_dict["column_expression"]
  2281. if expr is not None:
  2282. index_dict["column_names"].append(None)
  2283. if "expressions" in index_dict:
  2284. index_dict["expressions"].append(expr)
  2285. else:
  2286. index_dict["expressions"] = index_dict["column_names"][:-1]
  2287. index_dict["expressions"].append(expr)
  2288. if row_dict["descend"].lower() != "asc":
  2289. assert row_dict["descend"].lower() == "desc"
  2290. cs = index_dict.setdefault("column_sorting", {})
  2291. cs[expr] = ("desc",)
  2292. else:
  2293. assert row_dict["descend"].lower() == "asc"
  2294. cn = self.normalize_name(row_dict["column_name"])
  2295. index_dict["column_names"].append(cn)
  2296. if "expressions" in index_dict:
  2297. index_dict["expressions"].append(cn)
  2298. default = ReflectionDefaults.indexes
  2299. return (
  2300. (key, list(indexes[key].values()) if key in indexes else default())
  2301. for key in (
  2302. (schema, self.normalize_name(obj_name))
  2303. for obj_name in all_objects
  2304. )
  2305. )
  2306. @reflection.cache
  2307. def get_pk_constraint(self, connection, table_name, schema=None, **kw):
  2308. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2309. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2310. """
  2311. data = self.get_multi_pk_constraint(
  2312. connection,
  2313. schema=schema,
  2314. filter_names=[table_name],
  2315. scope=ObjectScope.ANY,
  2316. kind=ObjectKind.ANY,
  2317. **kw,
  2318. )
  2319. return self._value_or_raise(data, table_name, schema)
  2320. @lru_cache()
  2321. def _constraint_query(self, owner):
  2322. local = dictionary.all_cons_columns.alias("local")
  2323. remote = dictionary.all_cons_columns.alias("remote")
  2324. return (
  2325. select(
  2326. dictionary.all_constraints.c.table_name,
  2327. dictionary.all_constraints.c.constraint_type,
  2328. dictionary.all_constraints.c.constraint_name,
  2329. local.c.column_name.label("local_column"),
  2330. remote.c.table_name.label("remote_table"),
  2331. remote.c.column_name.label("remote_column"),
  2332. remote.c.owner.label("remote_owner"),
  2333. dictionary.all_constraints.c.search_condition,
  2334. dictionary.all_constraints.c.delete_rule,
  2335. )
  2336. .select_from(dictionary.all_constraints)
  2337. .join(
  2338. local,
  2339. and_(
  2340. local.c.owner == dictionary.all_constraints.c.owner,
  2341. dictionary.all_constraints.c.constraint_name
  2342. == local.c.constraint_name,
  2343. ),
  2344. )
  2345. .outerjoin(
  2346. remote,
  2347. and_(
  2348. dictionary.all_constraints.c.r_owner == remote.c.owner,
  2349. dictionary.all_constraints.c.r_constraint_name
  2350. == remote.c.constraint_name,
  2351. or_(
  2352. remote.c.position.is_(sql.null()),
  2353. local.c.position == remote.c.position,
  2354. ),
  2355. ),
  2356. )
  2357. .where(
  2358. dictionary.all_constraints.c.owner == owner,
  2359. dictionary.all_constraints.c.table_name.in_(
  2360. bindparam("all_objects")
  2361. ),
  2362. dictionary.all_constraints.c.constraint_type.in_(
  2363. ("R", "P", "U", "C")
  2364. ),
  2365. )
  2366. .order_by(
  2367. dictionary.all_constraints.c.constraint_name, local.c.position
  2368. )
  2369. )
  2370. @reflection.flexi_cache(
  2371. ("schema", InternalTraversal.dp_string),
  2372. ("dblink", InternalTraversal.dp_string),
  2373. ("all_objects", InternalTraversal.dp_string_list),
  2374. )
  2375. def _get_all_constraint_rows(
  2376. self, connection, schema, dblink, all_objects, **kw
  2377. ):
  2378. owner = self.denormalize_schema_name(
  2379. schema or self.default_schema_name
  2380. )
  2381. query = self._constraint_query(owner)
  2382. # since the result is cached a list must be created
  2383. values = list(
  2384. self._run_batches(
  2385. connection,
  2386. query,
  2387. dblink,
  2388. returns_long=False,
  2389. mappings=True,
  2390. all_objects=all_objects,
  2391. )
  2392. )
  2393. return values
  2394. @_handle_synonyms_decorator
  2395. def get_multi_pk_constraint(
  2396. self,
  2397. connection,
  2398. *,
  2399. scope,
  2400. schema,
  2401. filter_names,
  2402. kind,
  2403. dblink=None,
  2404. **kw,
  2405. ):
  2406. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2407. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2408. """
  2409. all_objects = self._get_all_objects(
  2410. connection, schema, scope, kind, filter_names, dblink, **kw
  2411. )
  2412. primary_keys = defaultdict(dict)
  2413. default = ReflectionDefaults.pk_constraint
  2414. for row_dict in self._get_all_constraint_rows(
  2415. connection, schema, dblink, all_objects, **kw
  2416. ):
  2417. if row_dict["constraint_type"] != "P":
  2418. continue
  2419. table_name = self.normalize_name(row_dict["table_name"])
  2420. constraint_name = self.normalize_name(row_dict["constraint_name"])
  2421. column_name = self.normalize_name(row_dict["local_column"])
  2422. table_pk = primary_keys[(schema, table_name)]
  2423. if not table_pk:
  2424. table_pk["name"] = constraint_name
  2425. table_pk["constrained_columns"] = [column_name]
  2426. else:
  2427. table_pk["constrained_columns"].append(column_name)
  2428. return (
  2429. (key, primary_keys[key] if key in primary_keys else default())
  2430. for key in (
  2431. (schema, self.normalize_name(obj_name))
  2432. for obj_name in all_objects
  2433. )
  2434. )
  2435. @reflection.cache
  2436. def get_foreign_keys(
  2437. self,
  2438. connection,
  2439. table_name,
  2440. schema=None,
  2441. **kw,
  2442. ):
  2443. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2444. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2445. """
  2446. data = self.get_multi_foreign_keys(
  2447. connection,
  2448. schema=schema,
  2449. filter_names=[table_name],
  2450. scope=ObjectScope.ANY,
  2451. kind=ObjectKind.ANY,
  2452. **kw,
  2453. )
  2454. return self._value_or_raise(data, table_name, schema)
  2455. @_handle_synonyms_decorator
  2456. def get_multi_foreign_keys(
  2457. self,
  2458. connection,
  2459. *,
  2460. scope,
  2461. schema,
  2462. filter_names,
  2463. kind,
  2464. dblink=None,
  2465. **kw,
  2466. ):
  2467. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2468. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2469. """
  2470. all_objects = self._get_all_objects(
  2471. connection, schema, scope, kind, filter_names, dblink, **kw
  2472. )
  2473. resolve_synonyms = kw.get("oracle_resolve_synonyms", False)
  2474. owner = self.denormalize_schema_name(
  2475. schema or self.default_schema_name
  2476. )
  2477. all_remote_owners = set()
  2478. fkeys = defaultdict(dict)
  2479. for row_dict in self._get_all_constraint_rows(
  2480. connection, schema, dblink, all_objects, **kw
  2481. ):
  2482. if row_dict["constraint_type"] != "R":
  2483. continue
  2484. table_name = self.normalize_name(row_dict["table_name"])
  2485. constraint_name = self.normalize_name(row_dict["constraint_name"])
  2486. table_fkey = fkeys[(schema, table_name)]
  2487. assert constraint_name is not None
  2488. local_column = self.normalize_name(row_dict["local_column"])
  2489. remote_table = self.normalize_name(row_dict["remote_table"])
  2490. remote_column = self.normalize_name(row_dict["remote_column"])
  2491. remote_owner_orig = row_dict["remote_owner"]
  2492. remote_owner = self.normalize_name(remote_owner_orig)
  2493. if remote_owner_orig is not None:
  2494. all_remote_owners.add(remote_owner_orig)
  2495. if remote_table is None:
  2496. # ticket 363
  2497. if dblink and not dblink.startswith("@"):
  2498. dblink = f"@{dblink}"
  2499. util.warn(
  2500. "Got 'None' querying 'table_name' from "
  2501. f"all_cons_columns{dblink or ''} - does the user have "
  2502. "proper rights to the table?"
  2503. )
  2504. continue
  2505. if constraint_name not in table_fkey:
  2506. table_fkey[constraint_name] = fkey = {
  2507. "name": constraint_name,
  2508. "constrained_columns": [],
  2509. "referred_schema": None,
  2510. "referred_table": remote_table,
  2511. "referred_columns": [],
  2512. "options": {},
  2513. }
  2514. if resolve_synonyms:
  2515. # will be removed below
  2516. fkey["_ref_schema"] = remote_owner
  2517. if schema is not None or remote_owner_orig != owner:
  2518. fkey["referred_schema"] = remote_owner
  2519. delete_rule = row_dict["delete_rule"]
  2520. if delete_rule != "NO ACTION":
  2521. fkey["options"]["ondelete"] = delete_rule
  2522. else:
  2523. fkey = table_fkey[constraint_name]
  2524. fkey["constrained_columns"].append(local_column)
  2525. fkey["referred_columns"].append(remote_column)
  2526. if resolve_synonyms and all_remote_owners:
  2527. query = select(
  2528. dictionary.all_synonyms.c.owner,
  2529. dictionary.all_synonyms.c.table_name,
  2530. dictionary.all_synonyms.c.table_owner,
  2531. dictionary.all_synonyms.c.synonym_name,
  2532. ).where(dictionary.all_synonyms.c.owner.in_(all_remote_owners))
  2533. result = self._execute_reflection(
  2534. connection, query, dblink, returns_long=False
  2535. ).mappings()
  2536. remote_owners_lut = {}
  2537. for row in result:
  2538. synonym_owner = self.normalize_name(row["owner"])
  2539. table_name = self.normalize_name(row["table_name"])
  2540. remote_owners_lut[(synonym_owner, table_name)] = (
  2541. row["table_owner"],
  2542. row["synonym_name"],
  2543. )
  2544. empty = (None, None)
  2545. for table_fkeys in fkeys.values():
  2546. for table_fkey in table_fkeys.values():
  2547. key = (
  2548. table_fkey.pop("_ref_schema"),
  2549. table_fkey["referred_table"],
  2550. )
  2551. remote_owner, syn_name = remote_owners_lut.get(key, empty)
  2552. if syn_name:
  2553. sn = self.normalize_name(syn_name)
  2554. table_fkey["referred_table"] = sn
  2555. if schema is not None or remote_owner != owner:
  2556. ro = self.normalize_name(remote_owner)
  2557. table_fkey["referred_schema"] = ro
  2558. else:
  2559. table_fkey["referred_schema"] = None
  2560. default = ReflectionDefaults.foreign_keys
  2561. return (
  2562. (key, list(fkeys[key].values()) if key in fkeys else default())
  2563. for key in (
  2564. (schema, self.normalize_name(obj_name))
  2565. for obj_name in all_objects
  2566. )
  2567. )
  2568. @reflection.cache
  2569. def get_unique_constraints(
  2570. self, connection, table_name, schema=None, **kw
  2571. ):
  2572. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2573. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2574. """
  2575. data = self.get_multi_unique_constraints(
  2576. connection,
  2577. schema=schema,
  2578. filter_names=[table_name],
  2579. scope=ObjectScope.ANY,
  2580. kind=ObjectKind.ANY,
  2581. **kw,
  2582. )
  2583. return self._value_or_raise(data, table_name, schema)
  2584. @_handle_synonyms_decorator
  2585. def get_multi_unique_constraints(
  2586. self,
  2587. connection,
  2588. *,
  2589. scope,
  2590. schema,
  2591. filter_names,
  2592. kind,
  2593. dblink=None,
  2594. **kw,
  2595. ):
  2596. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2597. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2598. """
  2599. all_objects = self._get_all_objects(
  2600. connection, schema, scope, kind, filter_names, dblink, **kw
  2601. )
  2602. unique_cons = defaultdict(dict)
  2603. index_names = {
  2604. row_dict["index_name"]
  2605. for row_dict in self._get_indexes_rows(
  2606. connection, schema, dblink, all_objects, **kw
  2607. )
  2608. }
  2609. for row_dict in self._get_all_constraint_rows(
  2610. connection, schema, dblink, all_objects, **kw
  2611. ):
  2612. if row_dict["constraint_type"] != "U":
  2613. continue
  2614. table_name = self.normalize_name(row_dict["table_name"])
  2615. constraint_name_orig = row_dict["constraint_name"]
  2616. constraint_name = self.normalize_name(constraint_name_orig)
  2617. column_name = self.normalize_name(row_dict["local_column"])
  2618. table_uc = unique_cons[(schema, table_name)]
  2619. assert constraint_name is not None
  2620. if constraint_name not in table_uc:
  2621. table_uc[constraint_name] = uc = {
  2622. "name": constraint_name,
  2623. "column_names": [],
  2624. "duplicates_index": constraint_name
  2625. if constraint_name_orig in index_names
  2626. else None,
  2627. }
  2628. else:
  2629. uc = table_uc[constraint_name]
  2630. uc["column_names"].append(column_name)
  2631. default = ReflectionDefaults.unique_constraints
  2632. return (
  2633. (
  2634. key,
  2635. list(unique_cons[key].values())
  2636. if key in unique_cons
  2637. else default(),
  2638. )
  2639. for key in (
  2640. (schema, self.normalize_name(obj_name))
  2641. for obj_name in all_objects
  2642. )
  2643. )
  2644. @reflection.cache
  2645. def get_view_definition(
  2646. self,
  2647. connection,
  2648. view_name,
  2649. schema=None,
  2650. dblink=None,
  2651. **kw,
  2652. ):
  2653. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2654. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2655. """
  2656. if kw.get("oracle_resolve_synonyms", False):
  2657. synonyms = self._get_synonyms(
  2658. connection, schema, filter_names=[view_name], dblink=dblink
  2659. )
  2660. if synonyms:
  2661. assert len(synonyms) == 1
  2662. row_dict = synonyms[0]
  2663. dblink = self.normalize_name(row_dict["db_link"])
  2664. schema = row_dict["table_owner"]
  2665. view_name = row_dict["table_name"]
  2666. name = self.denormalize_name(view_name)
  2667. owner = self.denormalize_schema_name(
  2668. schema or self.default_schema_name
  2669. )
  2670. query = (
  2671. select(dictionary.all_views.c.text)
  2672. .where(
  2673. dictionary.all_views.c.view_name == name,
  2674. dictionary.all_views.c.owner == owner,
  2675. )
  2676. .union_all(
  2677. select(dictionary.all_mviews.c.query).where(
  2678. dictionary.all_mviews.c.mview_name == name,
  2679. dictionary.all_mviews.c.owner == owner,
  2680. )
  2681. )
  2682. )
  2683. rp = self._execute_reflection(
  2684. connection, query, dblink, returns_long=False
  2685. ).scalar()
  2686. if rp is None:
  2687. raise exc.NoSuchTableError(
  2688. f"{schema}.{view_name}" if schema else view_name
  2689. )
  2690. else:
  2691. return rp
  2692. @reflection.cache
  2693. def get_check_constraints(
  2694. self, connection, table_name, schema=None, include_all=False, **kw
  2695. ):
  2696. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2697. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2698. """
  2699. data = self.get_multi_check_constraints(
  2700. connection,
  2701. schema=schema,
  2702. filter_names=[table_name],
  2703. scope=ObjectScope.ANY,
  2704. include_all=include_all,
  2705. kind=ObjectKind.ANY,
  2706. **kw,
  2707. )
  2708. return self._value_or_raise(data, table_name, schema)
  2709. @_handle_synonyms_decorator
  2710. def get_multi_check_constraints(
  2711. self,
  2712. connection,
  2713. *,
  2714. schema,
  2715. filter_names,
  2716. dblink=None,
  2717. scope,
  2718. kind,
  2719. include_all=False,
  2720. **kw,
  2721. ):
  2722. """Supported kw arguments are: ``dblink`` to reflect via a db link;
  2723. ``oracle_resolve_synonyms`` to resolve names to synonyms
  2724. """
  2725. all_objects = self._get_all_objects(
  2726. connection, schema, scope, kind, filter_names, dblink, **kw
  2727. )
  2728. not_null = re.compile(r"..+?. IS NOT NULL$")
  2729. check_constraints = defaultdict(list)
  2730. for row_dict in self._get_all_constraint_rows(
  2731. connection, schema, dblink, all_objects, **kw
  2732. ):
  2733. if row_dict["constraint_type"] != "C":
  2734. continue
  2735. table_name = self.normalize_name(row_dict["table_name"])
  2736. constraint_name = self.normalize_name(row_dict["constraint_name"])
  2737. search_condition = row_dict["search_condition"]
  2738. table_checks = check_constraints[(schema, table_name)]
  2739. if constraint_name is not None and (
  2740. include_all or not not_null.match(search_condition)
  2741. ):
  2742. table_checks.append(
  2743. {"name": constraint_name, "sqltext": search_condition}
  2744. )
  2745. default = ReflectionDefaults.check_constraints
  2746. return (
  2747. (
  2748. key,
  2749. check_constraints[key]
  2750. if key in check_constraints
  2751. else default(),
  2752. )
  2753. for key in (
  2754. (schema, self.normalize_name(obj_name))
  2755. for obj_name in all_objects
  2756. )
  2757. )
  2758. def _list_dblinks(self, connection, dblink=None):
  2759. query = select(dictionary.all_db_links.c.db_link)
  2760. links = self._execute_reflection(
  2761. connection, query, dblink, returns_long=False
  2762. ).scalars()
  2763. return [self.normalize_name(link) for link in links]
  2764. class _OuterJoinColumn(sql.ClauseElement):
  2765. __visit_name__ = "outer_join_column"
  2766. def __init__(self, column):
  2767. self.column = column