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