SQLAlchemy 2.1.0b2__cp313-cp313t-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 (270) hide show
  1. sqlalchemy/__init__.py +298 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +171 -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 +89 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4166 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  12. sqlalchemy/dialects/mssql/json.py +140 -0
  13. sqlalchemy/dialects/mssql/mssqlpython.py +220 -0
  14. sqlalchemy/dialects/mssql/provision.py +196 -0
  15. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  16. sqlalchemy/dialects/mssql/pyodbc.py +698 -0
  17. sqlalchemy/dialects/mysql/__init__.py +106 -0
  18. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  19. sqlalchemy/dialects/mysql/aiomysql.py +226 -0
  20. sqlalchemy/dialects/mysql/asyncmy.py +214 -0
  21. sqlalchemy/dialects/mysql/base.py +3877 -0
  22. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  23. sqlalchemy/dialects/mysql/dml.py +279 -0
  24. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  25. sqlalchemy/dialects/mysql/expression.py +146 -0
  26. sqlalchemy/dialects/mysql/json.py +92 -0
  27. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  28. sqlalchemy/dialects/mysql/mariadbconnector.py +330 -0
  29. sqlalchemy/dialects/mysql/mysqlconnector.py +296 -0
  30. sqlalchemy/dialects/mysql/mysqldb.py +312 -0
  31. sqlalchemy/dialects/mysql/provision.py +153 -0
  32. sqlalchemy/dialects/mysql/pymysql.py +157 -0
  33. sqlalchemy/dialects/mysql/pyodbc.py +156 -0
  34. sqlalchemy/dialects/mysql/reflection.py +724 -0
  35. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  36. sqlalchemy/dialects/mysql/types.py +845 -0
  37. sqlalchemy/dialects/oracle/__init__.py +85 -0
  38. sqlalchemy/dialects/oracle/base.py +3977 -0
  39. sqlalchemy/dialects/oracle/cx_oracle.py +1601 -0
  40. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  41. sqlalchemy/dialects/oracle/json.py +158 -0
  42. sqlalchemy/dialects/oracle/oracledb.py +909 -0
  43. sqlalchemy/dialects/oracle/provision.py +288 -0
  44. sqlalchemy/dialects/oracle/types.py +367 -0
  45. sqlalchemy/dialects/oracle/vector.py +368 -0
  46. sqlalchemy/dialects/postgresql/__init__.py +171 -0
  47. sqlalchemy/dialects/postgresql/_psycopg_common.py +229 -0
  48. sqlalchemy/dialects/postgresql/array.py +534 -0
  49. sqlalchemy/dialects/postgresql/asyncpg.py +1323 -0
  50. sqlalchemy/dialects/postgresql/base.py +5789 -0
  51. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  52. sqlalchemy/dialects/postgresql/dml.py +360 -0
  53. sqlalchemy/dialects/postgresql/ext.py +593 -0
  54. sqlalchemy/dialects/postgresql/hstore.py +423 -0
  55. sqlalchemy/dialects/postgresql/json.py +408 -0
  56. sqlalchemy/dialects/postgresql/named_types.py +521 -0
  57. sqlalchemy/dialects/postgresql/operators.py +130 -0
  58. sqlalchemy/dialects/postgresql/pg8000.py +670 -0
  59. sqlalchemy/dialects/postgresql/pg_catalog.py +344 -0
  60. sqlalchemy/dialects/postgresql/provision.py +184 -0
  61. sqlalchemy/dialects/postgresql/psycopg.py +799 -0
  62. sqlalchemy/dialects/postgresql/psycopg2.py +860 -0
  63. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  64. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  65. sqlalchemy/dialects/postgresql/types.py +388 -0
  66. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  67. sqlalchemy/dialects/sqlite/aiosqlite.py +321 -0
  68. sqlalchemy/dialects/sqlite/base.py +3063 -0
  69. sqlalchemy/dialects/sqlite/dml.py +279 -0
  70. sqlalchemy/dialects/sqlite/json.py +100 -0
  71. sqlalchemy/dialects/sqlite/provision.py +229 -0
  72. sqlalchemy/dialects/sqlite/pysqlcipher.py +161 -0
  73. sqlalchemy/dialects/sqlite/pysqlite.py +754 -0
  74. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  75. sqlalchemy/engine/__init__.py +62 -0
  76. sqlalchemy/engine/_processors_cy.cp313t-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp313t-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +633 -0
  80. sqlalchemy/engine/_row_cy.cp313t-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp313t-win_arm64.pyd +0 -0
  83. sqlalchemy/engine/_util_cy.py +136 -0
  84. sqlalchemy/engine/base.py +3354 -0
  85. sqlalchemy/engine/characteristics.py +155 -0
  86. sqlalchemy/engine/create.py +877 -0
  87. sqlalchemy/engine/cursor.py +2421 -0
  88. sqlalchemy/engine/default.py +2402 -0
  89. sqlalchemy/engine/events.py +965 -0
  90. sqlalchemy/engine/interfaces.py +3495 -0
  91. sqlalchemy/engine/mock.py +134 -0
  92. sqlalchemy/engine/processors.py +82 -0
  93. sqlalchemy/engine/reflection.py +2100 -0
  94. sqlalchemy/engine/result.py +1966 -0
  95. sqlalchemy/engine/row.py +397 -0
  96. sqlalchemy/engine/strategies.py +16 -0
  97. sqlalchemy/engine/url.py +922 -0
  98. sqlalchemy/engine/util.py +156 -0
  99. sqlalchemy/event/__init__.py +26 -0
  100. sqlalchemy/event/api.py +220 -0
  101. sqlalchemy/event/attr.py +674 -0
  102. sqlalchemy/event/base.py +472 -0
  103. sqlalchemy/event/legacy.py +258 -0
  104. sqlalchemy/event/registry.py +390 -0
  105. sqlalchemy/events.py +17 -0
  106. sqlalchemy/exc.py +922 -0
  107. sqlalchemy/ext/__init__.py +11 -0
  108. sqlalchemy/ext/associationproxy.py +2072 -0
  109. sqlalchemy/ext/asyncio/__init__.py +29 -0
  110. sqlalchemy/ext/asyncio/base.py +281 -0
  111. sqlalchemy/ext/asyncio/engine.py +1487 -0
  112. sqlalchemy/ext/asyncio/exc.py +21 -0
  113. sqlalchemy/ext/asyncio/result.py +994 -0
  114. sqlalchemy/ext/asyncio/scoping.py +1679 -0
  115. sqlalchemy/ext/asyncio/session.py +2007 -0
  116. sqlalchemy/ext/automap.py +1701 -0
  117. sqlalchemy/ext/baked.py +559 -0
  118. sqlalchemy/ext/compiler.py +600 -0
  119. sqlalchemy/ext/declarative/__init__.py +65 -0
  120. sqlalchemy/ext/declarative/extensions.py +560 -0
  121. sqlalchemy/ext/horizontal_shard.py +481 -0
  122. sqlalchemy/ext/hybrid.py +1877 -0
  123. sqlalchemy/ext/indexable.py +364 -0
  124. sqlalchemy/ext/instrumentation.py +450 -0
  125. sqlalchemy/ext/mutable.py +1081 -0
  126. sqlalchemy/ext/orderinglist.py +439 -0
  127. sqlalchemy/ext/serializer.py +185 -0
  128. sqlalchemy/future/__init__.py +16 -0
  129. sqlalchemy/future/engine.py +15 -0
  130. sqlalchemy/inspection.py +174 -0
  131. sqlalchemy/log.py +283 -0
  132. sqlalchemy/orm/__init__.py +176 -0
  133. sqlalchemy/orm/_orm_constructors.py +2694 -0
  134. sqlalchemy/orm/_typing.py +179 -0
  135. sqlalchemy/orm/attributes.py +2868 -0
  136. sqlalchemy/orm/base.py +976 -0
  137. sqlalchemy/orm/bulk_persistence.py +2152 -0
  138. sqlalchemy/orm/clsregistry.py +582 -0
  139. sqlalchemy/orm/collections.py +1568 -0
  140. sqlalchemy/orm/context.py +3471 -0
  141. sqlalchemy/orm/decl_api.py +2280 -0
  142. sqlalchemy/orm/decl_base.py +2309 -0
  143. sqlalchemy/orm/dependency.py +1306 -0
  144. sqlalchemy/orm/descriptor_props.py +1183 -0
  145. sqlalchemy/orm/dynamic.py +307 -0
  146. sqlalchemy/orm/evaluator.py +379 -0
  147. sqlalchemy/orm/events.py +3386 -0
  148. sqlalchemy/orm/exc.py +237 -0
  149. sqlalchemy/orm/identity.py +302 -0
  150. sqlalchemy/orm/instrumentation.py +746 -0
  151. sqlalchemy/orm/interfaces.py +1589 -0
  152. sqlalchemy/orm/loading.py +1684 -0
  153. sqlalchemy/orm/mapped_collection.py +557 -0
  154. sqlalchemy/orm/mapper.py +4411 -0
  155. sqlalchemy/orm/path_registry.py +829 -0
  156. sqlalchemy/orm/persistence.py +1789 -0
  157. sqlalchemy/orm/properties.py +973 -0
  158. sqlalchemy/orm/query.py +3528 -0
  159. sqlalchemy/orm/relationships.py +3570 -0
  160. sqlalchemy/orm/scoping.py +2232 -0
  161. sqlalchemy/orm/session.py +5403 -0
  162. sqlalchemy/orm/state.py +1175 -0
  163. sqlalchemy/orm/state_changes.py +196 -0
  164. sqlalchemy/orm/strategies.py +3492 -0
  165. sqlalchemy/orm/strategy_options.py +2562 -0
  166. sqlalchemy/orm/sync.py +164 -0
  167. sqlalchemy/orm/unitofwork.py +798 -0
  168. sqlalchemy/orm/util.py +2438 -0
  169. sqlalchemy/orm/writeonly.py +694 -0
  170. sqlalchemy/pool/__init__.py +41 -0
  171. sqlalchemy/pool/base.py +1522 -0
  172. sqlalchemy/pool/events.py +375 -0
  173. sqlalchemy/pool/impl.py +582 -0
  174. sqlalchemy/py.typed +0 -0
  175. sqlalchemy/schema.py +74 -0
  176. sqlalchemy/sql/__init__.py +156 -0
  177. sqlalchemy/sql/_annotated_cols.py +397 -0
  178. sqlalchemy/sql/_dml_constructors.py +132 -0
  179. sqlalchemy/sql/_elements_constructors.py +2164 -0
  180. sqlalchemy/sql/_orm_types.py +20 -0
  181. sqlalchemy/sql/_selectable_constructors.py +840 -0
  182. sqlalchemy/sql/_typing.py +487 -0
  183. sqlalchemy/sql/_util_cy.cp313t-win_arm64.pyd +0 -0
  184. sqlalchemy/sql/_util_cy.py +127 -0
  185. sqlalchemy/sql/annotation.py +590 -0
  186. sqlalchemy/sql/base.py +2699 -0
  187. sqlalchemy/sql/cache_key.py +1066 -0
  188. sqlalchemy/sql/coercions.py +1373 -0
  189. sqlalchemy/sql/compiler.py +8327 -0
  190. sqlalchemy/sql/crud.py +1815 -0
  191. sqlalchemy/sql/ddl.py +1928 -0
  192. sqlalchemy/sql/default_comparator.py +654 -0
  193. sqlalchemy/sql/dml.py +1977 -0
  194. sqlalchemy/sql/elements.py +6033 -0
  195. sqlalchemy/sql/events.py +458 -0
  196. sqlalchemy/sql/expression.py +172 -0
  197. sqlalchemy/sql/functions.py +2305 -0
  198. sqlalchemy/sql/lambdas.py +1443 -0
  199. sqlalchemy/sql/naming.py +209 -0
  200. sqlalchemy/sql/operators.py +2897 -0
  201. sqlalchemy/sql/roles.py +332 -0
  202. sqlalchemy/sql/schema.py +6703 -0
  203. sqlalchemy/sql/selectable.py +7553 -0
  204. sqlalchemy/sql/sqltypes.py +4093 -0
  205. sqlalchemy/sql/traversals.py +1042 -0
  206. sqlalchemy/sql/type_api.py +2446 -0
  207. sqlalchemy/sql/util.py +1495 -0
  208. sqlalchemy/sql/visitors.py +1157 -0
  209. sqlalchemy/testing/__init__.py +96 -0
  210. sqlalchemy/testing/assertions.py +1007 -0
  211. sqlalchemy/testing/assertsql.py +519 -0
  212. sqlalchemy/testing/asyncio.py +128 -0
  213. sqlalchemy/testing/config.py +440 -0
  214. sqlalchemy/testing/engines.py +483 -0
  215. sqlalchemy/testing/entities.py +117 -0
  216. sqlalchemy/testing/exclusions.py +476 -0
  217. sqlalchemy/testing/fixtures/__init__.py +30 -0
  218. sqlalchemy/testing/fixtures/base.py +384 -0
  219. sqlalchemy/testing/fixtures/mypy.py +247 -0
  220. sqlalchemy/testing/fixtures/orm.py +227 -0
  221. sqlalchemy/testing/fixtures/sql.py +538 -0
  222. sqlalchemy/testing/pickleable.py +155 -0
  223. sqlalchemy/testing/plugin/__init__.py +6 -0
  224. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  225. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  226. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  227. sqlalchemy/testing/profiling.py +329 -0
  228. sqlalchemy/testing/provision.py +613 -0
  229. sqlalchemy/testing/requirements.py +1978 -0
  230. sqlalchemy/testing/schema.py +198 -0
  231. sqlalchemy/testing/suite/__init__.py +19 -0
  232. sqlalchemy/testing/suite/test_cte.py +237 -0
  233. sqlalchemy/testing/suite/test_ddl.py +420 -0
  234. sqlalchemy/testing/suite/test_dialect.py +776 -0
  235. sqlalchemy/testing/suite/test_insert.py +630 -0
  236. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  237. sqlalchemy/testing/suite/test_results.py +660 -0
  238. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  239. sqlalchemy/testing/suite/test_select.py +2112 -0
  240. sqlalchemy/testing/suite/test_sequence.py +317 -0
  241. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  242. sqlalchemy/testing/suite/test_types.py +2271 -0
  243. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  244. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  245. sqlalchemy/testing/util.py +535 -0
  246. sqlalchemy/testing/warnings.py +52 -0
  247. sqlalchemy/types.py +76 -0
  248. sqlalchemy/util/__init__.py +158 -0
  249. sqlalchemy/util/_collections.py +688 -0
  250. sqlalchemy/util/_collections_cy.cp313t-win_arm64.pyd +0 -0
  251. sqlalchemy/util/_collections_cy.pxd +8 -0
  252. sqlalchemy/util/_collections_cy.py +516 -0
  253. sqlalchemy/util/_has_cython.py +46 -0
  254. sqlalchemy/util/_immutabledict_cy.cp313t-win_arm64.pyd +0 -0
  255. sqlalchemy/util/_immutabledict_cy.py +240 -0
  256. sqlalchemy/util/compat.py +299 -0
  257. sqlalchemy/util/concurrency.py +322 -0
  258. sqlalchemy/util/cython.py +79 -0
  259. sqlalchemy/util/deprecations.py +401 -0
  260. sqlalchemy/util/langhelpers.py +2320 -0
  261. sqlalchemy/util/preloaded.py +152 -0
  262. sqlalchemy/util/queue.py +304 -0
  263. sqlalchemy/util/tool_support.py +201 -0
  264. sqlalchemy/util/topological.py +120 -0
  265. sqlalchemy/util/typing.py +711 -0
  266. sqlalchemy-2.1.0b2.dist-info/METADATA +269 -0
  267. sqlalchemy-2.1.0b2.dist-info/RECORD +270 -0
  268. sqlalchemy-2.1.0b2.dist-info/WHEEL +5 -0
  269. sqlalchemy-2.1.0b2.dist-info/licenses/LICENSE +19 -0
  270. sqlalchemy-2.1.0b2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3977 @@
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
+ from typing import Any
1004
+ from typing import Callable
1005
+ from typing import TYPE_CHECKING
1006
+
1007
+ from . import dictionary
1008
+ from .json import JSON
1009
+ from .json import JSONIndexType
1010
+ from .json import JSONPathType
1011
+ from .types import _OracleBoolean
1012
+ from .types import _OracleDate
1013
+ from .types import BFILE
1014
+ from .types import BINARY_DOUBLE
1015
+ from .types import BINARY_FLOAT
1016
+ from .types import BOOLEAN
1017
+ from .types import DATE
1018
+ from .types import FLOAT
1019
+ from .types import INTERVAL
1020
+ from .types import LONG
1021
+ from .types import NCLOB
1022
+ from .types import NUMBER
1023
+ from .types import NVARCHAR2 # noqa
1024
+ from .types import OracleRaw # noqa
1025
+ from .types import RAW
1026
+ from .types import ROWID # noqa
1027
+ from .types import TIMESTAMP
1028
+ from .types import VARCHAR2 # noqa
1029
+ from .vector import VECTOR
1030
+ from .vector import VectorIndexConfig
1031
+ from .vector import VectorIndexType
1032
+ from ... import Computed
1033
+ from ... import exc
1034
+ from ... import schema as sa_schema
1035
+ from ... import sql
1036
+ from ... import util
1037
+ from ...engine import default
1038
+ from ...engine import ObjectKind
1039
+ from ...engine import ObjectScope
1040
+ from ...engine import reflection
1041
+ from ...engine.reflection import ReflectionDefaults
1042
+ from ...sql import and_
1043
+ from ...sql import bindparam
1044
+ from ...sql import compiler
1045
+ from ...sql import elements
1046
+ from ...sql import expression
1047
+ from ...sql import func
1048
+ from ...sql import null
1049
+ from ...sql import or_
1050
+ from ...sql import select
1051
+ from ...sql import selectable as sa_selectable
1052
+ from ...sql import sqltypes
1053
+ from ...sql import util as sql_util
1054
+ from ...sql import visitors
1055
+ from ...sql.base import NO_ARG
1056
+ from ...sql.compiler import AggregateOrderByStyle
1057
+ from ...sql.visitors import InternalTraversal
1058
+ from ...types import BLOB
1059
+ from ...types import CHAR
1060
+ from ...types import CLOB
1061
+ from ...types import DOUBLE_PRECISION
1062
+ from ...types import INTEGER
1063
+ from ...types import NCHAR
1064
+ from ...types import NVARCHAR
1065
+ from ...types import REAL
1066
+ from ...types import VARCHAR
1067
+
1068
+ if TYPE_CHECKING:
1069
+ from ...sql.sqltypes import _JSON_VALUE
1070
+
1071
+ RESERVED_WORDS = set(
1072
+ "SHARE RAW DROP BETWEEN FROM DESC OPTION PRIOR LONG THEN "
1073
+ "DEFAULT ALTER IS INTO MINUS INTEGER NUMBER GRANT IDENTIFIED "
1074
+ "ALL TO ORDER ON FLOAT DATE HAVING CLUSTER NOWAIT RESOURCE "
1075
+ "ANY TABLE INDEX FOR UPDATE WHERE CHECK SMALLINT WITH DELETE "
1076
+ "BY ASC REVOKE LIKE SIZE RENAME NOCOMPRESS NULL GROUP VALUES "
1077
+ "AS IN VIEW EXCLUSIVE COMPRESS SYNONYM SELECT INSERT EXISTS "
1078
+ "NOT TRIGGER ELSE CREATE INTERSECT PCTFREE DISTINCT USER "
1079
+ "CONNECT SET MODE OF UNIQUE VARCHAR2 VARCHAR LOCK OR CHAR "
1080
+ "DECIMAL UNION PUBLIC AND START UID COMMENT CURRENT LEVEL".split()
1081
+ )
1082
+
1083
+ NO_ARG_FNS = set(
1084
+ "UID CURRENT_DATE SYSDATE USER CURRENT_TIME CURRENT_TIMESTAMP".split()
1085
+ )
1086
+
1087
+
1088
+ colspecs = {
1089
+ sqltypes.Boolean: _OracleBoolean,
1090
+ sqltypes.Interval: INTERVAL,
1091
+ sqltypes.DateTime: DATE,
1092
+ sqltypes.Date: _OracleDate,
1093
+ sqltypes.JSON: JSON,
1094
+ sqltypes.JSON.JSONIndexType: JSONIndexType,
1095
+ sqltypes.JSON.JSONPathType: JSONPathType,
1096
+ }
1097
+
1098
+ ischema_names = {
1099
+ "VARCHAR2": VARCHAR,
1100
+ "NVARCHAR2": NVARCHAR,
1101
+ "CHAR": CHAR,
1102
+ "NCHAR": NCHAR,
1103
+ "DATE": DATE,
1104
+ "NUMBER": NUMBER,
1105
+ "BLOB": BLOB,
1106
+ "BFILE": BFILE,
1107
+ "CLOB": CLOB,
1108
+ "NCLOB": NCLOB,
1109
+ "TIMESTAMP": TIMESTAMP,
1110
+ "TIMESTAMP WITH TIME ZONE": TIMESTAMP,
1111
+ "TIMESTAMP WITH LOCAL TIME ZONE": TIMESTAMP,
1112
+ "INTERVAL DAY TO SECOND": INTERVAL,
1113
+ "RAW": RAW,
1114
+ "FLOAT": FLOAT,
1115
+ "DOUBLE PRECISION": DOUBLE_PRECISION,
1116
+ "REAL": REAL,
1117
+ "LONG": LONG,
1118
+ "BINARY_DOUBLE": BINARY_DOUBLE,
1119
+ "BINARY_FLOAT": BINARY_FLOAT,
1120
+ "ROWID": ROWID,
1121
+ "BOOLEAN": BOOLEAN,
1122
+ "VECTOR": VECTOR,
1123
+ "JSON": JSON,
1124
+ }
1125
+
1126
+
1127
+ class OracleTypeCompiler(compiler.GenericTypeCompiler):
1128
+ # Note:
1129
+ # Oracle DATE == DATETIME
1130
+ # Oracle does not allow milliseconds in DATE
1131
+ # Oracle does not support TIME columns
1132
+
1133
+ def visit_datetime(self, type_, **kw):
1134
+ return self.visit_DATE(type_, **kw)
1135
+
1136
+ def visit_float(self, type_, **kw):
1137
+ return self.visit_FLOAT(type_, **kw)
1138
+
1139
+ def visit_double(self, type_, **kw):
1140
+ return self.visit_DOUBLE_PRECISION(type_, **kw)
1141
+
1142
+ def visit_unicode(self, type_, **kw):
1143
+ if self.dialect._use_nchar_for_unicode:
1144
+ return self.visit_NVARCHAR2(type_, **kw)
1145
+ else:
1146
+ return self.visit_VARCHAR2(type_, **kw)
1147
+
1148
+ def visit_INTERVAL(self, type_, **kw):
1149
+ return "INTERVAL DAY%s TO SECOND%s" % (
1150
+ type_.day_precision is not None
1151
+ and "(%d)" % type_.day_precision
1152
+ or "",
1153
+ type_.second_precision is not None
1154
+ and "(%d)" % type_.second_precision
1155
+ or "",
1156
+ )
1157
+
1158
+ def visit_LONG(self, type_, **kw):
1159
+ return "LONG"
1160
+
1161
+ def visit_TIMESTAMP(self, type_, **kw):
1162
+ if getattr(type_, "local_timezone", False):
1163
+ return "TIMESTAMP WITH LOCAL TIME ZONE"
1164
+ elif type_.timezone:
1165
+ return "TIMESTAMP WITH TIME ZONE"
1166
+ else:
1167
+ return "TIMESTAMP"
1168
+
1169
+ def visit_DOUBLE_PRECISION(self, type_, **kw):
1170
+ return self._generate_numeric(type_, "DOUBLE PRECISION", **kw)
1171
+
1172
+ def visit_BINARY_DOUBLE(self, type_, **kw):
1173
+ return self._generate_numeric(type_, "BINARY_DOUBLE", **kw)
1174
+
1175
+ def visit_BINARY_FLOAT(self, type_, **kw):
1176
+ return self._generate_numeric(type_, "BINARY_FLOAT", **kw)
1177
+
1178
+ def visit_FLOAT(self, type_, **kw):
1179
+ kw["_requires_binary_precision"] = True
1180
+ return self._generate_numeric(type_, "FLOAT", **kw)
1181
+
1182
+ def visit_NUMBER(self, type_, **kw):
1183
+ return self._generate_numeric(type_, "NUMBER", **kw)
1184
+
1185
+ def _generate_numeric(
1186
+ self,
1187
+ type_,
1188
+ name,
1189
+ precision=None,
1190
+ scale=None,
1191
+ _requires_binary_precision=False,
1192
+ **kw,
1193
+ ):
1194
+ if precision is None:
1195
+ precision = getattr(type_, "precision", None)
1196
+
1197
+ if _requires_binary_precision:
1198
+ binary_precision = getattr(type_, "binary_precision", None)
1199
+
1200
+ if precision and binary_precision is None:
1201
+ # https://www.oracletutorial.com/oracle-basics/oracle-float/
1202
+ estimated_binary_precision = int(precision / 0.30103)
1203
+ raise exc.ArgumentError(
1204
+ "Oracle Database FLOAT types use 'binary precision', "
1205
+ "which does not convert cleanly from decimal "
1206
+ "'precision'. Please specify "
1207
+ "this type with a separate Oracle Database variant, such "
1208
+ f"as {type_.__class__.__name__}(precision={precision})."
1209
+ f"with_variant(oracle.FLOAT"
1210
+ f"(binary_precision="
1211
+ f"{estimated_binary_precision}), 'oracle'), so that the "
1212
+ "Oracle Database specific 'binary_precision' may be "
1213
+ "specified accurately."
1214
+ )
1215
+ else:
1216
+ precision = binary_precision
1217
+
1218
+ if scale is None:
1219
+ scale = getattr(type_, "scale", None)
1220
+
1221
+ if precision is None:
1222
+ return name
1223
+ elif scale is None:
1224
+ n = "%(name)s(%(precision)s)"
1225
+ return n % {"name": name, "precision": precision}
1226
+ else:
1227
+ n = "%(name)s(%(precision)s, %(scale)s)"
1228
+ return n % {"name": name, "precision": precision, "scale": scale}
1229
+
1230
+ def visit_string(self, type_, **kw):
1231
+ return self.visit_VARCHAR2(type_, **kw)
1232
+
1233
+ def visit_VARCHAR2(self, type_, **kw):
1234
+ return self._visit_varchar(type_, "", "2")
1235
+
1236
+ def visit_NVARCHAR2(self, type_, **kw):
1237
+ return self._visit_varchar(type_, "N", "2")
1238
+
1239
+ visit_NVARCHAR = visit_NVARCHAR2
1240
+
1241
+ def visit_VARCHAR(self, type_, **kw):
1242
+ return self._visit_varchar(type_, "", "")
1243
+
1244
+ def _visit_varchar(self, type_, n, num):
1245
+ if not type_.length:
1246
+ return "%(n)sVARCHAR%(two)s" % {"two": num, "n": n}
1247
+ elif not n and self.dialect._supports_char_length:
1248
+ varchar = "VARCHAR%(two)s(%(length)s CHAR)"
1249
+ return varchar % {"length": type_.length, "two": num}
1250
+ else:
1251
+ varchar = "%(n)sVARCHAR%(two)s(%(length)s)"
1252
+ return varchar % {"length": type_.length, "two": num, "n": n}
1253
+
1254
+ def visit_text(self, type_, **kw):
1255
+ return self.visit_CLOB(type_, **kw)
1256
+
1257
+ def visit_unicode_text(self, type_, **kw):
1258
+ if self.dialect._use_nchar_for_unicode:
1259
+ return self.visit_NCLOB(type_, **kw)
1260
+ else:
1261
+ return self.visit_CLOB(type_, **kw)
1262
+
1263
+ def visit_large_binary(self, type_, **kw):
1264
+ return self.visit_BLOB(type_, **kw)
1265
+
1266
+ def visit_big_integer(self, type_, **kw):
1267
+ return self.visit_NUMBER(type_, precision=19, **kw)
1268
+
1269
+ def visit_boolean(self, type_, **kw):
1270
+ if self.dialect.supports_native_boolean:
1271
+ return self.visit_BOOLEAN(type_, **kw)
1272
+ else:
1273
+ return self.visit_SMALLINT(type_, **kw)
1274
+
1275
+ def visit_RAW(self, type_, **kw):
1276
+ if type_.length:
1277
+ return "RAW(%(length)s)" % {"length": type_.length}
1278
+ else:
1279
+ return "RAW"
1280
+
1281
+ def visit_ROWID(self, type_, **kw):
1282
+ return "ROWID"
1283
+
1284
+ def visit_VECTOR(self, type_, **kw):
1285
+ dim = type_.dim if type_.dim is not None else "*"
1286
+ storage_format = (
1287
+ type_.storage_format.value
1288
+ if type_.storage_format is not None
1289
+ else "*"
1290
+ )
1291
+ storage_type = (
1292
+ type_.storage_type.value if type_.storage_type is not None else "*"
1293
+ )
1294
+ return f"VECTOR({dim},{storage_format},{storage_type})"
1295
+
1296
+ def visit_JSON(self, type_: JSON, **kw: Any) -> str:
1297
+ use_blob = (
1298
+ not self.dialect._supports_oracle_json
1299
+ if getattr(type_, "use_blob", NO_ARG) is NO_ARG
1300
+ else type_.use_blob
1301
+ )
1302
+
1303
+ if use_blob:
1304
+ return "BLOB"
1305
+ else:
1306
+ return "JSON"
1307
+
1308
+
1309
+ class OracleCompiler(compiler.SQLCompiler):
1310
+ """Oracle compiler modifies the lexical structure of Select
1311
+ statements to work under non-ANSI configured Oracle databases, if
1312
+ the use_ansi flag is False.
1313
+ """
1314
+
1315
+ compound_keywords = util.update_copy(
1316
+ compiler.SQLCompiler.compound_keywords,
1317
+ {expression.CompoundSelect.EXCEPT: "MINUS"},
1318
+ )
1319
+
1320
+ def __init__(self, *args, **kwargs):
1321
+ self.__wheres = {}
1322
+ super().__init__(*args, **kwargs)
1323
+
1324
+ def visit_mod_binary(self, binary, operator, **kw):
1325
+ return "mod(%s, %s)" % (
1326
+ self.process(binary.left, **kw),
1327
+ self.process(binary.right, **kw),
1328
+ )
1329
+
1330
+ def visit_now_func(self, fn, **kw):
1331
+ return "CURRENT_TIMESTAMP"
1332
+
1333
+ def visit_char_length_func(self, fn, **kw):
1334
+ return "LENGTH" + self.function_argspec(fn, **kw)
1335
+
1336
+ def visit_pow_func(self, fn, **kw):
1337
+ return f"POWER{self.function_argspec(fn)}"
1338
+
1339
+ def visit_match_op_binary(self, binary, operator, **kw):
1340
+ return "CONTAINS (%s, %s)" % (
1341
+ self.process(binary.left),
1342
+ self.process(binary.right),
1343
+ )
1344
+
1345
+ def visit_true(self, expr, **kw):
1346
+ return "1"
1347
+
1348
+ def visit_false(self, expr, **kw):
1349
+ return "0"
1350
+
1351
+ def visit_cast(self, cast, **kwargs):
1352
+ # Oracle requires VARCHAR2 to have a length in CAST expressions
1353
+ # Adapt String types to VARCHAR2 with appropriate length
1354
+ type_ = cast.typeclause.type
1355
+ if isinstance(type_, sqltypes.String) and not isinstance(
1356
+ type_, (sqltypes.Text, sqltypes.CLOB)
1357
+ ):
1358
+ adapted = VARCHAR2._adapt_string_for_cast(type_)
1359
+ type_clause = self.dialect.type_compiler_instance.process(adapted)
1360
+ else:
1361
+ type_clause = cast.typeclause._compiler_dispatch(self, **kwargs)
1362
+
1363
+ return "CAST(%s AS %s)" % (
1364
+ cast.clause._compiler_dispatch(self, **kwargs),
1365
+ type_clause,
1366
+ )
1367
+
1368
+ def get_cte_preamble(self, recursive):
1369
+ return "WITH"
1370
+
1371
+ def get_select_hint_text(self, byfroms):
1372
+ return " ".join("/*+ %s */" % text for table, text in byfroms.items())
1373
+
1374
+ def function_argspec(self, fn, **kw):
1375
+ if len(fn.clauses) > 0 or fn.name.upper() not in NO_ARG_FNS:
1376
+ return compiler.SQLCompiler.function_argspec(self, fn, **kw)
1377
+ else:
1378
+ return ""
1379
+
1380
+ def visit_function(self, func, **kw):
1381
+ text = super().visit_function(func, **kw)
1382
+ if kw.get("asfrom", False) and func.name.lower() != "table":
1383
+ text = "TABLE (%s)" % text
1384
+ return text
1385
+
1386
+ def visit_table_valued_column(self, element, **kw):
1387
+ text = super().visit_table_valued_column(element, **kw)
1388
+ text = text + ".COLUMN_VALUE"
1389
+ return text
1390
+
1391
+ def default_from(self):
1392
+ """Called when a ``SELECT`` statement has no froms,
1393
+ and no ``FROM`` clause is to be appended.
1394
+
1395
+ The Oracle compiler tacks a "FROM DUAL" to the statement.
1396
+ """
1397
+
1398
+ return " FROM DUAL"
1399
+
1400
+ def visit_join(self, join, from_linter=None, **kwargs):
1401
+ if self.dialect.use_ansi:
1402
+ return compiler.SQLCompiler.visit_join(
1403
+ self, join, from_linter=from_linter, **kwargs
1404
+ )
1405
+ else:
1406
+ if from_linter:
1407
+ from_linter.edges.add((join.left, join.right))
1408
+
1409
+ kwargs["asfrom"] = True
1410
+ if isinstance(join.right, expression.FromGrouping):
1411
+ right = join.right.element
1412
+ else:
1413
+ right = join.right
1414
+ return (
1415
+ self.process(join.left, from_linter=from_linter, **kwargs)
1416
+ + ", "
1417
+ + self.process(right, from_linter=from_linter, **kwargs)
1418
+ )
1419
+
1420
+ def _get_nonansi_join_whereclause(self, froms):
1421
+ clauses = []
1422
+
1423
+ def visit_join(join):
1424
+ if join.isouter:
1425
+ # https://docs.oracle.com/database/121/SQLRF/queries006.htm#SQLRF52354
1426
+ # "apply the outer join operator (+) to all columns of B in
1427
+ # the join condition in the WHERE clause" - that is,
1428
+ # unconditionally regardless of operator or the other side
1429
+ def visit_binary(binary):
1430
+ if isinstance(
1431
+ binary.left, expression.ColumnClause
1432
+ ) and join.right.is_derived_from(binary.left.table):
1433
+ binary.left = _OuterJoinColumn(binary.left)
1434
+ elif isinstance(
1435
+ binary.right, expression.ColumnClause
1436
+ ) and join.right.is_derived_from(binary.right.table):
1437
+ binary.right = _OuterJoinColumn(binary.right)
1438
+
1439
+ clauses.append(
1440
+ visitors.cloned_traverse(
1441
+ join.onclause, {}, {"binary": visit_binary}
1442
+ )
1443
+ )
1444
+ else:
1445
+ clauses.append(join.onclause)
1446
+
1447
+ for j in join.left, join.right:
1448
+ if isinstance(j, expression.Join):
1449
+ visit_join(j)
1450
+ elif isinstance(j, expression.FromGrouping):
1451
+ visit_join(j.element)
1452
+
1453
+ for f in froms:
1454
+ if isinstance(f, expression.Join):
1455
+ visit_join(f)
1456
+
1457
+ if not clauses:
1458
+ return None
1459
+ else:
1460
+ return sql.and_(*clauses)
1461
+
1462
+ def visit_outer_join_column(self, vc, **kw):
1463
+ return self.process(vc.column, **kw) + "(+)"
1464
+
1465
+ def visit_sequence(self, seq, **kw):
1466
+ return self.preparer.format_sequence(seq) + ".nextval"
1467
+
1468
+ def get_render_as_alias_suffix(self, alias_name_text):
1469
+ """Oracle doesn't like ``FROM table AS alias``"""
1470
+
1471
+ return " " + alias_name_text
1472
+
1473
+ def returning_clause(
1474
+ self, stmt, returning_cols, *, populate_result_map, **kw
1475
+ ):
1476
+ columns = []
1477
+ binds = []
1478
+
1479
+ for i, column in enumerate(
1480
+ expression._select_iterables(returning_cols)
1481
+ ):
1482
+ if (
1483
+ self.isupdate
1484
+ and isinstance(column, sa_schema.Column)
1485
+ and isinstance(column.server_default, Computed)
1486
+ and not self.dialect._supports_update_returning_computed_cols
1487
+ ):
1488
+ util.warn(
1489
+ "Computed columns don't work with Oracle Database UPDATE "
1490
+ "statements that use RETURNING; the value of the column "
1491
+ "*before* the UPDATE takes place is returned. It is "
1492
+ "advised to not use RETURNING with an Oracle Database "
1493
+ "computed column. Consider setting implicit_returning "
1494
+ "to False on the Table object in order to avoid implicit "
1495
+ "RETURNING clauses from being generated for this Table."
1496
+ )
1497
+ if column.type._has_column_expression:
1498
+ col_expr = column.type.column_expression(column)
1499
+ else:
1500
+ col_expr = column
1501
+
1502
+ outparam = sql.outparam("ret_%d" % i, type_=column.type)
1503
+ self.binds[outparam.key] = outparam
1504
+ binds.append(
1505
+ self.bindparam_string(self._truncate_bindparam(outparam))
1506
+ )
1507
+
1508
+ # has_out_parameters would in a normal case be set to True
1509
+ # as a result of the compiler visiting an outparam() object.
1510
+ # in this case, the above outparam() objects are not being
1511
+ # visited. Ensure the statement itself didn't have other
1512
+ # outparam() objects independently.
1513
+ # technically, this could be supported, but as it would be
1514
+ # a very strange use case without a clear rationale, disallow it
1515
+ if self.has_out_parameters:
1516
+ raise exc.InvalidRequestError(
1517
+ "Using explicit outparam() objects with "
1518
+ "UpdateBase.returning() in the same Core DML statement "
1519
+ "is not supported in the Oracle Database dialects."
1520
+ )
1521
+
1522
+ self._oracle_returning = True
1523
+
1524
+ columns.append(self.process(col_expr, within_columns_clause=False))
1525
+ if populate_result_map:
1526
+ self._add_to_result_map(
1527
+ getattr(col_expr, "name", col_expr._anon_name_label),
1528
+ getattr(col_expr, "name", col_expr._anon_name_label),
1529
+ (
1530
+ column,
1531
+ getattr(column, "name", None),
1532
+ getattr(column, "key", None),
1533
+ ),
1534
+ column.type,
1535
+ )
1536
+
1537
+ return "RETURNING " + ", ".join(columns) + " INTO " + ", ".join(binds)
1538
+
1539
+ def _row_limit_clause(self, select, **kw):
1540
+ """Oracle Database 12c supports OFFSET/FETCH operators
1541
+ Use it instead subquery with row_number
1542
+
1543
+ """
1544
+
1545
+ if (
1546
+ select._fetch_clause is not None
1547
+ or not self.dialect._supports_offset_fetch
1548
+ ):
1549
+ return super()._row_limit_clause(
1550
+ select, use_literal_execute_for_simple_int=True, **kw
1551
+ )
1552
+ else:
1553
+ return self.fetch_clause(
1554
+ select,
1555
+ fetch_clause=self._get_limit_or_fetch(select),
1556
+ use_literal_execute_for_simple_int=True,
1557
+ **kw,
1558
+ )
1559
+
1560
+ def _get_limit_or_fetch(self, select):
1561
+ if select._fetch_clause is None:
1562
+ return select._limit_clause
1563
+ else:
1564
+ return select._fetch_clause
1565
+
1566
+ def fetch_clause(
1567
+ self,
1568
+ select,
1569
+ fetch_clause=None,
1570
+ require_offset=False,
1571
+ use_literal_execute_for_simple_int=False,
1572
+ **kw,
1573
+ ):
1574
+ text = super().fetch_clause(
1575
+ select,
1576
+ fetch_clause=fetch_clause,
1577
+ require_offset=require_offset,
1578
+ use_literal_execute_for_simple_int=(
1579
+ use_literal_execute_for_simple_int
1580
+ ),
1581
+ **kw,
1582
+ )
1583
+
1584
+ if select.dialect_options["oracle"]["fetch_approximate"]:
1585
+ text = re.sub("FETCH FIRST", "FETCH APPROX FIRST", text)
1586
+
1587
+ return text
1588
+
1589
+ def translate_select_structure(self, select_stmt, **kwargs):
1590
+ select = select_stmt
1591
+
1592
+ if not getattr(select, "_oracle_visit", None):
1593
+ if not self.dialect.use_ansi:
1594
+ froms = self._display_froms_for_select(
1595
+ select, kwargs.get("asfrom", False)
1596
+ )
1597
+ whereclause = self._get_nonansi_join_whereclause(froms)
1598
+ if whereclause is not None:
1599
+ select = select.where(whereclause)
1600
+ select._oracle_visit = True
1601
+
1602
+ # if fetch is used this is not needed
1603
+ if (
1604
+ select._has_row_limiting_clause
1605
+ and not self.dialect._supports_offset_fetch
1606
+ and select._fetch_clause is None
1607
+ ):
1608
+ limit_clause = select._limit_clause
1609
+ offset_clause = select._offset_clause
1610
+
1611
+ if select._simple_int_clause(limit_clause):
1612
+ limit_clause = limit_clause.render_literal_execute()
1613
+
1614
+ if select._simple_int_clause(offset_clause):
1615
+ offset_clause = offset_clause.render_literal_execute()
1616
+
1617
+ # currently using form at:
1618
+ # https://blogs.oracle.com/oraclemagazine/\
1619
+ # on-rownum-and-limiting-results
1620
+
1621
+ orig_select = select
1622
+ select = select._generate()
1623
+ select._oracle_visit = True
1624
+
1625
+ # add expressions to accommodate FOR UPDATE OF
1626
+ for_update = select._for_update_arg
1627
+ if for_update is not None and for_update.of:
1628
+ for_update = for_update._clone()
1629
+ for_update._copy_internals()
1630
+
1631
+ for elem in for_update.of:
1632
+ if not select.selected_columns.contains_column(elem):
1633
+ select = select.add_columns(elem)
1634
+
1635
+ # Wrap the middle select and add the hint
1636
+ inner_subquery = select.alias()
1637
+ limitselect = sql.select(
1638
+ *[
1639
+ c
1640
+ for c in inner_subquery.c
1641
+ if orig_select.selected_columns.corresponding_column(c)
1642
+ is not None
1643
+ ]
1644
+ )
1645
+
1646
+ if (
1647
+ limit_clause is not None
1648
+ and self.dialect.optimize_limits
1649
+ and select._simple_int_clause(limit_clause)
1650
+ ):
1651
+ limitselect = limitselect.prefix_with(
1652
+ expression.text(
1653
+ "/*+ FIRST_ROWS(%s) */"
1654
+ % self.process(limit_clause, **kwargs)
1655
+ )
1656
+ )
1657
+
1658
+ limitselect._oracle_visit = True
1659
+ limitselect._is_wrapper = True
1660
+
1661
+ # add expressions to accommodate FOR UPDATE OF
1662
+ if for_update is not None and for_update.of:
1663
+ adapter = sql_util.ClauseAdapter(inner_subquery)
1664
+ for_update.of = [
1665
+ adapter.traverse(elem) for elem in for_update.of
1666
+ ]
1667
+
1668
+ # If needed, add the limiting clause
1669
+ if limit_clause is not None:
1670
+ if select._simple_int_clause(limit_clause) and (
1671
+ offset_clause is None
1672
+ or select._simple_int_clause(offset_clause)
1673
+ ):
1674
+ max_row = limit_clause
1675
+
1676
+ if offset_clause is not None:
1677
+ max_row = max_row + offset_clause
1678
+
1679
+ else:
1680
+ max_row = limit_clause
1681
+
1682
+ if offset_clause is not None:
1683
+ max_row = max_row + offset_clause
1684
+ limitselect = limitselect.where(
1685
+ sql.literal_column("ROWNUM") <= max_row
1686
+ )
1687
+
1688
+ # If needed, add the ora_rn, and wrap again with offset.
1689
+ if offset_clause is None:
1690
+ limitselect._for_update_arg = for_update
1691
+ select = limitselect
1692
+ else:
1693
+ limitselect = limitselect.add_columns(
1694
+ sql.literal_column("ROWNUM").label("ora_rn")
1695
+ )
1696
+ limitselect._oracle_visit = True
1697
+ limitselect._is_wrapper = True
1698
+
1699
+ if for_update is not None and for_update.of:
1700
+ limitselect_cols = limitselect.selected_columns
1701
+ for elem in for_update.of:
1702
+ if (
1703
+ limitselect_cols.corresponding_column(elem)
1704
+ is None
1705
+ ):
1706
+ limitselect = limitselect.add_columns(elem)
1707
+
1708
+ limit_subquery = limitselect.alias()
1709
+ origselect_cols = orig_select.selected_columns
1710
+ offsetselect = sql.select(
1711
+ *[
1712
+ c
1713
+ for c in limit_subquery.c
1714
+ if origselect_cols.corresponding_column(c)
1715
+ is not None
1716
+ ]
1717
+ )
1718
+
1719
+ offsetselect._oracle_visit = True
1720
+ offsetselect._is_wrapper = True
1721
+
1722
+ if for_update is not None and for_update.of:
1723
+ adapter = sql_util.ClauseAdapter(limit_subquery)
1724
+ for_update.of = [
1725
+ adapter.traverse(elem) for elem in for_update.of
1726
+ ]
1727
+
1728
+ offsetselect = offsetselect.where(
1729
+ sql.literal_column("ora_rn") > offset_clause
1730
+ )
1731
+
1732
+ offsetselect._for_update_arg = for_update
1733
+ select = offsetselect
1734
+
1735
+ return select
1736
+
1737
+ def limit_clause(self, select, **kw):
1738
+ return ""
1739
+
1740
+ def visit_empty_set_expr(self, type_, **kw):
1741
+ return "SELECT 1 FROM DUAL WHERE 1!=1"
1742
+
1743
+ def for_update_clause(self, select, **kw):
1744
+ if self.is_subquery():
1745
+ return ""
1746
+
1747
+ tmp = " FOR UPDATE"
1748
+
1749
+ if select._for_update_arg.of:
1750
+ tmp += " OF " + ", ".join(
1751
+ self.process(elem, **kw) for elem in select._for_update_arg.of
1752
+ )
1753
+
1754
+ if select._for_update_arg.nowait:
1755
+ tmp += " NOWAIT"
1756
+ if select._for_update_arg.skip_locked:
1757
+ tmp += " SKIP LOCKED"
1758
+
1759
+ return tmp
1760
+
1761
+ def visit_is_distinct_from_binary(self, binary, operator, **kw):
1762
+ return "DECODE(%s, %s, 0, 1) = 1" % (
1763
+ self.process(binary.left),
1764
+ self.process(binary.right),
1765
+ )
1766
+
1767
+ def visit_is_not_distinct_from_binary(self, binary, operator, **kw):
1768
+ return "DECODE(%s, %s, 0, 1) = 0" % (
1769
+ self.process(binary.left),
1770
+ self.process(binary.right),
1771
+ )
1772
+
1773
+ def visit_regexp_match_op_binary(self, binary, operator, **kw):
1774
+ string = self.process(binary.left, **kw)
1775
+ pattern = self.process(binary.right, **kw)
1776
+ flags = binary.modifiers["flags"]
1777
+ if flags is None:
1778
+ return "REGEXP_LIKE(%s, %s)" % (string, pattern)
1779
+ else:
1780
+ return "REGEXP_LIKE(%s, %s, %s)" % (
1781
+ string,
1782
+ pattern,
1783
+ self.render_literal_value(flags, sqltypes.STRINGTYPE),
1784
+ )
1785
+
1786
+ def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
1787
+ return "NOT %s" % self.visit_regexp_match_op_binary(
1788
+ binary, operator, **kw
1789
+ )
1790
+
1791
+ def visit_regexp_replace_op_binary(self, binary, operator, **kw):
1792
+ string = self.process(binary.left, **kw)
1793
+ pattern_replace = self.process(binary.right, **kw)
1794
+ flags = binary.modifiers["flags"]
1795
+ if flags is None:
1796
+ return "REGEXP_REPLACE(%s, %s)" % (
1797
+ string,
1798
+ pattern_replace,
1799
+ )
1800
+ else:
1801
+ return "REGEXP_REPLACE(%s, %s, %s)" % (
1802
+ string,
1803
+ pattern_replace,
1804
+ self.render_literal_value(flags, sqltypes.STRINGTYPE),
1805
+ )
1806
+
1807
+ def visit_aggregate_strings_func(self, fn, **kw):
1808
+ return super().visit_aggregate_strings_func(
1809
+ fn, use_function_name="LISTAGG", **kw
1810
+ )
1811
+
1812
+ def _visit_bitwise(self, binary, fn_name, custom_right=None, **kw):
1813
+ left = self.process(binary.left, **kw)
1814
+ right = self.process(
1815
+ custom_right if custom_right is not None else binary.right, **kw
1816
+ )
1817
+ return f"{fn_name}({left}, {right})"
1818
+
1819
+ def visit_bitwise_xor_op_binary(self, binary, operator, **kw):
1820
+ return self._visit_bitwise(binary, "BITXOR", **kw)
1821
+
1822
+ def visit_bitwise_or_op_binary(self, binary, operator, **kw):
1823
+ return self._visit_bitwise(binary, "BITOR", **kw)
1824
+
1825
+ def visit_bitwise_and_op_binary(self, binary, operator, **kw):
1826
+ return self._visit_bitwise(binary, "BITAND", **kw)
1827
+
1828
+ def visit_bitwise_rshift_op_binary(self, binary, operator, **kw):
1829
+ raise exc.CompileError("Cannot compile bitwise_rshift in oracle")
1830
+
1831
+ def visit_bitwise_lshift_op_binary(self, binary, operator, **kw):
1832
+ raise exc.CompileError("Cannot compile bitwise_lshift in oracle")
1833
+
1834
+ def visit_bitwise_not_op_unary_operator(self, element, operator, **kw):
1835
+ raise exc.CompileError("Cannot compile bitwise_not in oracle")
1836
+
1837
+ def _render_json_extract_from_binary(self, binary, operator, **kw):
1838
+ literal_kw = kw.copy()
1839
+ literal_kw["literal_binds"] = True
1840
+
1841
+ left = self.process(binary.left, **kw)
1842
+ right = self.process(binary.right, **literal_kw)
1843
+
1844
+ if binary.type._type_affinity is sqltypes.Boolean:
1845
+ # RETURNING clause doesn't handle true/false to 1/0
1846
+ # mapping, so use CASE expression for boolean
1847
+ return (
1848
+ f"CASE JSON_VALUE({left}, {right})"
1849
+ f" WHEN 'true' THEN 1"
1850
+ f" WHEN 'false' THEN 0"
1851
+ f" ELSE CAST(JSON_VALUE({left}, {right})"
1852
+ f" AS NUMBER(1)) END"
1853
+ )
1854
+ elif binary.type._type_affinity is sqltypes.Integer:
1855
+ json_value_returning = "INTEGER"
1856
+ elif binary.type._type_affinity in (
1857
+ sqltypes.Numeric,
1858
+ sqltypes.Float,
1859
+ ):
1860
+ if isinstance(binary.type, sqltypes.Float):
1861
+ json_value_returning = "FLOAT"
1862
+ else:
1863
+ json_value_returning = (
1864
+ f"NUMBER({binary.type.precision}, {binary.type.scale})"
1865
+ )
1866
+ elif binary.type._type_affinity is sqltypes.String:
1867
+ json_value_returning = "VARCHAR2(4000)"
1868
+ else:
1869
+ # binary.type._type_affinity is sqltypes.JSON
1870
+ # or other
1871
+ return f"JSON_QUERY({left}, {right})"
1872
+
1873
+ return (
1874
+ f"JSON_VALUE({left}, {right}"
1875
+ f" RETURNING {json_value_returning} ERROR ON ERROR)"
1876
+ )
1877
+
1878
+ def visit_json_getitem_op_binary(
1879
+ self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
1880
+ ) -> str:
1881
+ return self._render_json_extract_from_binary(binary, operator, **kw)
1882
+
1883
+ def visit_json_path_getitem_op_binary(
1884
+ self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
1885
+ ) -> str:
1886
+ return self._render_json_extract_from_binary(binary, operator, **kw)
1887
+
1888
+
1889
+ class OracleDDLCompiler(compiler.DDLCompiler):
1890
+
1891
+ def _build_vector_index_config(
1892
+ self, vector_index_config: VectorIndexConfig
1893
+ ) -> str:
1894
+ parts = []
1895
+ sql_param_name = {
1896
+ "hnsw_neighbors": "neighbors",
1897
+ "hnsw_efconstruction": "efconstruction",
1898
+ "ivf_neighbor_partitions": "neighbor partitions",
1899
+ "ivf_sample_per_partition": "sample_per_partition",
1900
+ "ivf_min_vectors_per_partition": "min_vectors_per_partition",
1901
+ }
1902
+ if vector_index_config.index_type == VectorIndexType.HNSW:
1903
+ parts.append("ORGANIZATION INMEMORY NEIGHBOR GRAPH")
1904
+ elif vector_index_config.index_type == VectorIndexType.IVF:
1905
+ parts.append("ORGANIZATION NEIGHBOR PARTITIONS")
1906
+ if vector_index_config.distance is not None:
1907
+ parts.append(f"DISTANCE {vector_index_config.distance.value}")
1908
+
1909
+ if vector_index_config.accuracy is not None:
1910
+ parts.append(
1911
+ f"WITH TARGET ACCURACY {vector_index_config.accuracy}"
1912
+ )
1913
+
1914
+ parameters_str = [f"type {vector_index_config.index_type.name}"]
1915
+ prefix = vector_index_config.index_type.name.lower() + "_"
1916
+
1917
+ for field in fields(vector_index_config):
1918
+ if field.name.startswith(prefix):
1919
+ key = sql_param_name.get(field.name)
1920
+ value = getattr(vector_index_config, field.name)
1921
+ if value is not None:
1922
+ parameters_str.append(f"{key} {value}")
1923
+
1924
+ parameters_str = ", ".join(parameters_str)
1925
+ parts.append(f"PARAMETERS ({parameters_str})")
1926
+
1927
+ if vector_index_config.parallel is not None:
1928
+ parts.append(f"PARALLEL {vector_index_config.parallel}")
1929
+
1930
+ return " ".join(parts)
1931
+
1932
+ def define_constraint_cascades(self, constraint):
1933
+ text = ""
1934
+ if constraint.ondelete is not None:
1935
+ text += " ON DELETE %s" % constraint.ondelete
1936
+
1937
+ # oracle has no ON UPDATE CASCADE -
1938
+ # its only available via triggers
1939
+ # https://web.archive.org/web/20090317041251/https://asktom.oracle.com/tkyte/update_cascade/index.html
1940
+ if constraint.onupdate is not None:
1941
+ util.warn(
1942
+ "Oracle Database does not contain native UPDATE CASCADE "
1943
+ "functionality - onupdates will not be rendered for foreign "
1944
+ "keys. Consider using deferrable=True, initially='deferred' "
1945
+ "or triggers."
1946
+ )
1947
+
1948
+ return text
1949
+
1950
+ def visit_drop_table_comment(self, drop, **kw):
1951
+ return "COMMENT ON TABLE %s IS ''" % self.preparer.format_table(
1952
+ drop.element
1953
+ )
1954
+
1955
+ def visit_create_index(self, create, **kw):
1956
+ index = create.element
1957
+ self._verify_index_table(index)
1958
+ preparer = self.preparer
1959
+ text = "CREATE "
1960
+ if index.unique:
1961
+ text += "UNIQUE "
1962
+ if index.dialect_options["oracle"]["bitmap"]:
1963
+ text += "BITMAP "
1964
+ vector_options = index.dialect_options["oracle"]["vector"]
1965
+ if vector_options:
1966
+ text += "VECTOR "
1967
+ text += "INDEX %s ON %s (%s)" % (
1968
+ self._prepared_index_name(index, include_schema=True),
1969
+ preparer.format_table(index.table, use_schema=True),
1970
+ ", ".join(
1971
+ self.sql_compiler.process(
1972
+ expr, include_table=False, literal_binds=True
1973
+ )
1974
+ for expr in index.expressions
1975
+ ),
1976
+ )
1977
+ if index.dialect_options["oracle"]["compress"] is not False:
1978
+ if index.dialect_options["oracle"]["compress"] is True:
1979
+ text += " COMPRESS"
1980
+ else:
1981
+ text += " COMPRESS %d" % (
1982
+ index.dialect_options["oracle"]["compress"]
1983
+ )
1984
+ if vector_options:
1985
+ if vector_options is True:
1986
+ vector_options = VectorIndexConfig()
1987
+
1988
+ text += " " + self._build_vector_index_config(vector_options)
1989
+ return text
1990
+
1991
+ def post_create_table(self, table):
1992
+ table_opts = []
1993
+ opts = table.dialect_options["oracle"]
1994
+
1995
+ if opts["on_commit"]:
1996
+ on_commit_options = opts["on_commit"].replace("_", " ").upper()
1997
+ table_opts.append("\n ON COMMIT %s" % on_commit_options)
1998
+
1999
+ if opts["compress"]:
2000
+ if opts["compress"] is True:
2001
+ table_opts.append("\n COMPRESS")
2002
+ else:
2003
+ table_opts.append("\n COMPRESS FOR %s" % (opts["compress"]))
2004
+ if opts["tablespace"]:
2005
+ table_opts.append(
2006
+ "\n TABLESPACE %s" % self.preparer.quote(opts["tablespace"])
2007
+ )
2008
+ return "".join(table_opts)
2009
+
2010
+ def get_identity_options(self, identity_options):
2011
+ text = super().get_identity_options(identity_options)
2012
+ text = text.replace("NO MINVALUE", "NOMINVALUE")
2013
+ text = text.replace("NO MAXVALUE", "NOMAXVALUE")
2014
+ text = text.replace("NO CYCLE", "NOCYCLE")
2015
+ options = identity_options.dialect_options["oracle"]
2016
+ if options.get("order") is not None:
2017
+ text += " ORDER" if options["order"] else " NOORDER"
2018
+ return text.strip()
2019
+
2020
+ def visit_computed_column(self, generated, **kw):
2021
+ text = "GENERATED ALWAYS AS (%s)" % self.sql_compiler.process(
2022
+ generated.sqltext, include_table=False, literal_binds=True
2023
+ )
2024
+ if generated.persisted is True:
2025
+ raise exc.CompileError(
2026
+ "Oracle Database computed columns do not support 'stored' "
2027
+ "persistence; set the 'persisted' flag to None or False for "
2028
+ "Oracle Database support."
2029
+ )
2030
+ elif generated.persisted is False:
2031
+ text += " VIRTUAL"
2032
+ return text
2033
+
2034
+ def visit_identity_column(self, identity, **kw):
2035
+ if identity.always is None:
2036
+ kind = ""
2037
+ else:
2038
+ kind = "ALWAYS" if identity.always else "BY DEFAULT"
2039
+ text = "GENERATED %s" % kind
2040
+ if identity.dialect_options["oracle"].get("on_null"):
2041
+ text += " ON NULL"
2042
+ text += " AS IDENTITY"
2043
+ options = self.get_identity_options(identity)
2044
+ if options:
2045
+ text += " (%s)" % options
2046
+ return text
2047
+
2048
+
2049
+ class OracleIdentifierPreparer(compiler.IdentifierPreparer):
2050
+ reserved_words = {x.lower() for x in RESERVED_WORDS}
2051
+ illegal_initial_characters = {str(dig) for dig in range(0, 10)}.union(
2052
+ ["_", "$"]
2053
+ )
2054
+
2055
+ def _bindparam_requires_quotes(self, value):
2056
+ """Return True if the given identifier requires quoting."""
2057
+ lc_value = value.lower()
2058
+ return (
2059
+ lc_value in self.reserved_words
2060
+ or value[0] in self.illegal_initial_characters
2061
+ or not self.legal_characters.match(str(value))
2062
+ )
2063
+
2064
+ def format_savepoint(self, savepoint):
2065
+ name = savepoint.ident.lstrip("_")
2066
+ return super().format_savepoint(savepoint, name)
2067
+
2068
+
2069
+ class OracleExecutionContext(default.DefaultExecutionContext):
2070
+ def fire_sequence(self, seq, type_):
2071
+ return self._execute_scalar(
2072
+ "SELECT "
2073
+ + self.identifier_preparer.format_sequence(seq)
2074
+ + ".nextval FROM DUAL",
2075
+ type_,
2076
+ )
2077
+
2078
+ def pre_exec(self):
2079
+ if self.statement and "_oracle_dblink" in self.execution_options:
2080
+ self.statement = self.statement.replace(
2081
+ dictionary.DB_LINK_PLACEHOLDER,
2082
+ self.execution_options["_oracle_dblink"],
2083
+ )
2084
+
2085
+
2086
+ class OracleDialect(default.DefaultDialect):
2087
+ name = "oracle"
2088
+ supports_statement_cache = True
2089
+ supports_alter = True
2090
+ max_identifier_length = 128
2091
+
2092
+ _supports_offset_fetch = True
2093
+
2094
+ insert_returning = True
2095
+ update_returning = True
2096
+ delete_returning = True
2097
+
2098
+ div_is_floordiv = False
2099
+
2100
+ supports_simple_order_by_label = False
2101
+ cte_follows_insert = True
2102
+ returns_native_bytes = True
2103
+
2104
+ supports_native_boolean = True
2105
+ supports_sequences = True
2106
+ sequences_optional = False
2107
+ postfetch_lastrowid = False
2108
+
2109
+ default_paramstyle = "named"
2110
+ colspecs = colspecs
2111
+ ischema_names = ischema_names
2112
+ requires_name_normalize = True
2113
+
2114
+ supports_comments = True
2115
+
2116
+ supports_default_values = False
2117
+ supports_default_metavalue = True
2118
+ supports_empty_insert = False
2119
+ supports_identity_columns = True
2120
+
2121
+ _supports_oracle_json = True
2122
+
2123
+ aggregate_order_by_style = AggregateOrderByStyle.WITHIN_GROUP
2124
+
2125
+ statement_compiler = OracleCompiler
2126
+ ddl_compiler = OracleDDLCompiler
2127
+ type_compiler_cls = OracleTypeCompiler
2128
+ preparer = OracleIdentifierPreparer
2129
+ execution_ctx_cls = OracleExecutionContext
2130
+
2131
+ reflection_options = ("oracle_resolve_synonyms",)
2132
+
2133
+ _use_nchar_for_unicode = False
2134
+
2135
+ construct_arguments = [
2136
+ (
2137
+ sa_schema.Table,
2138
+ {
2139
+ "resolve_synonyms": False,
2140
+ "on_commit": None,
2141
+ "compress": False,
2142
+ "tablespace": None,
2143
+ },
2144
+ ),
2145
+ (
2146
+ sa_schema.Index,
2147
+ {
2148
+ "bitmap": False,
2149
+ "compress": False,
2150
+ "vector": False,
2151
+ },
2152
+ ),
2153
+ (sa_schema.Sequence, {"order": None}),
2154
+ (sa_schema.Identity, {"order": None, "on_null": None}),
2155
+ (sa_selectable.Select, {"fetch_approximate": False}),
2156
+ (sa_selectable.CompoundSelect, {"fetch_approximate": False}),
2157
+ ]
2158
+
2159
+ @util.deprecated_params(
2160
+ use_binds_for_limits=(
2161
+ "1.4",
2162
+ "The ``use_binds_for_limits`` Oracle Database dialect parameter "
2163
+ "is deprecated. The dialect now renders LIMIT / OFFSET integers "
2164
+ "inline in all cases using a post-compilation hook, so that the "
2165
+ "value is still represented by a 'bound parameter' on the Core "
2166
+ "Expression side.",
2167
+ )
2168
+ )
2169
+ def __init__(
2170
+ self,
2171
+ use_ansi=True,
2172
+ optimize_limits=False,
2173
+ use_binds_for_limits=None,
2174
+ use_nchar_for_unicode=False,
2175
+ exclude_tablespaces=("SYSTEM", "SYSAUX"),
2176
+ enable_offset_fetch=True,
2177
+ json_serializer: Callable[[_JSON_VALUE], str] | None = None,
2178
+ json_deserializer: Callable[[str], _JSON_VALUE] | None = None,
2179
+ **kwargs,
2180
+ ):
2181
+ default.DefaultDialect.__init__(self, **kwargs)
2182
+ self._use_nchar_for_unicode = use_nchar_for_unicode
2183
+ self.use_ansi = use_ansi
2184
+ self.optimize_limits = optimize_limits
2185
+ self.exclude_tablespaces = exclude_tablespaces
2186
+ self.enable_offset_fetch = self._supports_offset_fetch = (
2187
+ enable_offset_fetch
2188
+ )
2189
+ self._json_serializer = json_serializer
2190
+ self._json_deserializer = json_deserializer
2191
+
2192
+ def initialize(self, connection):
2193
+ super().initialize(connection)
2194
+
2195
+ # Oracle 8i has RETURNING:
2196
+ # https://docs.oracle.com/cd/A87860_01/doc/index.htm
2197
+
2198
+ # so does Oracle8:
2199
+ # https://docs.oracle.com/cd/A64702_01/doc/index.htm
2200
+
2201
+ if self._is_oracle_8:
2202
+ self.colspecs = self.colspecs.copy()
2203
+ self.colspecs.pop(sqltypes.Interval)
2204
+ self.use_ansi = False
2205
+
2206
+ self._supports_oracle_json = self.server_version_info >= (21,)
2207
+ self.supports_native_boolean = self.server_version_info >= (23,)
2208
+ self.supports_identity_columns = self.server_version_info >= (12,)
2209
+ self._supports_offset_fetch = (
2210
+ self.enable_offset_fetch and self.server_version_info >= (12,)
2211
+ )
2212
+
2213
+ def _get_effective_compat_server_version_info(self, connection):
2214
+ # dialect does not need compat levels below 12.2, so don't query
2215
+ # in those cases
2216
+
2217
+ if self.server_version_info < (12, 2):
2218
+ return self.server_version_info
2219
+ try:
2220
+ compat = connection.exec_driver_sql(
2221
+ "SELECT value FROM v$parameter WHERE name = 'compatible'"
2222
+ ).scalar()
2223
+ except exc.DBAPIError:
2224
+ compat = None
2225
+
2226
+ if compat:
2227
+ try:
2228
+ return tuple(int(x) for x in compat.split("."))
2229
+ except:
2230
+ return self.server_version_info
2231
+ else:
2232
+ return self.server_version_info
2233
+
2234
+ @property
2235
+ def _is_oracle_8(self):
2236
+ return self.server_version_info and self.server_version_info < (9,)
2237
+
2238
+ @property
2239
+ def _supports_table_compression(self):
2240
+ return self.server_version_info and self.server_version_info >= (10, 1)
2241
+
2242
+ @property
2243
+ def _supports_table_compress_for(self):
2244
+ return self.server_version_info and self.server_version_info >= (11,)
2245
+
2246
+ @property
2247
+ def _supports_char_length(self):
2248
+ return not self._is_oracle_8
2249
+
2250
+ @property
2251
+ def _supports_update_returning_computed_cols(self):
2252
+ # on version 18 this error is no longet present while it happens on 11
2253
+ # it may work also on versions before the 18
2254
+ return self.server_version_info and self.server_version_info >= (18,)
2255
+
2256
+ @property
2257
+ def _supports_except_all(self):
2258
+ return self.server_version_info and self.server_version_info >= (21,)
2259
+
2260
+ def do_release_savepoint(self, connection, name):
2261
+ # Oracle does not support RELEASE SAVEPOINT
2262
+ pass
2263
+
2264
+ def _check_max_identifier_length(self, connection):
2265
+ if self._get_effective_compat_server_version_info(connection) < (
2266
+ 12,
2267
+ 2,
2268
+ ):
2269
+ return 30
2270
+ else:
2271
+ # use the default
2272
+ return None
2273
+
2274
+ def get_isolation_level_values(self, dbapi_connection):
2275
+ return ["READ COMMITTED", "SERIALIZABLE"]
2276
+
2277
+ def get_default_isolation_level(self, dbapi_conn):
2278
+ try:
2279
+ return self.get_isolation_level(dbapi_conn)
2280
+ except NotImplementedError:
2281
+ raise
2282
+ except:
2283
+ return "READ COMMITTED"
2284
+
2285
+ def _execute_reflection(
2286
+ self, connection, query, dblink, returns_long, params=None
2287
+ ):
2288
+ if dblink and not dblink.startswith("@"):
2289
+ dblink = f"@{dblink}"
2290
+ execution_options = {
2291
+ # handle db links
2292
+ "_oracle_dblink": dblink or "",
2293
+ # override any schema translate map
2294
+ "schema_translate_map": None,
2295
+ }
2296
+
2297
+ if dblink and returns_long:
2298
+ # Oracle seems to error with
2299
+ # "ORA-00997: illegal use of LONG datatype" when returning
2300
+ # LONG columns via a dblink in a query with bind params
2301
+ # This type seems to be very hard to cast into something else
2302
+ # so it seems easier to just use bind param in this case
2303
+ def visit_bindparam(bindparam):
2304
+ bindparam.literal_execute = True
2305
+
2306
+ query = visitors.cloned_traverse(
2307
+ query, {}, {"bindparam": visit_bindparam}
2308
+ )
2309
+ return connection.execute(
2310
+ query, params, execution_options=execution_options
2311
+ )
2312
+
2313
+ @util.memoized_property
2314
+ def _has_table_query(self):
2315
+ # materialized views are returned by all_tables
2316
+ tables = (
2317
+ select(
2318
+ dictionary.all_tables.c.table_name,
2319
+ dictionary.all_tables.c.owner,
2320
+ )
2321
+ .union_all(
2322
+ select(
2323
+ dictionary.all_views.c.view_name.label("table_name"),
2324
+ dictionary.all_views.c.owner,
2325
+ )
2326
+ )
2327
+ .subquery("tables_and_views")
2328
+ )
2329
+
2330
+ query = select(tables.c.table_name).where(
2331
+ tables.c.table_name == bindparam("table_name"),
2332
+ tables.c.owner == bindparam("owner"),
2333
+ )
2334
+ return query
2335
+
2336
+ @reflection.cache
2337
+ def has_table(
2338
+ self, connection, table_name, schema=None, dblink=None, **kw
2339
+ ):
2340
+ """Supported kw arguments are: ``dblink`` to reflect via a db link."""
2341
+ self._ensure_has_table_connection(connection)
2342
+
2343
+ if not schema:
2344
+ schema = self.default_schema_name
2345
+
2346
+ params = {
2347
+ "table_name": self.denormalize_name(table_name),
2348
+ "owner": self.denormalize_schema_name(schema),
2349
+ }
2350
+ cursor = self._execute_reflection(
2351
+ connection,
2352
+ self._has_table_query,
2353
+ dblink,
2354
+ returns_long=False,
2355
+ params=params,
2356
+ )
2357
+ return bool(cursor.scalar())
2358
+
2359
+ @reflection.cache
2360
+ def has_sequence(
2361
+ self, connection, sequence_name, schema=None, dblink=None, **kw
2362
+ ):
2363
+ """Supported kw arguments are: ``dblink`` to reflect via a db link."""
2364
+ if not schema:
2365
+ schema = self.default_schema_name
2366
+
2367
+ query = select(dictionary.all_sequences.c.sequence_name).where(
2368
+ dictionary.all_sequences.c.sequence_name
2369
+ == self.denormalize_schema_name(sequence_name),
2370
+ dictionary.all_sequences.c.sequence_owner
2371
+ == self.denormalize_schema_name(schema),
2372
+ )
2373
+
2374
+ cursor = self._execute_reflection(
2375
+ connection, query, dblink, returns_long=False
2376
+ )
2377
+ return bool(cursor.scalar())
2378
+
2379
+ def _get_default_schema_name(self, connection):
2380
+ return self.normalize_name(
2381
+ connection.exec_driver_sql(
2382
+ "select sys_context( 'userenv', 'current_schema' ) from dual"
2383
+ ).scalar()
2384
+ )
2385
+
2386
+ def denormalize_schema_name(self, name):
2387
+ # look for quoted_name
2388
+ force = getattr(name, "quote", None)
2389
+ if force is None and name == "public":
2390
+ # look for case insensitive, no quoting specified, "public"
2391
+ return "PUBLIC"
2392
+ return super().denormalize_name(name)
2393
+
2394
+ @reflection.flexi_cache(
2395
+ ("schema", InternalTraversal.dp_string),
2396
+ ("filter_names", InternalTraversal.dp_string_list),
2397
+ ("dblink", InternalTraversal.dp_string),
2398
+ )
2399
+ def _get_synonyms(self, connection, schema, filter_names, dblink, **kw):
2400
+ owner = self.denormalize_schema_name(
2401
+ schema or self.default_schema_name
2402
+ )
2403
+
2404
+ has_filter_names, params = self._prepare_filter_names(filter_names)
2405
+ query = select(
2406
+ dictionary.all_synonyms.c.synonym_name,
2407
+ dictionary.all_synonyms.c.table_name,
2408
+ dictionary.all_synonyms.c.table_owner,
2409
+ dictionary.all_synonyms.c.db_link,
2410
+ ).where(dictionary.all_synonyms.c.owner == owner)
2411
+ if has_filter_names:
2412
+ query = query.where(
2413
+ dictionary.all_synonyms.c.synonym_name.in_(
2414
+ params["filter_names"]
2415
+ )
2416
+ )
2417
+ result = self._execute_reflection(
2418
+ connection, query, dblink, returns_long=False
2419
+ ).mappings()
2420
+ return result.all()
2421
+
2422
+ @lru_cache()
2423
+ def _all_objects_query(
2424
+ self, owner, scope, kind, has_filter_names, has_mat_views
2425
+ ):
2426
+ query = (
2427
+ select(dictionary.all_objects.c.object_name)
2428
+ .select_from(dictionary.all_objects)
2429
+ .where(dictionary.all_objects.c.owner == owner)
2430
+ )
2431
+
2432
+ # NOTE: materialized views are listed in all_objects twice;
2433
+ # once as MATERIALIZE VIEW and once as TABLE
2434
+ if kind is ObjectKind.ANY:
2435
+ # materilaized view are listed also as tables so there is no
2436
+ # need to add them to the in_.
2437
+ query = query.where(
2438
+ dictionary.all_objects.c.object_type.in_(("TABLE", "VIEW"))
2439
+ )
2440
+ else:
2441
+ object_type = []
2442
+ if ObjectKind.VIEW in kind:
2443
+ object_type.append("VIEW")
2444
+ if (
2445
+ ObjectKind.MATERIALIZED_VIEW in kind
2446
+ and ObjectKind.TABLE not in kind
2447
+ ):
2448
+ # materilaized view are listed also as tables so there is no
2449
+ # need to add them to the in_ if also selecting tables.
2450
+ object_type.append("MATERIALIZED VIEW")
2451
+ if ObjectKind.TABLE in kind:
2452
+ object_type.append("TABLE")
2453
+ if has_mat_views and ObjectKind.MATERIALIZED_VIEW not in kind:
2454
+ # materialized view are listed also as tables,
2455
+ # so they need to be filtered out
2456
+ # EXCEPT ALL / MINUS profiles as faster than using
2457
+ # NOT EXISTS or NOT IN with a subquery, but it's in
2458
+ # general faster to get the mat view names and exclude
2459
+ # them only when needed
2460
+ query = query.where(
2461
+ dictionary.all_objects.c.object_name.not_in(
2462
+ bindparam("mat_views")
2463
+ )
2464
+ )
2465
+ query = query.where(
2466
+ dictionary.all_objects.c.object_type.in_(object_type)
2467
+ )
2468
+
2469
+ # handles scope
2470
+ if scope is ObjectScope.DEFAULT:
2471
+ query = query.where(dictionary.all_objects.c.temporary == "N")
2472
+ elif scope is ObjectScope.TEMPORARY:
2473
+ query = query.where(dictionary.all_objects.c.temporary == "Y")
2474
+
2475
+ if has_filter_names:
2476
+ query = query.where(
2477
+ dictionary.all_objects.c.object_name.in_(
2478
+ bindparam("filter_names")
2479
+ )
2480
+ )
2481
+ return query
2482
+
2483
+ @reflection.flexi_cache(
2484
+ ("schema", InternalTraversal.dp_string),
2485
+ ("scope", InternalTraversal.dp_plain_obj),
2486
+ ("kind", InternalTraversal.dp_plain_obj),
2487
+ ("filter_names", InternalTraversal.dp_string_list),
2488
+ ("dblink", InternalTraversal.dp_string),
2489
+ )
2490
+ def _get_all_objects(
2491
+ self, connection, schema, scope, kind, filter_names, dblink, **kw
2492
+ ):
2493
+ owner = self.denormalize_schema_name(
2494
+ schema or self.default_schema_name
2495
+ )
2496
+
2497
+ has_filter_names, params = self._prepare_filter_names(filter_names)
2498
+ has_mat_views = False
2499
+ if (
2500
+ ObjectKind.TABLE in kind
2501
+ and ObjectKind.MATERIALIZED_VIEW not in kind
2502
+ ):
2503
+ # see note in _all_objects_query
2504
+ mat_views = self.get_materialized_view_names(
2505
+ connection, schema, dblink, _normalize=False, **kw
2506
+ )
2507
+ if mat_views:
2508
+ params["mat_views"] = mat_views
2509
+ has_mat_views = True
2510
+
2511
+ query = self._all_objects_query(
2512
+ owner, scope, kind, has_filter_names, has_mat_views
2513
+ )
2514
+
2515
+ result = self._execute_reflection(
2516
+ connection, query, dblink, returns_long=False, params=params
2517
+ ).scalars()
2518
+
2519
+ return result.all()
2520
+
2521
+ def _handle_synonyms_decorator(fn):
2522
+ @wraps(fn)
2523
+ def wrapper(self, *args, **kwargs):
2524
+ return self._handle_synonyms(fn, *args, **kwargs)
2525
+
2526
+ return wrapper
2527
+
2528
+ def _handle_synonyms(self, fn, connection, *args, **kwargs):
2529
+ if not kwargs.get("oracle_resolve_synonyms", False):
2530
+ return fn(self, connection, *args, **kwargs)
2531
+
2532
+ original_kw = kwargs.copy()
2533
+ schema = kwargs.pop("schema", None)
2534
+ result = self._get_synonyms(
2535
+ connection,
2536
+ schema=schema,
2537
+ filter_names=kwargs.pop("filter_names", None),
2538
+ dblink=kwargs.pop("dblink", None),
2539
+ info_cache=kwargs.get("info_cache", None),
2540
+ )
2541
+
2542
+ dblinks_owners = defaultdict(dict)
2543
+ for row in result:
2544
+ key = row["db_link"], row["table_owner"]
2545
+ tn = self.normalize_name(row["table_name"])
2546
+ dblinks_owners[key][tn] = row["synonym_name"]
2547
+
2548
+ if not dblinks_owners:
2549
+ # No synonym, do the plain thing
2550
+ return fn(self, connection, *args, **original_kw)
2551
+
2552
+ data = {}
2553
+ for (dblink, table_owner), mapping in dblinks_owners.items():
2554
+ call_kw = {
2555
+ **original_kw,
2556
+ "schema": table_owner,
2557
+ "dblink": self.normalize_name(dblink),
2558
+ "filter_names": mapping.keys(),
2559
+ }
2560
+ call_result = fn(self, connection, *args, **call_kw)
2561
+ for (_, tn), value in call_result:
2562
+ synonym_name = self.normalize_name(mapping[tn])
2563
+ data[(schema, synonym_name)] = value
2564
+ return data.items()
2565
+
2566
+ @reflection.cache
2567
+ def get_schema_names(self, connection, dblink=None, **kw):
2568
+ """Supported kw arguments are: ``dblink`` to reflect via a db link."""
2569
+ query = select(dictionary.all_users.c.username).order_by(
2570
+ dictionary.all_users.c.username
2571
+ )
2572
+ result = self._execute_reflection(
2573
+ connection, query, dblink, returns_long=False
2574
+ ).scalars()
2575
+ return [self.normalize_name(row) for row in result]
2576
+
2577
+ @reflection.cache
2578
+ def get_table_names(self, connection, schema=None, dblink=None, **kw):
2579
+ """Supported kw arguments are: ``dblink`` to reflect via a db link."""
2580
+ # note that table_names() isn't loading DBLINKed or synonym'ed tables
2581
+ if schema is None:
2582
+ schema = self.default_schema_name
2583
+
2584
+ den_schema = self.denormalize_schema_name(schema)
2585
+ if kw.get("oracle_resolve_synonyms", False):
2586
+ tables = (
2587
+ select(
2588
+ dictionary.all_tables.c.table_name,
2589
+ dictionary.all_tables.c.owner,
2590
+ dictionary.all_tables.c.iot_name,
2591
+ dictionary.all_tables.c.duration,
2592
+ dictionary.all_tables.c.tablespace_name,
2593
+ )
2594
+ .union_all(
2595
+ select(
2596
+ dictionary.all_synonyms.c.synonym_name.label(
2597
+ "table_name"
2598
+ ),
2599
+ dictionary.all_synonyms.c.owner,
2600
+ dictionary.all_tables.c.iot_name,
2601
+ dictionary.all_tables.c.duration,
2602
+ dictionary.all_tables.c.tablespace_name,
2603
+ )
2604
+ .select_from(dictionary.all_tables)
2605
+ .join(
2606
+ dictionary.all_synonyms,
2607
+ and_(
2608
+ dictionary.all_tables.c.table_name
2609
+ == dictionary.all_synonyms.c.table_name,
2610
+ dictionary.all_tables.c.owner
2611
+ == func.coalesce(
2612
+ dictionary.all_synonyms.c.table_owner,
2613
+ dictionary.all_synonyms.c.owner,
2614
+ ),
2615
+ ),
2616
+ )
2617
+ )
2618
+ .subquery("available_tables")
2619
+ )
2620
+ else:
2621
+ tables = dictionary.all_tables
2622
+
2623
+ query = select(tables.c.table_name)
2624
+ if self.exclude_tablespaces:
2625
+ query = query.where(
2626
+ func.coalesce(
2627
+ tables.c.tablespace_name, "no tablespace"
2628
+ ).not_in(self.exclude_tablespaces)
2629
+ )
2630
+ query = query.where(
2631
+ tables.c.owner == den_schema,
2632
+ tables.c.iot_name.is_(null()),
2633
+ tables.c.duration.is_(null()),
2634
+ )
2635
+
2636
+ # remove materialized views
2637
+ mat_query = select(
2638
+ dictionary.all_mviews.c.mview_name.label("table_name")
2639
+ ).where(dictionary.all_mviews.c.owner == den_schema)
2640
+
2641
+ query = (
2642
+ query.except_all(mat_query)
2643
+ if self._supports_except_all
2644
+ else query.except_(mat_query)
2645
+ )
2646
+
2647
+ result = self._execute_reflection(
2648
+ connection, query, dblink, returns_long=False
2649
+ ).scalars()
2650
+ return [self.normalize_name(row) for row in result]
2651
+
2652
+ @reflection.cache
2653
+ def get_temp_table_names(self, connection, dblink=None, **kw):
2654
+ """Supported kw arguments are: ``dblink`` to reflect via a db link."""
2655
+ schema = self.denormalize_schema_name(self.default_schema_name)
2656
+
2657
+ query = select(dictionary.all_tables.c.table_name)
2658
+ if self.exclude_tablespaces:
2659
+ query = query.where(
2660
+ func.coalesce(
2661
+ dictionary.all_tables.c.tablespace_name, "no tablespace"
2662
+ ).not_in(self.exclude_tablespaces)
2663
+ )
2664
+ query = query.where(
2665
+ dictionary.all_tables.c.owner == schema,
2666
+ dictionary.all_tables.c.iot_name.is_(null()),
2667
+ dictionary.all_tables.c.duration.is_not(null()),
2668
+ )
2669
+
2670
+ result = self._execute_reflection(
2671
+ connection, query, dblink, returns_long=False
2672
+ ).scalars()
2673
+ return [self.normalize_name(row) for row in result]
2674
+
2675
+ @reflection.cache
2676
+ def get_materialized_view_names(
2677
+ self, connection, schema=None, dblink=None, _normalize=True, **kw
2678
+ ):
2679
+ """Supported kw arguments are: ``dblink`` to reflect via a db link."""
2680
+ if not schema:
2681
+ schema = self.default_schema_name
2682
+
2683
+ query = select(dictionary.all_mviews.c.mview_name).where(
2684
+ dictionary.all_mviews.c.owner
2685
+ == self.denormalize_schema_name(schema)
2686
+ )
2687
+ result = self._execute_reflection(
2688
+ connection, query, dblink, returns_long=False
2689
+ ).scalars()
2690
+ if _normalize:
2691
+ return [self.normalize_name(row) for row in result]
2692
+ else:
2693
+ return result.all()
2694
+
2695
+ @reflection.cache
2696
+ def get_view_names(self, connection, schema=None, dblink=None, **kw):
2697
+ """Supported kw arguments are: ``dblink`` to reflect via a db link."""
2698
+ if not schema:
2699
+ schema = self.default_schema_name
2700
+
2701
+ query = select(dictionary.all_views.c.view_name).where(
2702
+ dictionary.all_views.c.owner
2703
+ == self.denormalize_schema_name(schema)
2704
+ )
2705
+ result = self._execute_reflection(
2706
+ connection, query, dblink, returns_long=False
2707
+ ).scalars()
2708
+ return [self.normalize_name(row) for row in result]
2709
+
2710
+ @reflection.cache
2711
+ def get_sequence_names(self, connection, schema=None, dblink=None, **kw):
2712
+ """Supported kw arguments are: ``dblink`` to reflect via a db link."""
2713
+ if not schema:
2714
+ schema = self.default_schema_name
2715
+ query = select(dictionary.all_sequences.c.sequence_name).where(
2716
+ dictionary.all_sequences.c.sequence_owner
2717
+ == self.denormalize_schema_name(schema)
2718
+ )
2719
+
2720
+ result = self._execute_reflection(
2721
+ connection, query, dblink, returns_long=False
2722
+ ).scalars()
2723
+ return [self.normalize_name(row) for row in result]
2724
+
2725
+ def _value_or_raise(self, data, table, schema):
2726
+ table = self.normalize_name(str(table))
2727
+ try:
2728
+ return dict(data)[(schema, table)]
2729
+ except KeyError:
2730
+ raise exc.NoSuchTableError(
2731
+ f"{schema}.{table}" if schema else table
2732
+ ) from None
2733
+
2734
+ def _prepare_filter_names(self, filter_names):
2735
+ if filter_names:
2736
+ fn = [self.denormalize_name(name) for name in filter_names]
2737
+ return True, {"filter_names": fn}
2738
+ else:
2739
+ return False, {}
2740
+
2741
+ @reflection.cache
2742
+ def get_table_options(self, connection, table_name, schema=None, **kw):
2743
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
2744
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
2745
+ """
2746
+ data = self.get_multi_table_options(
2747
+ connection,
2748
+ schema=schema,
2749
+ filter_names=[table_name],
2750
+ scope=ObjectScope.ANY,
2751
+ kind=ObjectKind.ANY,
2752
+ **kw,
2753
+ )
2754
+ return self._value_or_raise(data, table_name, schema)
2755
+
2756
+ @lru_cache()
2757
+ def _table_options_query(
2758
+ self, owner, scope, kind, has_filter_names, has_mat_views
2759
+ ):
2760
+ query = select(
2761
+ dictionary.all_tables.c.table_name,
2762
+ (
2763
+ dictionary.all_tables.c.compression
2764
+ if self._supports_table_compression
2765
+ else sql.null().label("compression")
2766
+ ),
2767
+ (
2768
+ dictionary.all_tables.c.compress_for
2769
+ if self._supports_table_compress_for
2770
+ else sql.null().label("compress_for")
2771
+ ),
2772
+ dictionary.all_tables.c.tablespace_name,
2773
+ ).where(dictionary.all_tables.c.owner == owner)
2774
+ if has_filter_names:
2775
+ query = query.where(
2776
+ dictionary.all_tables.c.table_name.in_(
2777
+ bindparam("filter_names")
2778
+ )
2779
+ )
2780
+ if scope is ObjectScope.DEFAULT:
2781
+ query = query.where(dictionary.all_tables.c.duration.is_(null()))
2782
+ elif scope is ObjectScope.TEMPORARY:
2783
+ query = query.where(
2784
+ dictionary.all_tables.c.duration.is_not(null())
2785
+ )
2786
+
2787
+ if (
2788
+ has_mat_views
2789
+ and ObjectKind.TABLE in kind
2790
+ and ObjectKind.MATERIALIZED_VIEW not in kind
2791
+ ):
2792
+ # can't use EXCEPT ALL / MINUS here because we don't have an
2793
+ # excludable row vs. the query above
2794
+ # outerjoin + where null works better on oracle 21 but 11 does
2795
+ # not like it at all. this is the next best thing
2796
+
2797
+ query = query.where(
2798
+ dictionary.all_tables.c.table_name.not_in(
2799
+ bindparam("mat_views")
2800
+ )
2801
+ )
2802
+ elif (
2803
+ ObjectKind.TABLE not in kind
2804
+ and ObjectKind.MATERIALIZED_VIEW in kind
2805
+ ):
2806
+ query = query.where(
2807
+ dictionary.all_tables.c.table_name.in_(bindparam("mat_views"))
2808
+ )
2809
+ return query
2810
+
2811
+ @_handle_synonyms_decorator
2812
+ def get_multi_table_options(
2813
+ self,
2814
+ connection,
2815
+ *,
2816
+ schema,
2817
+ filter_names,
2818
+ scope,
2819
+ kind,
2820
+ dblink=None,
2821
+ **kw,
2822
+ ):
2823
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
2824
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
2825
+ """
2826
+ owner = self.denormalize_schema_name(
2827
+ schema or self.default_schema_name
2828
+ )
2829
+
2830
+ has_filter_names, params = self._prepare_filter_names(filter_names)
2831
+ has_mat_views = False
2832
+
2833
+ if (
2834
+ ObjectKind.TABLE in kind
2835
+ and ObjectKind.MATERIALIZED_VIEW not in kind
2836
+ ):
2837
+ # see note in _table_options_query
2838
+ mat_views = self.get_materialized_view_names(
2839
+ connection, schema, dblink, _normalize=False, **kw
2840
+ )
2841
+ if mat_views:
2842
+ params["mat_views"] = mat_views
2843
+ has_mat_views = True
2844
+ elif (
2845
+ ObjectKind.TABLE not in kind
2846
+ and ObjectKind.MATERIALIZED_VIEW in kind
2847
+ ):
2848
+ mat_views = self.get_materialized_view_names(
2849
+ connection, schema, dblink, _normalize=False, **kw
2850
+ )
2851
+ params["mat_views"] = mat_views
2852
+
2853
+ options = {}
2854
+ default = ReflectionDefaults.table_options
2855
+
2856
+ if ObjectKind.TABLE in kind or ObjectKind.MATERIALIZED_VIEW in kind:
2857
+ query = self._table_options_query(
2858
+ owner, scope, kind, has_filter_names, has_mat_views
2859
+ )
2860
+ result = self._execute_reflection(
2861
+ connection, query, dblink, returns_long=False, params=params
2862
+ )
2863
+
2864
+ for table, compression, compress_for, tablespace in result:
2865
+ data = default()
2866
+ if compression == "ENABLED":
2867
+ data["oracle_compress"] = compress_for
2868
+ if tablespace:
2869
+ data["oracle_tablespace"] = tablespace
2870
+ options[(schema, self.normalize_name(table))] = data
2871
+ if ObjectKind.VIEW in kind and ObjectScope.DEFAULT in scope:
2872
+ # add the views (no temporary views)
2873
+ for view in self.get_view_names(connection, schema, dblink, **kw):
2874
+ if not filter_names or view in filter_names:
2875
+ options[(schema, view)] = default()
2876
+
2877
+ return options.items()
2878
+
2879
+ @reflection.cache
2880
+ def get_columns(self, connection, table_name, schema=None, **kw):
2881
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
2882
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
2883
+ """
2884
+
2885
+ data = self.get_multi_columns(
2886
+ connection,
2887
+ schema=schema,
2888
+ filter_names=[table_name],
2889
+ scope=ObjectScope.ANY,
2890
+ kind=ObjectKind.ANY,
2891
+ **kw,
2892
+ )
2893
+ return self._value_or_raise(data, table_name, schema)
2894
+
2895
+ def _run_batches(
2896
+ self, connection, query, dblink, returns_long, mappings, all_objects
2897
+ ):
2898
+ each_batch = 500
2899
+ batches = list(all_objects)
2900
+ while batches:
2901
+ batch = batches[0:each_batch]
2902
+ batches[0:each_batch] = []
2903
+
2904
+ result = self._execute_reflection(
2905
+ connection,
2906
+ query,
2907
+ dblink,
2908
+ returns_long=returns_long,
2909
+ params={"all_objects": batch},
2910
+ )
2911
+ if mappings:
2912
+ yield from result.mappings()
2913
+ else:
2914
+ yield from result
2915
+
2916
+ @lru_cache()
2917
+ def _column_query(self, owner):
2918
+ all_cols = dictionary.all_tab_cols
2919
+ all_comments = dictionary.all_col_comments
2920
+ all_ids = dictionary.all_tab_identity_cols
2921
+
2922
+ if self.server_version_info >= (12,):
2923
+ add_cols = (
2924
+ all_cols.c.default_on_null,
2925
+ sql.case(
2926
+ (all_ids.c.table_name.is_(None), sql.null()),
2927
+ else_=all_ids.c.generation_type
2928
+ + ","
2929
+ + all_ids.c.identity_options,
2930
+ ).label("identity_options"),
2931
+ )
2932
+ join_identity_cols = True
2933
+ else:
2934
+ add_cols = (
2935
+ sql.null().label("default_on_null"),
2936
+ sql.null().label("identity_options"),
2937
+ )
2938
+ join_identity_cols = False
2939
+
2940
+ # NOTE: on oracle cannot create tables/views without columns and
2941
+ # a table cannot have all column hidden:
2942
+ # ORA-54039: table must have at least one column that is not invisible
2943
+ # all_tab_cols returns data for tables/views/mat-views.
2944
+ # all_tab_cols does not return recycled tables
2945
+
2946
+ query = (
2947
+ select(
2948
+ all_cols.c.table_name,
2949
+ all_cols.c.column_name,
2950
+ all_cols.c.data_type,
2951
+ all_cols.c.char_length,
2952
+ all_cols.c.data_length,
2953
+ all_cols.c.data_precision,
2954
+ all_cols.c.data_scale,
2955
+ all_cols.c.nullable,
2956
+ all_cols.c.data_default,
2957
+ all_comments.c.comments,
2958
+ all_cols.c.virtual_column,
2959
+ *add_cols,
2960
+ ).select_from(all_cols)
2961
+ # NOTE: all_col_comments has a row for each column even if no
2962
+ # comment is present, so a join could be performed, but there
2963
+ # seems to be no difference compared to an outer join
2964
+ .outerjoin(
2965
+ all_comments,
2966
+ and_(
2967
+ all_cols.c.table_name == all_comments.c.table_name,
2968
+ all_cols.c.column_name == all_comments.c.column_name,
2969
+ all_cols.c.owner == all_comments.c.owner,
2970
+ ),
2971
+ )
2972
+ )
2973
+ if join_identity_cols:
2974
+ query = query.outerjoin(
2975
+ all_ids,
2976
+ and_(
2977
+ all_cols.c.table_name == all_ids.c.table_name,
2978
+ all_cols.c.column_name == all_ids.c.column_name,
2979
+ all_cols.c.owner == all_ids.c.owner,
2980
+ ),
2981
+ )
2982
+
2983
+ query = query.where(
2984
+ all_cols.c.table_name.in_(bindparam("all_objects")),
2985
+ all_cols.c.hidden_column == "NO",
2986
+ all_cols.c.owner == owner,
2987
+ ).order_by(all_cols.c.table_name, all_cols.c.column_id)
2988
+ return query
2989
+
2990
+ @_handle_synonyms_decorator
2991
+ def get_multi_columns(
2992
+ self,
2993
+ connection,
2994
+ *,
2995
+ schema,
2996
+ filter_names,
2997
+ scope,
2998
+ kind,
2999
+ dblink=None,
3000
+ **kw,
3001
+ ):
3002
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3003
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3004
+ """
3005
+ owner = self.denormalize_schema_name(
3006
+ schema or self.default_schema_name
3007
+ )
3008
+ query = self._column_query(owner)
3009
+
3010
+ if (
3011
+ filter_names
3012
+ and kind is ObjectKind.ANY
3013
+ and scope is ObjectScope.ANY
3014
+ ):
3015
+ all_objects = [self.denormalize_name(n) for n in filter_names]
3016
+ else:
3017
+ all_objects = self._get_all_objects(
3018
+ connection, schema, scope, kind, filter_names, dblink, **kw
3019
+ )
3020
+
3021
+ columns = defaultdict(list)
3022
+
3023
+ # all_tab_cols.data_default is LONG
3024
+ result = self._run_batches(
3025
+ connection,
3026
+ query,
3027
+ dblink,
3028
+ returns_long=True,
3029
+ mappings=True,
3030
+ all_objects=all_objects,
3031
+ )
3032
+
3033
+ def maybe_int(value):
3034
+ if isinstance(value, float) and value.is_integer():
3035
+ return int(value)
3036
+ else:
3037
+ return value
3038
+
3039
+ remove_size = re.compile(r"\(\d+\)")
3040
+
3041
+ for row_dict in result:
3042
+ table_name = self.normalize_name(row_dict["table_name"])
3043
+ orig_colname = row_dict["column_name"]
3044
+ colname = self.normalize_name(orig_colname)
3045
+ coltype = row_dict["data_type"]
3046
+ precision = maybe_int(row_dict["data_precision"])
3047
+
3048
+ if coltype == "NUMBER":
3049
+ scale = maybe_int(row_dict["data_scale"])
3050
+ if precision is None and scale == 0:
3051
+ coltype = INTEGER()
3052
+ else:
3053
+ coltype = NUMBER(precision, scale)
3054
+ elif coltype == "FLOAT":
3055
+ # https://docs.oracle.com/cd/B14117_01/server.101/b10758/sqlqr06.htm
3056
+ if precision == 126:
3057
+ # The DOUBLE PRECISION datatype is a floating-point
3058
+ # number with binary precision 126.
3059
+ coltype = DOUBLE_PRECISION()
3060
+ elif precision == 63:
3061
+ # The REAL datatype is a floating-point number with a
3062
+ # binary precision of 63, or 18 decimal.
3063
+ coltype = REAL()
3064
+ else:
3065
+ # non standard precision
3066
+ coltype = FLOAT(binary_precision=precision)
3067
+
3068
+ elif coltype in ("VARCHAR2", "NVARCHAR2", "CHAR", "NCHAR"):
3069
+ char_length = maybe_int(row_dict["char_length"])
3070
+ coltype = self.ischema_names.get(coltype)(char_length)
3071
+ elif coltype == "RAW":
3072
+ data_length = maybe_int(row_dict["data_length"])
3073
+ coltype = RAW(data_length)
3074
+ elif "WITH TIME ZONE" in coltype:
3075
+ coltype = TIMESTAMP(timezone=True)
3076
+ elif "WITH LOCAL TIME ZONE" in coltype:
3077
+ coltype = TIMESTAMP(local_timezone=True)
3078
+ else:
3079
+ coltype = re.sub(remove_size, "", coltype)
3080
+ try:
3081
+ coltype = self.ischema_names[coltype]
3082
+ except KeyError:
3083
+ util.warn(
3084
+ "Did not recognize type '%s' of column '%s'"
3085
+ % (coltype, colname)
3086
+ )
3087
+ coltype = sqltypes.NULLTYPE
3088
+
3089
+ default = row_dict["data_default"]
3090
+ if row_dict["virtual_column"] == "YES":
3091
+ computed = dict(sqltext=default)
3092
+ default = None
3093
+ else:
3094
+ computed = None
3095
+
3096
+ identity_options = row_dict["identity_options"]
3097
+ if identity_options is not None:
3098
+ identity = self._parse_identity_options(
3099
+ identity_options, row_dict["default_on_null"]
3100
+ )
3101
+ default = None
3102
+ else:
3103
+ identity = None
3104
+
3105
+ cdict = {
3106
+ "name": colname,
3107
+ "type": coltype,
3108
+ "nullable": row_dict["nullable"] == "Y",
3109
+ "default": default,
3110
+ "comment": row_dict["comments"],
3111
+ }
3112
+ if orig_colname.lower() == orig_colname:
3113
+ cdict["quote"] = True
3114
+ if computed is not None:
3115
+ cdict["computed"] = computed
3116
+ if identity is not None:
3117
+ cdict["identity"] = identity
3118
+
3119
+ columns[(schema, table_name)].append(cdict)
3120
+
3121
+ # NOTE: default not needed since all tables have columns
3122
+ # default = ReflectionDefaults.columns
3123
+ # return (
3124
+ # (key, value if value else default())
3125
+ # for key, value in columns.items()
3126
+ # )
3127
+ return columns.items()
3128
+
3129
+ def _parse_identity_options(self, identity_options, default_on_null):
3130
+ # identity_options is a string that starts with 'ALWAYS,' or
3131
+ # 'BY DEFAULT,' and continues with
3132
+ # START WITH: 1, INCREMENT BY: 1, MAX_VALUE: 123, MIN_VALUE: 1,
3133
+ # CYCLE_FLAG: N, CACHE_SIZE: 1, ORDER_FLAG: N, SCALE_FLAG: N,
3134
+ # EXTEND_FLAG: N, SESSION_FLAG: N, KEEP_VALUE: N
3135
+ parts = [p.strip() for p in identity_options.split(",")]
3136
+ identity = {
3137
+ "always": parts[0] == "ALWAYS",
3138
+ "oracle_on_null": default_on_null == "YES",
3139
+ }
3140
+
3141
+ for part in parts[1:]:
3142
+ option, value = part.split(":")
3143
+ value = value.strip()
3144
+
3145
+ if "START WITH" in option:
3146
+ identity["start"] = int(value)
3147
+ elif "INCREMENT BY" in option:
3148
+ identity["increment"] = int(value)
3149
+ elif "MAX_VALUE" in option:
3150
+ identity["maxvalue"] = int(value)
3151
+ elif "MIN_VALUE" in option:
3152
+ identity["minvalue"] = int(value)
3153
+ elif "CYCLE_FLAG" in option:
3154
+ identity["cycle"] = value == "Y"
3155
+ elif "CACHE_SIZE" in option:
3156
+ identity["cache"] = int(value)
3157
+ elif "ORDER_FLAG" in option:
3158
+ identity["oracle_order"] = value == "Y"
3159
+ return identity
3160
+
3161
+ @reflection.cache
3162
+ def get_table_comment(self, connection, table_name, schema=None, **kw):
3163
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3164
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3165
+ """
3166
+ data = self.get_multi_table_comment(
3167
+ connection,
3168
+ schema=schema,
3169
+ filter_names=[table_name],
3170
+ scope=ObjectScope.ANY,
3171
+ kind=ObjectKind.ANY,
3172
+ **kw,
3173
+ )
3174
+ return self._value_or_raise(data, table_name, schema)
3175
+
3176
+ @lru_cache()
3177
+ def _comment_query(self, owner, scope, kind, has_filter_names):
3178
+ # NOTE: all_tab_comments / all_mview_comments have a row for all
3179
+ # object even if they don't have comments
3180
+ queries = []
3181
+ if ObjectKind.TABLE in kind or ObjectKind.VIEW in kind:
3182
+ # all_tab_comments returns also plain views
3183
+ tbl_view = select(
3184
+ dictionary.all_tab_comments.c.table_name,
3185
+ dictionary.all_tab_comments.c.comments,
3186
+ ).where(
3187
+ dictionary.all_tab_comments.c.owner == owner,
3188
+ dictionary.all_tab_comments.c.table_name.not_like("BIN$%"),
3189
+ )
3190
+ if ObjectKind.VIEW not in kind:
3191
+ tbl_view = tbl_view.where(
3192
+ dictionary.all_tab_comments.c.table_type == "TABLE"
3193
+ )
3194
+ elif ObjectKind.TABLE not in kind:
3195
+ tbl_view = tbl_view.where(
3196
+ dictionary.all_tab_comments.c.table_type == "VIEW"
3197
+ )
3198
+ queries.append(tbl_view)
3199
+ if ObjectKind.MATERIALIZED_VIEW in kind:
3200
+ mat_view = select(
3201
+ dictionary.all_mview_comments.c.mview_name.label("table_name"),
3202
+ dictionary.all_mview_comments.c.comments,
3203
+ ).where(
3204
+ dictionary.all_mview_comments.c.owner == owner,
3205
+ dictionary.all_mview_comments.c.mview_name.not_like("BIN$%"),
3206
+ )
3207
+ queries.append(mat_view)
3208
+ if len(queries) == 1:
3209
+ query = queries[0]
3210
+ else:
3211
+ union = sql.union_all(*queries).subquery("tables_and_views")
3212
+ query = select(union.c.table_name, union.c.comments)
3213
+
3214
+ name_col = query.selected_columns.table_name
3215
+
3216
+ if scope in (ObjectScope.DEFAULT, ObjectScope.TEMPORARY):
3217
+ temp = "Y" if scope is ObjectScope.TEMPORARY else "N"
3218
+ # need distinct since materialized view are listed also
3219
+ # as tables in all_objects
3220
+ query = query.distinct().join(
3221
+ dictionary.all_objects,
3222
+ and_(
3223
+ dictionary.all_objects.c.owner == owner,
3224
+ dictionary.all_objects.c.object_name == name_col,
3225
+ dictionary.all_objects.c.temporary == temp,
3226
+ ),
3227
+ )
3228
+ if has_filter_names:
3229
+ query = query.where(name_col.in_(bindparam("filter_names")))
3230
+ return query
3231
+
3232
+ @_handle_synonyms_decorator
3233
+ def get_multi_table_comment(
3234
+ self,
3235
+ connection,
3236
+ *,
3237
+ schema,
3238
+ filter_names,
3239
+ scope,
3240
+ kind,
3241
+ dblink=None,
3242
+ **kw,
3243
+ ):
3244
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3245
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3246
+ """
3247
+ owner = self.denormalize_schema_name(
3248
+ schema or self.default_schema_name
3249
+ )
3250
+ has_filter_names, params = self._prepare_filter_names(filter_names)
3251
+ query = self._comment_query(owner, scope, kind, has_filter_names)
3252
+
3253
+ result = self._execute_reflection(
3254
+ connection, query, dblink, returns_long=False, params=params
3255
+ )
3256
+ default = ReflectionDefaults.table_comment
3257
+ # materialized views by default seem to have a comment like
3258
+ # "snapshot table for snapshot owner.mat_view_name"
3259
+ ignore_mat_view = "snapshot table for snapshot "
3260
+ return (
3261
+ (
3262
+ (schema, self.normalize_name(table)),
3263
+ (
3264
+ {"text": comment}
3265
+ if comment is not None
3266
+ and not comment.startswith(ignore_mat_view)
3267
+ else default()
3268
+ ),
3269
+ )
3270
+ for table, comment in result
3271
+ )
3272
+
3273
+ @reflection.cache
3274
+ def get_indexes(self, connection, table_name, schema=None, **kw):
3275
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3276
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3277
+ """
3278
+ data = self.get_multi_indexes(
3279
+ connection,
3280
+ schema=schema,
3281
+ filter_names=[table_name],
3282
+ scope=ObjectScope.ANY,
3283
+ kind=ObjectKind.ANY,
3284
+ **kw,
3285
+ )
3286
+ return self._value_or_raise(data, table_name, schema)
3287
+
3288
+ @lru_cache()
3289
+ def _index_query(self, owner):
3290
+ return (
3291
+ select(
3292
+ dictionary.all_ind_columns.c.table_name,
3293
+ dictionary.all_ind_columns.c.index_name,
3294
+ dictionary.all_ind_columns.c.column_name,
3295
+ dictionary.all_indexes.c.index_type,
3296
+ dictionary.all_indexes.c.uniqueness,
3297
+ dictionary.all_indexes.c.compression,
3298
+ dictionary.all_indexes.c.prefix_length,
3299
+ dictionary.all_ind_columns.c.descend,
3300
+ dictionary.all_ind_expressions.c.column_expression,
3301
+ )
3302
+ .select_from(dictionary.all_ind_columns)
3303
+ .join(
3304
+ dictionary.all_indexes,
3305
+ sql.and_(
3306
+ dictionary.all_ind_columns.c.index_name
3307
+ == dictionary.all_indexes.c.index_name,
3308
+ dictionary.all_ind_columns.c.index_owner
3309
+ == dictionary.all_indexes.c.owner,
3310
+ ),
3311
+ )
3312
+ .outerjoin(
3313
+ # NOTE: this adds about 20% to the query time. Using a
3314
+ # case expression with a scalar subquery only when needed
3315
+ # with the assumption that most indexes are not expression
3316
+ # would be faster but oracle does not like that with
3317
+ # LONG datatype. It errors with:
3318
+ # ORA-00997: illegal use of LONG datatype
3319
+ dictionary.all_ind_expressions,
3320
+ sql.and_(
3321
+ dictionary.all_ind_expressions.c.index_name
3322
+ == dictionary.all_ind_columns.c.index_name,
3323
+ dictionary.all_ind_expressions.c.index_owner
3324
+ == dictionary.all_ind_columns.c.index_owner,
3325
+ dictionary.all_ind_expressions.c.column_position
3326
+ == dictionary.all_ind_columns.c.column_position,
3327
+ ),
3328
+ )
3329
+ .where(
3330
+ dictionary.all_indexes.c.table_owner == owner,
3331
+ dictionary.all_indexes.c.table_name.in_(
3332
+ bindparam("all_objects")
3333
+ ),
3334
+ )
3335
+ .order_by(
3336
+ dictionary.all_ind_columns.c.index_name,
3337
+ dictionary.all_ind_columns.c.column_position,
3338
+ )
3339
+ )
3340
+
3341
+ @reflection.flexi_cache(
3342
+ ("schema", InternalTraversal.dp_string),
3343
+ ("dblink", InternalTraversal.dp_string),
3344
+ ("all_objects", InternalTraversal.dp_string_list),
3345
+ )
3346
+ def _get_indexes_rows(self, connection, schema, dblink, all_objects, **kw):
3347
+ owner = self.denormalize_schema_name(
3348
+ schema or self.default_schema_name
3349
+ )
3350
+
3351
+ query = self._index_query(owner)
3352
+
3353
+ pks = {
3354
+ row_dict["constraint_name"]
3355
+ for row_dict in self._get_all_constraint_rows(
3356
+ connection, schema, dblink, all_objects, **kw
3357
+ )
3358
+ if row_dict["constraint_type"] == "P"
3359
+ }
3360
+
3361
+ # all_ind_expressions.column_expression is LONG
3362
+ result = self._run_batches(
3363
+ connection,
3364
+ query,
3365
+ dblink,
3366
+ returns_long=True,
3367
+ mappings=True,
3368
+ all_objects=all_objects,
3369
+ )
3370
+
3371
+ return [
3372
+ row_dict
3373
+ for row_dict in result
3374
+ if row_dict["index_name"] not in pks
3375
+ ]
3376
+
3377
+ @_handle_synonyms_decorator
3378
+ def get_multi_indexes(
3379
+ self,
3380
+ connection,
3381
+ *,
3382
+ schema,
3383
+ filter_names,
3384
+ scope,
3385
+ kind,
3386
+ dblink=None,
3387
+ **kw,
3388
+ ):
3389
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3390
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3391
+ """
3392
+ all_objects = self._get_all_objects(
3393
+ connection, schema, scope, kind, filter_names, dblink, **kw
3394
+ )
3395
+
3396
+ uniqueness = {"NONUNIQUE": False, "UNIQUE": True}
3397
+ enabled = {"DISABLED": False, "ENABLED": True}
3398
+ is_bitmap = {"BITMAP", "FUNCTION-BASED BITMAP"}
3399
+
3400
+ indexes = defaultdict(dict)
3401
+
3402
+ for row_dict in self._get_indexes_rows(
3403
+ connection, schema, dblink, all_objects, **kw
3404
+ ):
3405
+ index_name = self.normalize_name(row_dict["index_name"])
3406
+ table_name = self.normalize_name(row_dict["table_name"])
3407
+ table_indexes = indexes[(schema, table_name)]
3408
+
3409
+ if index_name not in table_indexes:
3410
+ table_indexes[index_name] = index_dict = {
3411
+ "name": index_name,
3412
+ "column_names": [],
3413
+ "dialect_options": {},
3414
+ "unique": uniqueness.get(row_dict["uniqueness"], False),
3415
+ }
3416
+ do = index_dict["dialect_options"]
3417
+ if row_dict["index_type"] in is_bitmap:
3418
+ do["oracle_bitmap"] = True
3419
+ if enabled.get(row_dict["compression"], False):
3420
+ do["oracle_compress"] = row_dict["prefix_length"]
3421
+
3422
+ else:
3423
+ index_dict = table_indexes[index_name]
3424
+
3425
+ expr = row_dict["column_expression"]
3426
+ if expr is not None:
3427
+ index_dict["column_names"].append(None)
3428
+ if "expressions" in index_dict:
3429
+ index_dict["expressions"].append(expr)
3430
+ else:
3431
+ index_dict["expressions"] = index_dict["column_names"][:-1]
3432
+ index_dict["expressions"].append(expr)
3433
+
3434
+ if row_dict["descend"].lower() != "asc":
3435
+ assert row_dict["descend"].lower() == "desc"
3436
+ cs = index_dict.setdefault("column_sorting", {})
3437
+ cs[expr] = ("desc",)
3438
+ else:
3439
+ assert row_dict["descend"].lower() == "asc"
3440
+ cn = self.normalize_name(row_dict["column_name"])
3441
+ index_dict["column_names"].append(cn)
3442
+ if "expressions" in index_dict:
3443
+ index_dict["expressions"].append(cn)
3444
+
3445
+ default = ReflectionDefaults.indexes
3446
+
3447
+ return (
3448
+ (key, list(indexes[key].values()) if key in indexes else default())
3449
+ for key in (
3450
+ (schema, self.normalize_name(obj_name))
3451
+ for obj_name in all_objects
3452
+ )
3453
+ )
3454
+
3455
+ @reflection.cache
3456
+ def get_pk_constraint(self, connection, table_name, schema=None, **kw):
3457
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3458
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3459
+ """
3460
+ data = self.get_multi_pk_constraint(
3461
+ connection,
3462
+ schema=schema,
3463
+ filter_names=[table_name],
3464
+ scope=ObjectScope.ANY,
3465
+ kind=ObjectKind.ANY,
3466
+ **kw,
3467
+ )
3468
+ return self._value_or_raise(data, table_name, schema)
3469
+
3470
+ @lru_cache()
3471
+ def _constraint_query(self, owner):
3472
+ local = dictionary.all_cons_columns.alias("local")
3473
+ remote = dictionary.all_cons_columns.alias("remote")
3474
+ return (
3475
+ select(
3476
+ dictionary.all_constraints.c.table_name,
3477
+ dictionary.all_constraints.c.constraint_type,
3478
+ dictionary.all_constraints.c.constraint_name,
3479
+ local.c.column_name.label("local_column"),
3480
+ remote.c.table_name.label("remote_table"),
3481
+ remote.c.column_name.label("remote_column"),
3482
+ remote.c.owner.label("remote_owner"),
3483
+ dictionary.all_constraints.c.search_condition,
3484
+ dictionary.all_constraints.c.delete_rule,
3485
+ )
3486
+ .select_from(dictionary.all_constraints)
3487
+ .join(
3488
+ local,
3489
+ and_(
3490
+ local.c.owner == dictionary.all_constraints.c.owner,
3491
+ dictionary.all_constraints.c.constraint_name
3492
+ == local.c.constraint_name,
3493
+ ),
3494
+ )
3495
+ .outerjoin(
3496
+ remote,
3497
+ and_(
3498
+ dictionary.all_constraints.c.r_owner == remote.c.owner,
3499
+ dictionary.all_constraints.c.r_constraint_name
3500
+ == remote.c.constraint_name,
3501
+ or_(
3502
+ remote.c.position.is_(sql.null()),
3503
+ local.c.position == remote.c.position,
3504
+ ),
3505
+ ),
3506
+ )
3507
+ .where(
3508
+ dictionary.all_constraints.c.owner == owner,
3509
+ dictionary.all_constraints.c.table_name.in_(
3510
+ bindparam("all_objects")
3511
+ ),
3512
+ dictionary.all_constraints.c.constraint_type.in_(
3513
+ ("R", "P", "U", "C")
3514
+ ),
3515
+ )
3516
+ .order_by(
3517
+ dictionary.all_constraints.c.constraint_name, local.c.position
3518
+ )
3519
+ )
3520
+
3521
+ @reflection.flexi_cache(
3522
+ ("schema", InternalTraversal.dp_string),
3523
+ ("dblink", InternalTraversal.dp_string),
3524
+ ("all_objects", InternalTraversal.dp_string_list),
3525
+ )
3526
+ def _get_all_constraint_rows(
3527
+ self, connection, schema, dblink, all_objects, **kw
3528
+ ):
3529
+ owner = self.denormalize_schema_name(
3530
+ schema or self.default_schema_name
3531
+ )
3532
+ query = self._constraint_query(owner)
3533
+
3534
+ # since the result is cached a list must be created
3535
+ values = list(
3536
+ self._run_batches(
3537
+ connection,
3538
+ query,
3539
+ dblink,
3540
+ returns_long=False,
3541
+ mappings=True,
3542
+ all_objects=all_objects,
3543
+ )
3544
+ )
3545
+ return values
3546
+
3547
+ @_handle_synonyms_decorator
3548
+ def get_multi_pk_constraint(
3549
+ self,
3550
+ connection,
3551
+ *,
3552
+ scope,
3553
+ schema,
3554
+ filter_names,
3555
+ kind,
3556
+ dblink=None,
3557
+ **kw,
3558
+ ):
3559
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3560
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3561
+ """
3562
+ all_objects = self._get_all_objects(
3563
+ connection, schema, scope, kind, filter_names, dblink, **kw
3564
+ )
3565
+
3566
+ primary_keys = defaultdict(dict)
3567
+ default = ReflectionDefaults.pk_constraint
3568
+
3569
+ for row_dict in self._get_all_constraint_rows(
3570
+ connection, schema, dblink, all_objects, **kw
3571
+ ):
3572
+ if row_dict["constraint_type"] != "P":
3573
+ continue
3574
+ table_name = self.normalize_name(row_dict["table_name"])
3575
+ constraint_name = self.normalize_name(row_dict["constraint_name"])
3576
+ column_name = self.normalize_name(row_dict["local_column"])
3577
+
3578
+ table_pk = primary_keys[(schema, table_name)]
3579
+ if not table_pk:
3580
+ table_pk["name"] = constraint_name
3581
+ table_pk["constrained_columns"] = [column_name]
3582
+ else:
3583
+ table_pk["constrained_columns"].append(column_name)
3584
+
3585
+ return (
3586
+ (key, primary_keys[key] if key in primary_keys else default())
3587
+ for key in (
3588
+ (schema, self.normalize_name(obj_name))
3589
+ for obj_name in all_objects
3590
+ )
3591
+ )
3592
+
3593
+ @reflection.cache
3594
+ def get_foreign_keys(
3595
+ self,
3596
+ connection,
3597
+ table_name,
3598
+ schema=None,
3599
+ **kw,
3600
+ ):
3601
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3602
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3603
+ """
3604
+ data = self.get_multi_foreign_keys(
3605
+ connection,
3606
+ schema=schema,
3607
+ filter_names=[table_name],
3608
+ scope=ObjectScope.ANY,
3609
+ kind=ObjectKind.ANY,
3610
+ **kw,
3611
+ )
3612
+ return self._value_or_raise(data, table_name, schema)
3613
+
3614
+ @_handle_synonyms_decorator
3615
+ def get_multi_foreign_keys(
3616
+ self,
3617
+ connection,
3618
+ *,
3619
+ scope,
3620
+ schema,
3621
+ filter_names,
3622
+ kind,
3623
+ dblink=None,
3624
+ **kw,
3625
+ ):
3626
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3627
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3628
+ """
3629
+ all_objects = self._get_all_objects(
3630
+ connection, schema, scope, kind, filter_names, dblink, **kw
3631
+ )
3632
+
3633
+ resolve_synonyms = kw.get("oracle_resolve_synonyms", False)
3634
+
3635
+ owner = self.denormalize_schema_name(
3636
+ schema or self.default_schema_name
3637
+ )
3638
+
3639
+ all_remote_owners = set()
3640
+ fkeys = defaultdict(dict)
3641
+
3642
+ for row_dict in self._get_all_constraint_rows(
3643
+ connection, schema, dblink, all_objects, **kw
3644
+ ):
3645
+ if row_dict["constraint_type"] != "R":
3646
+ continue
3647
+
3648
+ table_name = self.normalize_name(row_dict["table_name"])
3649
+ constraint_name = self.normalize_name(row_dict["constraint_name"])
3650
+ table_fkey = fkeys[(schema, table_name)]
3651
+
3652
+ assert constraint_name is not None
3653
+
3654
+ local_column = self.normalize_name(row_dict["local_column"])
3655
+ remote_table = self.normalize_name(row_dict["remote_table"])
3656
+ remote_column = self.normalize_name(row_dict["remote_column"])
3657
+ remote_owner_orig = row_dict["remote_owner"]
3658
+ remote_owner = self.normalize_name(remote_owner_orig)
3659
+ if remote_owner_orig is not None:
3660
+ all_remote_owners.add(remote_owner_orig)
3661
+
3662
+ if remote_table is None:
3663
+ # ticket 363
3664
+ if dblink and not dblink.startswith("@"):
3665
+ dblink = f"@{dblink}"
3666
+ util.warn(
3667
+ "Got 'None' querying 'table_name' from "
3668
+ f"all_cons_columns{dblink or ''} - does the user have "
3669
+ "proper rights to the table?"
3670
+ )
3671
+ continue
3672
+
3673
+ if constraint_name not in table_fkey:
3674
+ table_fkey[constraint_name] = fkey = {
3675
+ "name": constraint_name,
3676
+ "constrained_columns": [],
3677
+ "referred_schema": None,
3678
+ "referred_table": remote_table,
3679
+ "referred_columns": [],
3680
+ "options": {},
3681
+ }
3682
+
3683
+ if resolve_synonyms:
3684
+ # will be removed below
3685
+ fkey["_ref_schema"] = remote_owner
3686
+
3687
+ if schema is not None or remote_owner_orig != owner:
3688
+ fkey["referred_schema"] = remote_owner
3689
+
3690
+ delete_rule = row_dict["delete_rule"]
3691
+ if delete_rule != "NO ACTION":
3692
+ fkey["options"]["ondelete"] = delete_rule
3693
+
3694
+ else:
3695
+ fkey = table_fkey[constraint_name]
3696
+
3697
+ fkey["constrained_columns"].append(local_column)
3698
+ fkey["referred_columns"].append(remote_column)
3699
+
3700
+ if resolve_synonyms and all_remote_owners:
3701
+ query = select(
3702
+ dictionary.all_synonyms.c.owner,
3703
+ dictionary.all_synonyms.c.table_name,
3704
+ dictionary.all_synonyms.c.table_owner,
3705
+ dictionary.all_synonyms.c.synonym_name,
3706
+ ).where(dictionary.all_synonyms.c.owner.in_(all_remote_owners))
3707
+
3708
+ result = self._execute_reflection(
3709
+ connection, query, dblink, returns_long=False
3710
+ ).mappings()
3711
+
3712
+ remote_owners_lut = {}
3713
+ for row in result:
3714
+ synonym_owner = self.normalize_name(row["owner"])
3715
+ table_name = self.normalize_name(row["table_name"])
3716
+
3717
+ remote_owners_lut[(synonym_owner, table_name)] = (
3718
+ row["table_owner"],
3719
+ row["synonym_name"],
3720
+ )
3721
+
3722
+ empty = (None, None)
3723
+ for table_fkeys in fkeys.values():
3724
+ for table_fkey in table_fkeys.values():
3725
+ key = (
3726
+ table_fkey.pop("_ref_schema"),
3727
+ table_fkey["referred_table"],
3728
+ )
3729
+ remote_owner, syn_name = remote_owners_lut.get(key, empty)
3730
+ if syn_name:
3731
+ sn = self.normalize_name(syn_name)
3732
+ table_fkey["referred_table"] = sn
3733
+ if schema is not None or remote_owner != owner:
3734
+ ro = self.normalize_name(remote_owner)
3735
+ table_fkey["referred_schema"] = ro
3736
+ else:
3737
+ table_fkey["referred_schema"] = None
3738
+ default = ReflectionDefaults.foreign_keys
3739
+
3740
+ return (
3741
+ (key, list(fkeys[key].values()) if key in fkeys else default())
3742
+ for key in (
3743
+ (schema, self.normalize_name(obj_name))
3744
+ for obj_name in all_objects
3745
+ )
3746
+ )
3747
+
3748
+ @reflection.cache
3749
+ def get_unique_constraints(
3750
+ self, connection, table_name, schema=None, **kw
3751
+ ):
3752
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3753
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3754
+ """
3755
+ data = self.get_multi_unique_constraints(
3756
+ connection,
3757
+ schema=schema,
3758
+ filter_names=[table_name],
3759
+ scope=ObjectScope.ANY,
3760
+ kind=ObjectKind.ANY,
3761
+ **kw,
3762
+ )
3763
+ return self._value_or_raise(data, table_name, schema)
3764
+
3765
+ @_handle_synonyms_decorator
3766
+ def get_multi_unique_constraints(
3767
+ self,
3768
+ connection,
3769
+ *,
3770
+ scope,
3771
+ schema,
3772
+ filter_names,
3773
+ kind,
3774
+ dblink=None,
3775
+ **kw,
3776
+ ):
3777
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3778
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3779
+ """
3780
+ all_objects = self._get_all_objects(
3781
+ connection, schema, scope, kind, filter_names, dblink, **kw
3782
+ )
3783
+
3784
+ unique_cons = defaultdict(dict)
3785
+
3786
+ index_names = {
3787
+ row_dict["index_name"]
3788
+ for row_dict in self._get_indexes_rows(
3789
+ connection, schema, dblink, all_objects, **kw
3790
+ )
3791
+ }
3792
+
3793
+ for row_dict in self._get_all_constraint_rows(
3794
+ connection, schema, dblink, all_objects, **kw
3795
+ ):
3796
+ if row_dict["constraint_type"] != "U":
3797
+ continue
3798
+ table_name = self.normalize_name(row_dict["table_name"])
3799
+ constraint_name_orig = row_dict["constraint_name"]
3800
+ constraint_name = self.normalize_name(constraint_name_orig)
3801
+ column_name = self.normalize_name(row_dict["local_column"])
3802
+ table_uc = unique_cons[(schema, table_name)]
3803
+
3804
+ assert constraint_name is not None
3805
+
3806
+ if constraint_name not in table_uc:
3807
+ table_uc[constraint_name] = uc = {
3808
+ "name": constraint_name,
3809
+ "column_names": [],
3810
+ "duplicates_index": (
3811
+ constraint_name
3812
+ if constraint_name_orig in index_names
3813
+ else None
3814
+ ),
3815
+ }
3816
+ else:
3817
+ uc = table_uc[constraint_name]
3818
+
3819
+ uc["column_names"].append(column_name)
3820
+
3821
+ default = ReflectionDefaults.unique_constraints
3822
+
3823
+ return (
3824
+ (
3825
+ key,
3826
+ (
3827
+ list(unique_cons[key].values())
3828
+ if key in unique_cons
3829
+ else default()
3830
+ ),
3831
+ )
3832
+ for key in (
3833
+ (schema, self.normalize_name(obj_name))
3834
+ for obj_name in all_objects
3835
+ )
3836
+ )
3837
+
3838
+ @reflection.cache
3839
+ def get_view_definition(
3840
+ self,
3841
+ connection,
3842
+ view_name,
3843
+ schema=None,
3844
+ dblink=None,
3845
+ **kw,
3846
+ ):
3847
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3848
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3849
+ """
3850
+ if kw.get("oracle_resolve_synonyms", False):
3851
+ synonyms = self._get_synonyms(
3852
+ connection, schema, filter_names=[view_name], dblink=dblink
3853
+ )
3854
+ if synonyms:
3855
+ assert len(synonyms) == 1
3856
+ row_dict = synonyms[0]
3857
+ dblink = self.normalize_name(row_dict["db_link"])
3858
+ schema = row_dict["table_owner"]
3859
+ view_name = row_dict["table_name"]
3860
+
3861
+ name = self.denormalize_name(view_name)
3862
+ owner = self.denormalize_schema_name(
3863
+ schema or self.default_schema_name
3864
+ )
3865
+ query = (
3866
+ select(dictionary.all_views.c.text)
3867
+ .where(
3868
+ dictionary.all_views.c.view_name == name,
3869
+ dictionary.all_views.c.owner == owner,
3870
+ )
3871
+ .union_all(
3872
+ select(dictionary.all_mviews.c.query).where(
3873
+ dictionary.all_mviews.c.mview_name == name,
3874
+ dictionary.all_mviews.c.owner == owner,
3875
+ )
3876
+ )
3877
+ )
3878
+
3879
+ rp = self._execute_reflection(
3880
+ connection, query, dblink, returns_long=False
3881
+ ).scalar()
3882
+ if rp is None:
3883
+ raise exc.NoSuchTableError(
3884
+ f"{schema}.{view_name}" if schema else view_name
3885
+ )
3886
+ else:
3887
+ return rp
3888
+
3889
+ @reflection.cache
3890
+ def get_check_constraints(
3891
+ self, connection, table_name, schema=None, include_all=False, **kw
3892
+ ):
3893
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3894
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3895
+ """
3896
+ data = self.get_multi_check_constraints(
3897
+ connection,
3898
+ schema=schema,
3899
+ filter_names=[table_name],
3900
+ scope=ObjectScope.ANY,
3901
+ include_all=include_all,
3902
+ kind=ObjectKind.ANY,
3903
+ **kw,
3904
+ )
3905
+ return self._value_or_raise(data, table_name, schema)
3906
+
3907
+ @_handle_synonyms_decorator
3908
+ def get_multi_check_constraints(
3909
+ self,
3910
+ connection,
3911
+ *,
3912
+ schema,
3913
+ filter_names,
3914
+ dblink=None,
3915
+ scope,
3916
+ kind,
3917
+ include_all=False,
3918
+ **kw,
3919
+ ):
3920
+ """Supported kw arguments are: ``dblink`` to reflect via a db link;
3921
+ ``oracle_resolve_synonyms`` to resolve names to synonyms
3922
+ """
3923
+ all_objects = self._get_all_objects(
3924
+ connection, schema, scope, kind, filter_names, dblink, **kw
3925
+ )
3926
+
3927
+ not_null = re.compile(r"..+?. IS NOT NULL$")
3928
+
3929
+ check_constraints = defaultdict(list)
3930
+
3931
+ for row_dict in self._get_all_constraint_rows(
3932
+ connection, schema, dblink, all_objects, **kw
3933
+ ):
3934
+ if row_dict["constraint_type"] != "C":
3935
+ continue
3936
+ table_name = self.normalize_name(row_dict["table_name"])
3937
+ constraint_name = self.normalize_name(row_dict["constraint_name"])
3938
+ search_condition = row_dict["search_condition"]
3939
+
3940
+ table_checks = check_constraints[(schema, table_name)]
3941
+ if constraint_name is not None and (
3942
+ include_all or not not_null.match(search_condition)
3943
+ ):
3944
+ table_checks.append(
3945
+ {"name": constraint_name, "sqltext": search_condition}
3946
+ )
3947
+
3948
+ default = ReflectionDefaults.check_constraints
3949
+
3950
+ return (
3951
+ (
3952
+ key,
3953
+ (
3954
+ check_constraints[key]
3955
+ if key in check_constraints
3956
+ else default()
3957
+ ),
3958
+ )
3959
+ for key in (
3960
+ (schema, self.normalize_name(obj_name))
3961
+ for obj_name in all_objects
3962
+ )
3963
+ )
3964
+
3965
+ def _list_dblinks(self, connection, dblink=None):
3966
+ query = select(dictionary.all_db_links.c.db_link)
3967
+ links = self._execute_reflection(
3968
+ connection, query, dblink, returns_long=False
3969
+ ).scalars()
3970
+ return [self.normalize_name(link) for link in links]
3971
+
3972
+
3973
+ class _OuterJoinColumn(sql.ClauseElement):
3974
+ __visit_name__ = "outer_join_column"
3975
+
3976
+ def __init__(self, column):
3977
+ self.column = column