SQLAlchemy 2.0.36__cp313-cp313-win32.whl

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