SQLAlchemy 2.1.0b1__cp313-cp313-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (267) hide show
  1. sqlalchemy/__init__.py +295 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +161 -0
  4. sqlalchemy/connectors/asyncio.py +476 -0
  5. sqlalchemy/connectors/pyodbc.py +250 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +30 -0
  8. sqlalchemy/dialects/mssql/__init__.py +88 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4110 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  12. sqlalchemy/dialects/mssql/json.py +129 -0
  13. sqlalchemy/dialects/mssql/provision.py +185 -0
  14. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  15. sqlalchemy/dialects/mssql/pyodbc.py +758 -0
  16. sqlalchemy/dialects/mysql/__init__.py +106 -0
  17. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  18. sqlalchemy/dialects/mysql/aiomysql.py +226 -0
  19. sqlalchemy/dialects/mysql/asyncmy.py +214 -0
  20. sqlalchemy/dialects/mysql/base.py +3870 -0
  21. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  22. sqlalchemy/dialects/mysql/dml.py +279 -0
  23. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  24. sqlalchemy/dialects/mysql/expression.py +146 -0
  25. sqlalchemy/dialects/mysql/json.py +91 -0
  26. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  27. sqlalchemy/dialects/mysql/mariadbconnector.py +330 -0
  28. sqlalchemy/dialects/mysql/mysqlconnector.py +296 -0
  29. sqlalchemy/dialects/mysql/mysqldb.py +312 -0
  30. sqlalchemy/dialects/mysql/provision.py +147 -0
  31. sqlalchemy/dialects/mysql/pymysql.py +157 -0
  32. sqlalchemy/dialects/mysql/pyodbc.py +156 -0
  33. sqlalchemy/dialects/mysql/reflection.py +724 -0
  34. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  35. sqlalchemy/dialects/mysql/types.py +845 -0
  36. sqlalchemy/dialects/oracle/__init__.py +83 -0
  37. sqlalchemy/dialects/oracle/base.py +3871 -0
  38. sqlalchemy/dialects/oracle/cx_oracle.py +1522 -0
  39. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  40. sqlalchemy/dialects/oracle/oracledb.py +894 -0
  41. sqlalchemy/dialects/oracle/provision.py +288 -0
  42. sqlalchemy/dialects/oracle/types.py +350 -0
  43. sqlalchemy/dialects/oracle/vector.py +368 -0
  44. sqlalchemy/dialects/postgresql/__init__.py +171 -0
  45. sqlalchemy/dialects/postgresql/_psycopg_common.py +193 -0
  46. sqlalchemy/dialects/postgresql/array.py +534 -0
  47. sqlalchemy/dialects/postgresql/asyncpg.py +1331 -0
  48. sqlalchemy/dialects/postgresql/base.py +5729 -0
  49. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  50. sqlalchemy/dialects/postgresql/dml.py +360 -0
  51. sqlalchemy/dialects/postgresql/ext.py +593 -0
  52. sqlalchemy/dialects/postgresql/hstore.py +413 -0
  53. sqlalchemy/dialects/postgresql/json.py +407 -0
  54. sqlalchemy/dialects/postgresql/named_types.py +521 -0
  55. sqlalchemy/dialects/postgresql/operators.py +130 -0
  56. sqlalchemy/dialects/postgresql/pg8000.py +672 -0
  57. sqlalchemy/dialects/postgresql/pg_catalog.py +344 -0
  58. sqlalchemy/dialects/postgresql/provision.py +175 -0
  59. sqlalchemy/dialects/postgresql/psycopg.py +815 -0
  60. sqlalchemy/dialects/postgresql/psycopg2.py +887 -0
  61. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  62. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  63. sqlalchemy/dialects/postgresql/types.py +388 -0
  64. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  65. sqlalchemy/dialects/sqlite/aiosqlite.py +321 -0
  66. sqlalchemy/dialects/sqlite/base.py +3050 -0
  67. sqlalchemy/dialects/sqlite/dml.py +279 -0
  68. sqlalchemy/dialects/sqlite/json.py +89 -0
  69. sqlalchemy/dialects/sqlite/provision.py +223 -0
  70. sqlalchemy/dialects/sqlite/pysqlcipher.py +157 -0
  71. sqlalchemy/dialects/sqlite/pysqlite.py +754 -0
  72. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  73. sqlalchemy/engine/__init__.py +62 -0
  74. sqlalchemy/engine/_processors_cy.cp313-win_arm64.pyd +0 -0
  75. sqlalchemy/engine/_processors_cy.py +92 -0
  76. sqlalchemy/engine/_result_cy.cp313-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_result_cy.py +633 -0
  78. sqlalchemy/engine/_row_cy.cp313-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_row_cy.py +232 -0
  80. sqlalchemy/engine/_util_cy.cp313-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_util_cy.py +136 -0
  82. sqlalchemy/engine/base.py +3334 -0
  83. sqlalchemy/engine/characteristics.py +155 -0
  84. sqlalchemy/engine/create.py +869 -0
  85. sqlalchemy/engine/cursor.py +2416 -0
  86. sqlalchemy/engine/default.py +2393 -0
  87. sqlalchemy/engine/events.py +965 -0
  88. sqlalchemy/engine/interfaces.py +3465 -0
  89. sqlalchemy/engine/mock.py +134 -0
  90. sqlalchemy/engine/processors.py +82 -0
  91. sqlalchemy/engine/reflection.py +2100 -0
  92. sqlalchemy/engine/result.py +1932 -0
  93. sqlalchemy/engine/row.py +397 -0
  94. sqlalchemy/engine/strategies.py +16 -0
  95. sqlalchemy/engine/url.py +922 -0
  96. sqlalchemy/engine/util.py +156 -0
  97. sqlalchemy/event/__init__.py +26 -0
  98. sqlalchemy/event/api.py +220 -0
  99. sqlalchemy/event/attr.py +674 -0
  100. sqlalchemy/event/base.py +472 -0
  101. sqlalchemy/event/legacy.py +258 -0
  102. sqlalchemy/event/registry.py +390 -0
  103. sqlalchemy/events.py +17 -0
  104. sqlalchemy/exc.py +922 -0
  105. sqlalchemy/ext/__init__.py +11 -0
  106. sqlalchemy/ext/associationproxy.py +2072 -0
  107. sqlalchemy/ext/asyncio/__init__.py +29 -0
  108. sqlalchemy/ext/asyncio/base.py +281 -0
  109. sqlalchemy/ext/asyncio/engine.py +1475 -0
  110. sqlalchemy/ext/asyncio/exc.py +21 -0
  111. sqlalchemy/ext/asyncio/result.py +994 -0
  112. sqlalchemy/ext/asyncio/scoping.py +1667 -0
  113. sqlalchemy/ext/asyncio/session.py +1993 -0
  114. sqlalchemy/ext/automap.py +1701 -0
  115. sqlalchemy/ext/baked.py +559 -0
  116. sqlalchemy/ext/compiler.py +600 -0
  117. sqlalchemy/ext/declarative/__init__.py +65 -0
  118. sqlalchemy/ext/declarative/extensions.py +560 -0
  119. sqlalchemy/ext/horizontal_shard.py +481 -0
  120. sqlalchemy/ext/hybrid.py +1877 -0
  121. sqlalchemy/ext/indexable.py +364 -0
  122. sqlalchemy/ext/instrumentation.py +450 -0
  123. sqlalchemy/ext/mutable.py +1081 -0
  124. sqlalchemy/ext/orderinglist.py +439 -0
  125. sqlalchemy/ext/serializer.py +185 -0
  126. sqlalchemy/future/__init__.py +16 -0
  127. sqlalchemy/future/engine.py +15 -0
  128. sqlalchemy/inspection.py +174 -0
  129. sqlalchemy/log.py +283 -0
  130. sqlalchemy/orm/__init__.py +175 -0
  131. sqlalchemy/orm/_orm_constructors.py +2694 -0
  132. sqlalchemy/orm/_typing.py +179 -0
  133. sqlalchemy/orm/attributes.py +2868 -0
  134. sqlalchemy/orm/base.py +970 -0
  135. sqlalchemy/orm/bulk_persistence.py +2152 -0
  136. sqlalchemy/orm/clsregistry.py +582 -0
  137. sqlalchemy/orm/collections.py +1568 -0
  138. sqlalchemy/orm/context.py +3471 -0
  139. sqlalchemy/orm/decl_api.py +2257 -0
  140. sqlalchemy/orm/decl_base.py +2304 -0
  141. sqlalchemy/orm/dependency.py +1306 -0
  142. sqlalchemy/orm/descriptor_props.py +1183 -0
  143. sqlalchemy/orm/dynamic.py +300 -0
  144. sqlalchemy/orm/evaluator.py +379 -0
  145. sqlalchemy/orm/events.py +3386 -0
  146. sqlalchemy/orm/exc.py +237 -0
  147. sqlalchemy/orm/identity.py +302 -0
  148. sqlalchemy/orm/instrumentation.py +746 -0
  149. sqlalchemy/orm/interfaces.py +1589 -0
  150. sqlalchemy/orm/loading.py +1684 -0
  151. sqlalchemy/orm/mapped_collection.py +557 -0
  152. sqlalchemy/orm/mapper.py +4406 -0
  153. sqlalchemy/orm/path_registry.py +814 -0
  154. sqlalchemy/orm/persistence.py +1789 -0
  155. sqlalchemy/orm/properties.py +973 -0
  156. sqlalchemy/orm/query.py +3521 -0
  157. sqlalchemy/orm/relationships.py +3570 -0
  158. sqlalchemy/orm/scoping.py +2220 -0
  159. sqlalchemy/orm/session.py +5389 -0
  160. sqlalchemy/orm/state.py +1175 -0
  161. sqlalchemy/orm/state_changes.py +196 -0
  162. sqlalchemy/orm/strategies.py +3480 -0
  163. sqlalchemy/orm/strategy_options.py +2544 -0
  164. sqlalchemy/orm/sync.py +164 -0
  165. sqlalchemy/orm/unitofwork.py +798 -0
  166. sqlalchemy/orm/util.py +2435 -0
  167. sqlalchemy/orm/writeonly.py +694 -0
  168. sqlalchemy/pool/__init__.py +41 -0
  169. sqlalchemy/pool/base.py +1514 -0
  170. sqlalchemy/pool/events.py +372 -0
  171. sqlalchemy/pool/impl.py +582 -0
  172. sqlalchemy/py.typed +0 -0
  173. sqlalchemy/schema.py +72 -0
  174. sqlalchemy/sql/__init__.py +153 -0
  175. sqlalchemy/sql/_dml_constructors.py +132 -0
  176. sqlalchemy/sql/_elements_constructors.py +2147 -0
  177. sqlalchemy/sql/_orm_types.py +20 -0
  178. sqlalchemy/sql/_selectable_constructors.py +773 -0
  179. sqlalchemy/sql/_typing.py +486 -0
  180. sqlalchemy/sql/_util_cy.cp313-win_arm64.pyd +0 -0
  181. sqlalchemy/sql/_util_cy.py +127 -0
  182. sqlalchemy/sql/annotation.py +590 -0
  183. sqlalchemy/sql/base.py +2602 -0
  184. sqlalchemy/sql/cache_key.py +1066 -0
  185. sqlalchemy/sql/coercions.py +1373 -0
  186. sqlalchemy/sql/compiler.py +8259 -0
  187. sqlalchemy/sql/crud.py +1807 -0
  188. sqlalchemy/sql/ddl.py +1928 -0
  189. sqlalchemy/sql/default_comparator.py +654 -0
  190. sqlalchemy/sql/dml.py +1974 -0
  191. sqlalchemy/sql/elements.py +6016 -0
  192. sqlalchemy/sql/events.py +458 -0
  193. sqlalchemy/sql/expression.py +170 -0
  194. sqlalchemy/sql/functions.py +2257 -0
  195. sqlalchemy/sql/lambdas.py +1443 -0
  196. sqlalchemy/sql/naming.py +209 -0
  197. sqlalchemy/sql/operators.py +2897 -0
  198. sqlalchemy/sql/roles.py +332 -0
  199. sqlalchemy/sql/schema.py +6560 -0
  200. sqlalchemy/sql/selectable.py +7497 -0
  201. sqlalchemy/sql/sqltypes.py +4050 -0
  202. sqlalchemy/sql/traversals.py +1042 -0
  203. sqlalchemy/sql/type_api.py +2425 -0
  204. sqlalchemy/sql/util.py +1495 -0
  205. sqlalchemy/sql/visitors.py +1157 -0
  206. sqlalchemy/testing/__init__.py +96 -0
  207. sqlalchemy/testing/assertions.py +1007 -0
  208. sqlalchemy/testing/assertsql.py +519 -0
  209. sqlalchemy/testing/asyncio.py +128 -0
  210. sqlalchemy/testing/config.py +440 -0
  211. sqlalchemy/testing/engines.py +478 -0
  212. sqlalchemy/testing/entities.py +117 -0
  213. sqlalchemy/testing/exclusions.py +476 -0
  214. sqlalchemy/testing/fixtures/__init__.py +30 -0
  215. sqlalchemy/testing/fixtures/base.py +366 -0
  216. sqlalchemy/testing/fixtures/mypy.py +247 -0
  217. sqlalchemy/testing/fixtures/orm.py +227 -0
  218. sqlalchemy/testing/fixtures/sql.py +538 -0
  219. sqlalchemy/testing/pickleable.py +155 -0
  220. sqlalchemy/testing/plugin/__init__.py +6 -0
  221. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  222. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  223. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  224. sqlalchemy/testing/profiling.py +329 -0
  225. sqlalchemy/testing/provision.py +596 -0
  226. sqlalchemy/testing/requirements.py +1973 -0
  227. sqlalchemy/testing/schema.py +198 -0
  228. sqlalchemy/testing/suite/__init__.py +19 -0
  229. sqlalchemy/testing/suite/test_cte.py +237 -0
  230. sqlalchemy/testing/suite/test_ddl.py +420 -0
  231. sqlalchemy/testing/suite/test_dialect.py +776 -0
  232. sqlalchemy/testing/suite/test_insert.py +630 -0
  233. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  234. sqlalchemy/testing/suite/test_results.py +660 -0
  235. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  236. sqlalchemy/testing/suite/test_select.py +2112 -0
  237. sqlalchemy/testing/suite/test_sequence.py +317 -0
  238. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  239. sqlalchemy/testing/suite/test_types.py +2253 -0
  240. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  241. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  242. sqlalchemy/testing/util.py +535 -0
  243. sqlalchemy/testing/warnings.py +52 -0
  244. sqlalchemy/types.py +76 -0
  245. sqlalchemy/util/__init__.py +157 -0
  246. sqlalchemy/util/_collections.py +693 -0
  247. sqlalchemy/util/_collections_cy.cp313-win_arm64.pyd +0 -0
  248. sqlalchemy/util/_collections_cy.pxd +8 -0
  249. sqlalchemy/util/_collections_cy.py +516 -0
  250. sqlalchemy/util/_has_cython.py +46 -0
  251. sqlalchemy/util/_immutabledict_cy.cp313-win_arm64.pyd +0 -0
  252. sqlalchemy/util/_immutabledict_cy.py +240 -0
  253. sqlalchemy/util/compat.py +287 -0
  254. sqlalchemy/util/concurrency.py +322 -0
  255. sqlalchemy/util/cython.py +79 -0
  256. sqlalchemy/util/deprecations.py +401 -0
  257. sqlalchemy/util/langhelpers.py +2256 -0
  258. sqlalchemy/util/preloaded.py +152 -0
  259. sqlalchemy/util/queue.py +304 -0
  260. sqlalchemy/util/tool_support.py +201 -0
  261. sqlalchemy/util/topological.py +120 -0
  262. sqlalchemy/util/typing.py +711 -0
  263. sqlalchemy-2.1.0b1.dist-info/METADATA +267 -0
  264. sqlalchemy-2.1.0b1.dist-info/RECORD +267 -0
  265. sqlalchemy-2.1.0b1.dist-info/WHEEL +5 -0
  266. sqlalchemy-2.1.0b1.dist-info/licenses/LICENSE +19 -0
  267. sqlalchemy-2.1.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1522 @@
1
+ # dialects/oracle/cx_oracle.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""".. dialect:: oracle+cx_oracle
11
+ :name: cx-Oracle
12
+ :dbapi: cx_oracle
13
+ :connectstring: oracle+cx_oracle://user:pass@hostname:port[/dbname][?service_name=<service>[&key=value&key=value...]]
14
+ :url: https://oracle.github.io/python-cx_Oracle/
15
+
16
+ Description
17
+ -----------
18
+
19
+ cx_Oracle was the original driver for Oracle Database. It was superseded by
20
+ python-oracledb which should be used instead.
21
+
22
+ DSN vs. Hostname connections
23
+ -----------------------------
24
+
25
+ cx_Oracle provides several methods of indicating the target database. The
26
+ dialect translates from a series of different URL forms.
27
+
28
+ Hostname Connections with Easy Connect Syntax
29
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
30
+
31
+ Given a hostname, port and service name of the target database, for example
32
+ from Oracle Database's Easy Connect syntax then connect in SQLAlchemy using the
33
+ ``service_name`` query string parameter::
34
+
35
+ engine = create_engine(
36
+ "oracle+cx_oracle://scott:tiger@hostname:port?service_name=myservice&encoding=UTF-8&nencoding=UTF-8"
37
+ )
38
+
39
+ Note that the default driver value for encoding and nencoding was changed to
40
+ “UTF-8” in cx_Oracle 8.0 so these parameters can be omitted when using that
41
+ version, or later.
42
+
43
+ To use a full Easy Connect string, pass it as the ``dsn`` key value in a
44
+ :paramref:`_sa.create_engine.connect_args` dictionary::
45
+
46
+ import cx_Oracle
47
+
48
+ e = create_engine(
49
+ "oracle+cx_oracle://@",
50
+ connect_args={
51
+ "user": "scott",
52
+ "password": "tiger",
53
+ "dsn": "hostname:port/myservice?transport_connect_timeout=30&expire_time=60",
54
+ },
55
+ )
56
+
57
+ Connections with tnsnames.ora or to Oracle Autonomous Database
58
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
59
+
60
+ Alternatively, if no port, database name, or service name is provided, the
61
+ dialect will use an Oracle Database DSN "connection string". This takes the
62
+ "hostname" portion of the URL as the data source name. For example, if the
63
+ ``tnsnames.ora`` file contains a TNS Alias of ``myalias`` as below:
64
+
65
+ .. sourcecode:: text
66
+
67
+ myalias =
68
+ (DESCRIPTION =
69
+ (ADDRESS = (PROTOCOL = TCP)(HOST = mymachine.example.com)(PORT = 1521))
70
+ (CONNECT_DATA =
71
+ (SERVER = DEDICATED)
72
+ (SERVICE_NAME = orclpdb1)
73
+ )
74
+ )
75
+
76
+ The cx_Oracle dialect connects to this database service when ``myalias`` is the
77
+ hostname portion of the URL, without specifying a port, database name or
78
+ ``service_name``::
79
+
80
+ engine = create_engine("oracle+cx_oracle://scott:tiger@myalias")
81
+
82
+ Users of Oracle Autonomous Database should use this syntax. If the database is
83
+ configured for mutural TLS ("mTLS"), then you must also configure the cloud
84
+ wallet as shown in cx_Oracle documentation `Connecting to Autononmous Databases
85
+ <https://cx-oracle.readthedocs.io/en/latest/user_guide/connection_handling.html#autonomousdb>`_.
86
+
87
+ SID Connections
88
+ ^^^^^^^^^^^^^^^
89
+
90
+ To use Oracle Database's obsolete System Identifier connection syntax, the SID
91
+ can be passed in a "database name" portion of the URL::
92
+
93
+ engine = create_engine(
94
+ "oracle+cx_oracle://scott:tiger@hostname:port/dbname"
95
+ )
96
+
97
+ Above, the DSN passed to cx_Oracle is created by ``cx_Oracle.makedsn()`` as
98
+ follows::
99
+
100
+ >>> import cx_Oracle
101
+ >>> cx_Oracle.makedsn("hostname", 1521, sid="dbname")
102
+ '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=hostname)(PORT=1521))(CONNECT_DATA=(SID=dbname)))'
103
+
104
+ Note that although the SQLAlchemy syntax ``hostname:port/dbname`` looks like
105
+ Oracle's Easy Connect syntax it is different. It uses a SID in place of the
106
+ service name required by Easy Connect. The Easy Connect syntax does not
107
+ support SIDs.
108
+
109
+ Passing cx_Oracle connect arguments
110
+ -----------------------------------
111
+
112
+ Additional connection arguments can usually be passed via the URL query string;
113
+ particular symbols like ``SYSDBA`` are intercepted and converted to the correct
114
+ symbol::
115
+
116
+ e = create_engine(
117
+ "oracle+cx_oracle://user:pass@dsn?encoding=UTF-8&nencoding=UTF-8&mode=SYSDBA&events=true"
118
+ )
119
+
120
+ To pass arguments directly to ``.connect()`` without using the query
121
+ string, use the :paramref:`_sa.create_engine.connect_args` dictionary.
122
+ Any cx_Oracle parameter value and/or constant may be passed, such as::
123
+
124
+ import cx_Oracle
125
+
126
+ e = create_engine(
127
+ "oracle+cx_oracle://user:pass@dsn",
128
+ connect_args={
129
+ "encoding": "UTF-8",
130
+ "nencoding": "UTF-8",
131
+ "mode": cx_Oracle.SYSDBA,
132
+ "events": True,
133
+ },
134
+ )
135
+
136
+ Note that the default driver value for ``encoding`` and ``nencoding`` was
137
+ changed to "UTF-8" in cx_Oracle 8.0 so these parameters can be omitted when
138
+ using that version, or later.
139
+
140
+ Options consumed by the SQLAlchemy cx_Oracle dialect outside of the driver
141
+ --------------------------------------------------------------------------
142
+
143
+ There are also options that are consumed by the SQLAlchemy cx_oracle dialect
144
+ itself. These options are always passed directly to :func:`_sa.create_engine`
145
+ , such as::
146
+
147
+ e = create_engine(
148
+ "oracle+cx_oracle://user:pass@dsn", coerce_to_decimal=False
149
+ )
150
+
151
+ The parameters accepted by the cx_oracle dialect are as follows:
152
+
153
+ * ``arraysize`` - set the cx_oracle.arraysize value on cursors; defaults
154
+ to ``None``, indicating that the driver default should be used (typically
155
+ the value is 100). This setting controls how many rows are buffered when
156
+ fetching rows, and can have a significant effect on performance when
157
+ modified.
158
+
159
+ .. versionchanged:: 2.0.26 - changed the default value from 50 to None,
160
+ to use the default value of the driver itself.
161
+
162
+ * ``auto_convert_lobs`` - defaults to True; See :ref:`cx_oracle_lob`.
163
+
164
+ * ``coerce_to_decimal`` - see :ref:`cx_oracle_numeric` for detail.
165
+
166
+ * ``encoding_errors`` - see :ref:`cx_oracle_unicode_encoding_errors` for detail.
167
+
168
+ .. _cx_oracle_sessionpool:
169
+
170
+ Using cx_Oracle SessionPool
171
+ ---------------------------
172
+
173
+ The cx_Oracle driver provides its own connection pool implementation that may
174
+ be used in place of SQLAlchemy's pooling functionality. The driver pool
175
+ supports Oracle Database features such dead connection detection, connection
176
+ draining for planned database downtime, support for Oracle Application
177
+ Continuity and Transparent Application Continuity, and gives support for
178
+ Database Resident Connection Pooling (DRCP).
179
+
180
+ Using the driver pool can be achieved by using the
181
+ :paramref:`_sa.create_engine.creator` parameter to provide a function that
182
+ returns a new connection, along with setting
183
+ :paramref:`_sa.create_engine.pool_class` to ``NullPool`` to disable
184
+ SQLAlchemy's pooling::
185
+
186
+ import cx_Oracle
187
+ from sqlalchemy import create_engine
188
+ from sqlalchemy.pool import NullPool
189
+
190
+ pool = cx_Oracle.SessionPool(
191
+ user="scott",
192
+ password="tiger",
193
+ dsn="orclpdb",
194
+ min=1,
195
+ max=4,
196
+ increment=1,
197
+ threaded=True,
198
+ encoding="UTF-8",
199
+ nencoding="UTF-8",
200
+ )
201
+
202
+ engine = create_engine(
203
+ "oracle+cx_oracle://", creator=pool.acquire, poolclass=NullPool
204
+ )
205
+
206
+ The above engine may then be used normally where cx_Oracle's pool handles
207
+ connection pooling::
208
+
209
+ with engine.connect() as conn:
210
+ print(conn.scalar("select 1 from dual"))
211
+
212
+ As well as providing a scalable solution for multi-user applications, the
213
+ cx_Oracle session pool supports some Oracle features such as DRCP and
214
+ `Application Continuity
215
+ <https://cx-oracle.readthedocs.io/en/latest/user_guide/ha.html#application-continuity-ac>`_.
216
+
217
+ Note that the pool creation parameters ``threaded``, ``encoding`` and
218
+ ``nencoding`` were deprecated in later cx_Oracle releases.
219
+
220
+ Using Oracle Database Resident Connection Pooling (DRCP)
221
+ --------------------------------------------------------
222
+
223
+ When using Oracle Database's DRCP, the best practice is to pass a connection
224
+ class and "purity" when acquiring a connection from the SessionPool. Refer to
225
+ the `cx_Oracle DRCP documentation
226
+ <https://cx-oracle.readthedocs.io/en/latest/user_guide/connection_handling.html#database-resident-connection-pooling-drcp>`_.
227
+
228
+ This can be achieved by wrapping ``pool.acquire()``::
229
+
230
+ import cx_Oracle
231
+ from sqlalchemy import create_engine
232
+ from sqlalchemy.pool import NullPool
233
+
234
+ pool = cx_Oracle.SessionPool(
235
+ user="scott",
236
+ password="tiger",
237
+ dsn="orclpdb",
238
+ min=2,
239
+ max=5,
240
+ increment=1,
241
+ threaded=True,
242
+ encoding="UTF-8",
243
+ nencoding="UTF-8",
244
+ )
245
+
246
+
247
+ def creator():
248
+ return pool.acquire(
249
+ cclass="MYCLASS", purity=cx_Oracle.ATTR_PURITY_SELF
250
+ )
251
+
252
+
253
+ engine = create_engine(
254
+ "oracle+cx_oracle://", creator=creator, poolclass=NullPool
255
+ )
256
+
257
+ The above engine may then be used normally where cx_Oracle handles session
258
+ pooling and Oracle Database additionally uses DRCP::
259
+
260
+ with engine.connect() as conn:
261
+ print(conn.scalar("select 1 from dual"))
262
+
263
+ .. _cx_oracle_unicode:
264
+
265
+ Unicode
266
+ -------
267
+
268
+ As is the case for all DBAPIs under Python 3, all strings are inherently
269
+ Unicode strings. In all cases however, the driver requires an explicit
270
+ encoding configuration.
271
+
272
+ Ensuring the Correct Client Encoding
273
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
274
+
275
+ The long accepted standard for establishing client encoding for nearly all
276
+ Oracle Database related software is via the `NLS_LANG
277
+ <https://www.oracle.com/database/technologies/faq-nls-lang.html>`_ environment
278
+ variable. Older versions of cx_Oracle use this environment variable as the
279
+ source of its encoding configuration. The format of this variable is
280
+ Territory_Country.CharacterSet; a typical value would be
281
+ ``AMERICAN_AMERICA.AL32UTF8``. cx_Oracle version 8 and later use the character
282
+ set "UTF-8" by default, and ignore the character set component of NLS_LANG.
283
+
284
+ The cx_Oracle driver also supported a programmatic alternative which is to pass
285
+ the ``encoding`` and ``nencoding`` parameters directly to its ``.connect()``
286
+ function. These can be present in the URL as follows::
287
+
288
+ engine = create_engine(
289
+ "oracle+cx_oracle://scott:tiger@tnsalias?encoding=UTF-8&nencoding=UTF-8"
290
+ )
291
+
292
+ For the meaning of the ``encoding`` and ``nencoding`` parameters, please
293
+ consult
294
+ `Characters Sets and National Language Support (NLS) <https://cx-oracle.readthedocs.io/en/latest/user_guide/globalization.html#globalization>`_.
295
+
296
+ .. seealso::
297
+
298
+ `Characters Sets and National Language Support (NLS) <https://cx-oracle.readthedocs.io/en/latest/user_guide/globalization.html#globalization>`_
299
+ - in the cx_Oracle documentation.
300
+
301
+
302
+ Unicode-specific Column datatypes
303
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
304
+
305
+ The Core expression language handles unicode data by use of the
306
+ :class:`.Unicode` and :class:`.UnicodeText` datatypes. These types correspond
307
+ to the VARCHAR2 and CLOB Oracle Database datatypes by default. When using
308
+ these datatypes with Unicode data, it is expected that the database is
309
+ configured with a Unicode-aware character set, as well as that the ``NLS_LANG``
310
+ environment variable is set appropriately (this applies to older versions of
311
+ cx_Oracle), so that the VARCHAR2 and CLOB datatypes can accommodate the data.
312
+
313
+ In the case that Oracle Database is not configured with a Unicode character
314
+ set, the two options are to use the :class:`_types.NCHAR` and
315
+ :class:`_oracle.NCLOB` datatypes explicitly, or to pass the flag
316
+ ``use_nchar_for_unicode=True`` to :func:`_sa.create_engine`, which will cause
317
+ the SQLAlchemy dialect to use NCHAR/NCLOB for the :class:`.Unicode` /
318
+ :class:`.UnicodeText` datatypes instead of VARCHAR/CLOB.
319
+
320
+ .. _cx_oracle_unicode_encoding_errors:
321
+
322
+ Encoding Errors
323
+ ^^^^^^^^^^^^^^^
324
+
325
+ For the unusual case that data in Oracle Database is present with a broken
326
+ encoding, the dialect accepts a parameter ``encoding_errors`` which will be
327
+ passed to Unicode decoding functions in order to affect how decoding errors are
328
+ handled. The value is ultimately consumed by the Python `decode
329
+ <https://docs.python.org/3/library/stdtypes.html#bytes.decode>`_ function, and
330
+ is passed both via cx_Oracle's ``encodingErrors`` parameter consumed by
331
+ ``Cursor.var()``, as well as SQLAlchemy's own decoding function, as the
332
+ cx_Oracle dialect makes use of both under different circumstances.
333
+
334
+ .. _cx_oracle_setinputsizes:
335
+
336
+ Fine grained control over cx_Oracle data binding performance with setinputsizes
337
+ -------------------------------------------------------------------------------
338
+
339
+ The cx_Oracle DBAPI has a deep and fundamental reliance upon the usage of the
340
+ DBAPI ``setinputsizes()`` call. The purpose of this call is to establish the
341
+ datatypes that are bound to a SQL statement for Python values being passed as
342
+ parameters. While virtually no other DBAPI assigns any use to the
343
+ ``setinputsizes()`` call, the cx_Oracle DBAPI relies upon it heavily in its
344
+ interactions with the Oracle Database client interface, and in some scenarios
345
+ it is not possible for SQLAlchemy to know exactly how data should be bound, as
346
+ some settings can cause profoundly different performance characteristics, while
347
+ altering the type coercion behavior at the same time.
348
+
349
+ Users of the cx_Oracle dialect are **strongly encouraged** to read through
350
+ cx_Oracle's list of built-in datatype symbols at
351
+ https://cx-oracle.readthedocs.io/en/latest/api_manual/module.html#database-types.
352
+ Note that in some cases, significant performance degradation can occur when
353
+ using these types vs. not, in particular when specifying ``cx_Oracle.CLOB``.
354
+
355
+ On the SQLAlchemy side, the :meth:`.DialectEvents.do_setinputsizes` event can
356
+ be used both for runtime visibility (e.g. logging) of the setinputsizes step as
357
+ well as to fully control how ``setinputsizes()`` is used on a per-statement
358
+ basis.
359
+
360
+ Example 1 - logging all setinputsizes calls
361
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
362
+
363
+ The following example illustrates how to log the intermediary values from a
364
+ SQLAlchemy perspective before they are converted to the raw ``setinputsizes()``
365
+ parameter dictionary. The keys of the dictionary are :class:`.BindParameter`
366
+ objects which have a ``.key`` and a ``.type`` attribute::
367
+
368
+ from sqlalchemy import create_engine, event
369
+
370
+ engine = create_engine("oracle+cx_oracle://scott:tiger@host/xe")
371
+
372
+
373
+ @event.listens_for(engine, "do_setinputsizes")
374
+ def _log_setinputsizes(inputsizes, cursor, statement, parameters, context):
375
+ for bindparam, dbapitype in inputsizes.items():
376
+ log.info(
377
+ "Bound parameter name: %s SQLAlchemy type: %r DBAPI object: %s",
378
+ bindparam.key,
379
+ bindparam.type,
380
+ dbapitype,
381
+ )
382
+
383
+ Example 2 - remove all bindings to CLOB
384
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
385
+
386
+ The ``CLOB`` datatype in cx_Oracle incurs a significant performance overhead,
387
+ however is set by default for the ``Text`` type within the SQLAlchemy 1.2
388
+ series. This setting can be modified as follows::
389
+
390
+ from sqlalchemy import create_engine, event
391
+ from cx_Oracle import CLOB
392
+
393
+ engine = create_engine("oracle+cx_oracle://scott:tiger@host/xe")
394
+
395
+
396
+ @event.listens_for(engine, "do_setinputsizes")
397
+ def _remove_clob(inputsizes, cursor, statement, parameters, context):
398
+ for bindparam, dbapitype in list(inputsizes.items()):
399
+ if dbapitype is CLOB:
400
+ del inputsizes[bindparam]
401
+
402
+ .. _cx_oracle_lob:
403
+
404
+ LOB Datatypes
405
+ --------------
406
+
407
+ LOB datatypes refer to the "large object" datatypes such as CLOB, NCLOB and
408
+ BLOB. Modern versions of cx_Oracle is optimized for these datatypes to be
409
+ delivered as a single buffer. As such, SQLAlchemy makes use of these newer type
410
+ handlers by default.
411
+
412
+ To disable the use of newer type handlers and deliver LOB objects as classic
413
+ buffered objects with a ``read()`` method, the parameter
414
+ ``auto_convert_lobs=False`` may be passed to :func:`_sa.create_engine`,
415
+ which takes place only engine-wide.
416
+
417
+ .. _cx_oracle_returning:
418
+
419
+ RETURNING Support
420
+ -----------------
421
+
422
+ The cx_Oracle dialect implements RETURNING using OUT parameters.
423
+ The dialect supports RETURNING fully.
424
+
425
+ Two Phase Transactions Not Supported
426
+ ------------------------------------
427
+
428
+ Two phase transactions are **not supported** under cx_Oracle due to poor driver
429
+ support. The newer :ref:`oracledb` dialect however **does** support two phase
430
+ transactions.
431
+
432
+ .. _cx_oracle_numeric:
433
+
434
+ Precision Numerics
435
+ ------------------
436
+
437
+ SQLAlchemy's numeric types can handle receiving and returning values as Python
438
+ ``Decimal`` objects or float objects. When a :class:`.Numeric` object, or a
439
+ subclass such as :class:`.Float`, :class:`_oracle.DOUBLE_PRECISION` etc. is in
440
+ use, the :paramref:`.Numeric.asdecimal` flag determines if values should be
441
+ coerced to ``Decimal`` upon return, or returned as float objects. To make
442
+ matters more complicated under Oracle Database, the ``NUMBER`` type can also
443
+ represent integer values if the "scale" is zero, so the Oracle
444
+ Database-specific :class:`_oracle.NUMBER` type takes this into account as well.
445
+
446
+ The cx_Oracle dialect makes extensive use of connection- and cursor-level
447
+ "outputtypehandler" callables in order to coerce numeric values as requested.
448
+ These callables are specific to the specific flavor of :class:`.Numeric` in
449
+ use, as well as if no SQLAlchemy typing objects are present. There are
450
+ observed scenarios where Oracle Database may send incomplete or ambiguous
451
+ information about the numeric types being returned, such as a query where the
452
+ numeric types are buried under multiple levels of subquery. The type handlers
453
+ do their best to make the right decision in all cases, deferring to the
454
+ underlying cx_Oracle DBAPI for all those cases where the driver can make the
455
+ best decision.
456
+
457
+ When no typing objects are present, as when executing plain SQL strings, a
458
+ default "outputtypehandler" is present which will generally return numeric
459
+ values which specify precision and scale as Python ``Decimal`` objects. To
460
+ disable this coercion to decimal for performance reasons, pass the flag
461
+ ``coerce_to_decimal=False`` to :func:`_sa.create_engine`::
462
+
463
+ engine = create_engine("oracle+cx_oracle://dsn", coerce_to_decimal=False)
464
+
465
+ The ``coerce_to_decimal`` flag only impacts the results of plain string
466
+ SQL statements that are not otherwise associated with a :class:`.Numeric`
467
+ SQLAlchemy type (or a subclass of such).
468
+
469
+ """ # noqa
470
+ from __future__ import annotations
471
+
472
+ import decimal
473
+ import random
474
+ import re
475
+
476
+ from . import base as oracle
477
+ from .base import OracleCompiler
478
+ from .base import OracleDialect
479
+ from .base import OracleExecutionContext
480
+ from .types import _OracleDateLiteralRender
481
+ from ... import exc
482
+ from ... import util
483
+ from ...engine import cursor as _cursor
484
+ from ...engine import interfaces
485
+ from ...engine import processors
486
+ from ...sql import sqltypes
487
+ from ...sql._typing import is_sql_compiler
488
+ from ...sql.sqltypes import Boolean
489
+
490
+ # source:
491
+ # https://github.com/oracle/python-cx_Oracle/issues/596#issuecomment-999243649
492
+ _CX_ORACLE_MAGIC_LOB_SIZE = 131072
493
+
494
+
495
+ class _OracleInteger(sqltypes.Integer):
496
+ def get_dbapi_type(self, dbapi):
497
+ # see https://github.com/oracle/python-cx_Oracle/issues/
498
+ # 208#issuecomment-409715955
499
+ return int
500
+
501
+ def _cx_oracle_var(self, dialect, cursor, arraysize=None):
502
+ cx_Oracle = dialect.dbapi
503
+ return cursor.var(
504
+ cx_Oracle.STRING,
505
+ 255,
506
+ arraysize=arraysize if arraysize is not None else cursor.arraysize,
507
+ outconverter=int,
508
+ )
509
+
510
+ def _cx_oracle_outputtypehandler(self, dialect):
511
+ def handler(cursor, name, default_type, size, precision, scale):
512
+ return self._cx_oracle_var(dialect, cursor)
513
+
514
+ return handler
515
+
516
+
517
+ class _OracleNumericCommon(sqltypes.NumericCommon, sqltypes.TypeEngine):
518
+ is_number = False
519
+
520
+ def bind_processor(self, dialect):
521
+ if self.scale == 0:
522
+ return None
523
+ elif self.asdecimal:
524
+ processor = processors.to_decimal_processor_factory(
525
+ decimal.Decimal, self._effective_decimal_return_scale
526
+ )
527
+
528
+ def process(value):
529
+ if isinstance(value, (int, float)):
530
+ return processor(value)
531
+ elif value is not None and value.is_infinite():
532
+ return float(value)
533
+ else:
534
+ return value
535
+
536
+ return process
537
+ else:
538
+ return processors.to_float
539
+
540
+ def result_processor(self, dialect, coltype):
541
+ return None
542
+
543
+ def _cx_oracle_outputtypehandler(self, dialect):
544
+ cx_Oracle = dialect.dbapi
545
+
546
+ def handler(cursor, name, default_type, size, precision, scale):
547
+ outconverter = None
548
+
549
+ if precision:
550
+ if self.asdecimal:
551
+ if default_type == cx_Oracle.NATIVE_FLOAT:
552
+ # receiving float and doing Decimal after the fact
553
+ # allows for float("inf") to be handled
554
+ type_ = default_type
555
+ outconverter = decimal.Decimal
556
+ else:
557
+ type_ = decimal.Decimal
558
+ else:
559
+ if self.is_number and scale == 0:
560
+ # integer. cx_Oracle is observed to handle the widest
561
+ # variety of ints when no directives are passed,
562
+ # from 5.2 to 7.0. See [ticket:4457]
563
+ return None
564
+ else:
565
+ type_ = cx_Oracle.NATIVE_FLOAT
566
+
567
+ else:
568
+ if self.asdecimal:
569
+ if default_type == cx_Oracle.NATIVE_FLOAT:
570
+ type_ = default_type
571
+ outconverter = decimal.Decimal
572
+ else:
573
+ type_ = decimal.Decimal
574
+ else:
575
+ if self.is_number and scale == 0:
576
+ # integer. cx_Oracle is observed to handle the widest
577
+ # variety of ints when no directives are passed,
578
+ # from 5.2 to 7.0. See [ticket:4457]
579
+ return None
580
+ else:
581
+ type_ = cx_Oracle.NATIVE_FLOAT
582
+
583
+ return cursor.var(
584
+ type_,
585
+ 255,
586
+ arraysize=cursor.arraysize,
587
+ outconverter=outconverter,
588
+ )
589
+
590
+ return handler
591
+
592
+
593
+ class _OracleNumeric(_OracleNumericCommon, sqltypes.Numeric):
594
+ pass
595
+
596
+
597
+ class _OracleFloat(_OracleNumericCommon, sqltypes.Float):
598
+ pass
599
+
600
+
601
+ class _OracleUUID(sqltypes.Uuid):
602
+ def get_dbapi_type(self, dbapi):
603
+ return dbapi.STRING
604
+
605
+
606
+ class _OracleBinaryFloat(_OracleNumericCommon):
607
+ def get_dbapi_type(self, dbapi):
608
+ return dbapi.NATIVE_FLOAT
609
+
610
+
611
+ class _OracleBINARY_FLOAT(_OracleBinaryFloat, oracle.BINARY_FLOAT):
612
+ pass
613
+
614
+
615
+ class _OracleBINARY_DOUBLE(_OracleBinaryFloat, oracle.BINARY_DOUBLE):
616
+ pass
617
+
618
+
619
+ class _OracleNUMBER(_OracleNumericCommon, sqltypes.Numeric):
620
+ is_number = True
621
+
622
+
623
+ class _CXOracleDate(oracle._OracleDate):
624
+ def bind_processor(self, dialect):
625
+ return None
626
+
627
+ def result_processor(self, dialect, coltype):
628
+ def process(value):
629
+ if value is not None:
630
+ return value.date()
631
+ else:
632
+ return value
633
+
634
+ return process
635
+
636
+
637
+ class _CXOracleTIMESTAMP(_OracleDateLiteralRender, sqltypes.TIMESTAMP):
638
+ def literal_processor(self, dialect):
639
+ return self._literal_processor_datetime(dialect)
640
+
641
+
642
+ class _LOBDataType:
643
+ pass
644
+
645
+
646
+ # TODO: the names used across CHAR / VARCHAR / NCHAR / NVARCHAR
647
+ # here are inconsistent and not very good
648
+ class _OracleChar(sqltypes.CHAR):
649
+ def get_dbapi_type(self, dbapi):
650
+ return dbapi.FIXED_CHAR
651
+
652
+
653
+ class _OracleNChar(sqltypes.NCHAR):
654
+ def get_dbapi_type(self, dbapi):
655
+ return dbapi.FIXED_NCHAR
656
+
657
+
658
+ class _OracleUnicodeStringNCHAR(oracle.NVARCHAR2):
659
+ def get_dbapi_type(self, dbapi):
660
+ return dbapi.NCHAR
661
+
662
+
663
+ class _OracleUnicodeStringCHAR(sqltypes.Unicode):
664
+ def get_dbapi_type(self, dbapi):
665
+ return dbapi.LONG_STRING
666
+
667
+
668
+ class _OracleUnicodeTextNCLOB(_LOBDataType, oracle.NCLOB):
669
+ def get_dbapi_type(self, dbapi):
670
+ # previously, this was dbapi.NCLOB.
671
+ # DB_TYPE_NVARCHAR will instead be passed to setinputsizes()
672
+ # when this datatype is used.
673
+ return dbapi.DB_TYPE_NVARCHAR
674
+
675
+
676
+ class _OracleUnicodeTextCLOB(_LOBDataType, sqltypes.UnicodeText):
677
+ def get_dbapi_type(self, dbapi):
678
+ # previously, this was dbapi.CLOB.
679
+ # DB_TYPE_NVARCHAR will instead be passed to setinputsizes()
680
+ # when this datatype is used.
681
+ return dbapi.DB_TYPE_NVARCHAR
682
+
683
+
684
+ class _OracleText(_LOBDataType, sqltypes.Text):
685
+ def get_dbapi_type(self, dbapi):
686
+ # previously, this was dbapi.CLOB.
687
+ # DB_TYPE_NVARCHAR will instead be passed to setinputsizes()
688
+ # when this datatype is used.
689
+ return dbapi.DB_TYPE_NVARCHAR
690
+
691
+
692
+ class _OracleLong(_LOBDataType, oracle.LONG):
693
+ def get_dbapi_type(self, dbapi):
694
+ return dbapi.LONG_STRING
695
+
696
+
697
+ class _OracleString(sqltypes.String):
698
+ pass
699
+
700
+
701
+ class _OracleEnum(sqltypes.Enum):
702
+ def bind_processor(self, dialect):
703
+ enum_proc = sqltypes.Enum.bind_processor(self, dialect)
704
+
705
+ def process(value):
706
+ raw_str = enum_proc(value)
707
+ return raw_str
708
+
709
+ return process
710
+
711
+
712
+ class _OracleBinary(_LOBDataType, sqltypes.LargeBinary):
713
+ def get_dbapi_type(self, dbapi):
714
+ # previously, this was dbapi.BLOB.
715
+ # DB_TYPE_RAW will instead be passed to setinputsizes()
716
+ # when this datatype is used.
717
+ return dbapi.DB_TYPE_RAW
718
+
719
+ def bind_processor(self, dialect):
720
+ return None
721
+
722
+ def result_processor(self, dialect, coltype):
723
+ if not dialect.auto_convert_lobs:
724
+ return None
725
+ else:
726
+ return super().result_processor(dialect, coltype)
727
+
728
+
729
+ class _OracleInterval(oracle.INTERVAL):
730
+ def get_dbapi_type(self, dbapi):
731
+ return dbapi.INTERVAL
732
+
733
+
734
+ class _OracleRaw(oracle.RAW):
735
+ pass
736
+
737
+
738
+ class _OracleRowid(oracle.ROWID):
739
+ def get_dbapi_type(self, dbapi):
740
+ return dbapi.ROWID
741
+
742
+
743
+ class OracleCompiler_cx_oracle(OracleCompiler):
744
+ _oracle_cx_sql_compiler = True
745
+
746
+ _oracle_returning = False
747
+
748
+ # Oracle bind names can't start with digits or underscores.
749
+ # currently we rely upon Oracle-specific quoting of bind names in most
750
+ # cases. however for expanding params, the escape chars are used.
751
+ # see #8708
752
+ bindname_escape_characters = util.immutabledict(
753
+ {
754
+ "%": "P",
755
+ "(": "A",
756
+ ")": "Z",
757
+ ":": "C",
758
+ ".": "C",
759
+ "[": "C",
760
+ "]": "C",
761
+ " ": "C",
762
+ "\\": "C",
763
+ "/": "C",
764
+ "?": "C",
765
+ }
766
+ )
767
+
768
+ def bindparam_string(self, name, **kw):
769
+ quote = getattr(name, "quote", None)
770
+ if (
771
+ quote is True
772
+ or quote is not False
773
+ and self.preparer._bindparam_requires_quotes(name)
774
+ # bind param quoting for Oracle doesn't work with post_compile
775
+ # params. For those, the default bindparam_string will escape
776
+ # special chars, and the appending of a number "_1" etc. will
777
+ # take care of reserved words
778
+ and not kw.get("post_compile", False)
779
+ ):
780
+ # interesting to note about expanding parameters - since the
781
+ # new parameters take the form <paramname>_<int>, at least if
782
+ # they are originally formed from reserved words, they no longer
783
+ # need quoting :). names that include illegal characters
784
+ # won't work however.
785
+ quoted_name = '"%s"' % name
786
+ kw["escaped_from"] = name
787
+ name = quoted_name
788
+ return OracleCompiler.bindparam_string(self, name, **kw)
789
+
790
+ # TODO: we could likely do away with quoting altogether for
791
+ # Oracle parameters and use the custom escaping here
792
+ escaped_from = kw.get("escaped_from", None)
793
+ if not escaped_from:
794
+ if self._bind_translate_re.search(name):
795
+ # not quite the translate use case as we want to
796
+ # also get a quick boolean if we even found
797
+ # unusual characters in the name
798
+ new_name = self._bind_translate_re.sub(
799
+ lambda m: self._bind_translate_chars[m.group(0)],
800
+ name,
801
+ )
802
+ if new_name[0].isdigit() or new_name[0] == "_":
803
+ new_name = "D" + new_name
804
+ kw["escaped_from"] = name
805
+ name = new_name
806
+ elif name[0].isdigit() or name[0] == "_":
807
+ new_name = "D" + name
808
+ kw["escaped_from"] = name
809
+ name = new_name
810
+
811
+ return OracleCompiler.bindparam_string(self, name, **kw)
812
+
813
+
814
+ class OracleExecutionContext_cx_oracle(OracleExecutionContext):
815
+ out_parameters = None
816
+
817
+ def _generate_out_parameter_vars(self):
818
+ # check for has_out_parameters or RETURNING, create cx_Oracle.var
819
+ # objects if so
820
+ if self.compiled.has_out_parameters or self.compiled._oracle_returning:
821
+ out_parameters = self.out_parameters
822
+ assert out_parameters is not None
823
+
824
+ len_params = len(self.parameters)
825
+
826
+ quoted_bind_names = self.compiled.escaped_bind_names
827
+ for bindparam in self.compiled.binds.values():
828
+ if bindparam.isoutparam:
829
+ name = self.compiled.bind_names[bindparam]
830
+ type_impl = bindparam.type.dialect_impl(self.dialect)
831
+
832
+ if hasattr(type_impl, "_cx_oracle_var"):
833
+ out_parameters[name] = type_impl._cx_oracle_var(
834
+ self.dialect, self.cursor, arraysize=len_params
835
+ )
836
+ else:
837
+ dbtype = type_impl.get_dbapi_type(self.dialect.dbapi)
838
+
839
+ cx_Oracle = self.dialect.dbapi
840
+
841
+ assert cx_Oracle is not None
842
+
843
+ if dbtype is None:
844
+ raise exc.InvalidRequestError(
845
+ "Cannot create out parameter for "
846
+ "parameter "
847
+ "%r - its type %r is not supported by"
848
+ " cx_oracle" % (bindparam.key, bindparam.type)
849
+ )
850
+
851
+ # note this is an OUT parameter. Using
852
+ # non-LOB datavalues with large unicode-holding
853
+ # values causes the failure (both cx_Oracle and
854
+ # oracledb):
855
+ # ORA-22835: Buffer too small for CLOB to CHAR or
856
+ # BLOB to RAW conversion (actual: 16507,
857
+ # maximum: 4000)
858
+ # [SQL: INSERT INTO long_text (x, y, z) VALUES
859
+ # (:x, :y, :z) RETURNING long_text.x, long_text.y,
860
+ # long_text.z INTO :ret_0, :ret_1, :ret_2]
861
+ # so even for DB_TYPE_NVARCHAR we convert to a LOB
862
+
863
+ if isinstance(type_impl, _LOBDataType):
864
+ if dbtype == cx_Oracle.DB_TYPE_NVARCHAR:
865
+ dbtype = cx_Oracle.NCLOB
866
+ elif dbtype == cx_Oracle.DB_TYPE_RAW:
867
+ dbtype = cx_Oracle.BLOB
868
+ # other LOB types go in directly
869
+
870
+ out_parameters[name] = self.cursor.var(
871
+ dbtype,
872
+ # this is fine also in oracledb_async since
873
+ # the driver will await the read coroutine
874
+ outconverter=lambda value: value.read(),
875
+ arraysize=len_params,
876
+ )
877
+ elif (
878
+ isinstance(type_impl, _OracleNumericCommon)
879
+ and type_impl.asdecimal
880
+ ):
881
+ out_parameters[name] = self.cursor.var(
882
+ decimal.Decimal,
883
+ arraysize=len_params,
884
+ )
885
+ elif isinstance(type_impl, Boolean):
886
+ if self.dialect.supports_native_boolean:
887
+ out_parameters[name] = self.cursor.var(
888
+ cx_Oracle.BOOLEAN, arraysize=len_params
889
+ )
890
+ else:
891
+ out_parameters[name] = self.cursor.var(
892
+ cx_Oracle.NUMBER,
893
+ arraysize=len_params,
894
+ outconverter=bool,
895
+ )
896
+ else:
897
+ out_parameters[name] = self.cursor.var(
898
+ dbtype, arraysize=len_params
899
+ )
900
+
901
+ for param in self.parameters:
902
+ param[quoted_bind_names.get(name, name)] = (
903
+ out_parameters[name]
904
+ )
905
+
906
+ def _generate_cursor_outputtype_handler(self):
907
+ output_handlers = {}
908
+
909
+ for keyname, name, objects, type_ in self.compiled._result_columns:
910
+ handler = type_._cached_custom_processor(
911
+ self.dialect,
912
+ "cx_oracle_outputtypehandler",
913
+ self._get_cx_oracle_type_handler,
914
+ )
915
+
916
+ if handler:
917
+ denormalized_name = self.dialect.denormalize_name(keyname)
918
+ output_handlers[denormalized_name] = handler
919
+
920
+ if output_handlers:
921
+ default_handler = self._dbapi_connection.outputtypehandler
922
+
923
+ def output_type_handler(
924
+ cursor, name, default_type, size, precision, scale
925
+ ):
926
+ if name in output_handlers:
927
+ return output_handlers[name](
928
+ cursor, name, default_type, size, precision, scale
929
+ )
930
+ else:
931
+ return default_handler(
932
+ cursor, name, default_type, size, precision, scale
933
+ )
934
+
935
+ self.cursor.outputtypehandler = output_type_handler
936
+
937
+ def _get_cx_oracle_type_handler(self, impl):
938
+ if hasattr(impl, "_cx_oracle_outputtypehandler"):
939
+ return impl._cx_oracle_outputtypehandler(self.dialect)
940
+ else:
941
+ return None
942
+
943
+ def pre_exec(self):
944
+ super().pre_exec()
945
+ if not getattr(self.compiled, "_oracle_cx_sql_compiler", False):
946
+ return
947
+
948
+ self.out_parameters = {}
949
+
950
+ self._generate_out_parameter_vars()
951
+
952
+ self._generate_cursor_outputtype_handler()
953
+
954
+ def post_exec(self):
955
+ if (
956
+ self.compiled
957
+ and is_sql_compiler(self.compiled)
958
+ and self.compiled._oracle_returning
959
+ ):
960
+ initial_buffer = self.fetchall_for_returning(
961
+ self.cursor, _internal=True
962
+ )
963
+
964
+ fetch_strategy = _cursor.FullyBufferedCursorFetchStrategy(
965
+ self.cursor,
966
+ [
967
+ (entry.keyname, None)
968
+ for entry in self.compiled._result_columns
969
+ ],
970
+ initial_buffer=initial_buffer,
971
+ )
972
+
973
+ self.cursor_fetch_strategy = fetch_strategy
974
+
975
+ def create_cursor(self):
976
+ c = self._dbapi_connection.cursor()
977
+ if self.dialect.arraysize:
978
+ c.arraysize = self.dialect.arraysize
979
+
980
+ return c
981
+
982
+ def fetchall_for_returning(self, cursor, *, _internal=False):
983
+ compiled = self.compiled
984
+ if (
985
+ not _internal
986
+ and compiled is None
987
+ or not is_sql_compiler(compiled)
988
+ or not compiled._oracle_returning
989
+ ):
990
+ raise NotImplementedError(
991
+ "execution context was not prepared for Oracle RETURNING"
992
+ )
993
+
994
+ # create a fake cursor result from the out parameters. unlike
995
+ # get_out_parameter_values(), the result-row handlers here will be
996
+ # applied at the Result level
997
+
998
+ numcols = len(self.out_parameters)
999
+
1000
+ # [stmt_result for stmt_result in outparam.values] == each
1001
+ # statement in executemany
1002
+ # [val for val in stmt_result] == each row for a particular
1003
+ # statement
1004
+ return list(
1005
+ zip(
1006
+ *[
1007
+ [
1008
+ val
1009
+ for stmt_result in self.out_parameters[
1010
+ f"ret_{j}"
1011
+ ].values
1012
+ for val in (stmt_result or ())
1013
+ ]
1014
+ for j in range(numcols)
1015
+ ]
1016
+ )
1017
+ )
1018
+
1019
+ def get_out_parameter_values(self, out_param_names):
1020
+ # this method should not be called when the compiler has
1021
+ # RETURNING as we've turned the has_out_parameters flag set to
1022
+ # False.
1023
+ assert not self.compiled.returning
1024
+
1025
+ return [
1026
+ self.dialect._paramval(self.out_parameters[name])
1027
+ for name in out_param_names
1028
+ ]
1029
+
1030
+
1031
+ class OracleDialect_cx_oracle(OracleDialect):
1032
+ supports_statement_cache = True
1033
+ execution_ctx_cls = OracleExecutionContext_cx_oracle
1034
+ statement_compiler = OracleCompiler_cx_oracle
1035
+
1036
+ supports_sane_rowcount = True
1037
+ supports_sane_multi_rowcount = True
1038
+
1039
+ insert_executemany_returning = True
1040
+ insert_executemany_returning_sort_by_parameter_order = True
1041
+ update_executemany_returning = True
1042
+ delete_executemany_returning = True
1043
+
1044
+ bind_typing = interfaces.BindTyping.SETINPUTSIZES
1045
+
1046
+ driver = "cx_oracle"
1047
+
1048
+ colspecs = util.update_copy(
1049
+ OracleDialect.colspecs,
1050
+ {
1051
+ sqltypes.TIMESTAMP: _CXOracleTIMESTAMP,
1052
+ sqltypes.Numeric: _OracleNumeric,
1053
+ sqltypes.Float: _OracleFloat,
1054
+ oracle.BINARY_FLOAT: _OracleBINARY_FLOAT,
1055
+ oracle.BINARY_DOUBLE: _OracleBINARY_DOUBLE,
1056
+ sqltypes.Integer: _OracleInteger,
1057
+ oracle.NUMBER: _OracleNUMBER,
1058
+ sqltypes.Date: _CXOracleDate,
1059
+ sqltypes.LargeBinary: _OracleBinary,
1060
+ sqltypes.Boolean: oracle._OracleBoolean,
1061
+ sqltypes.Interval: _OracleInterval,
1062
+ oracle.INTERVAL: _OracleInterval,
1063
+ sqltypes.Text: _OracleText,
1064
+ sqltypes.String: _OracleString,
1065
+ sqltypes.UnicodeText: _OracleUnicodeTextCLOB,
1066
+ sqltypes.CHAR: _OracleChar,
1067
+ sqltypes.NCHAR: _OracleNChar,
1068
+ sqltypes.Enum: _OracleEnum,
1069
+ oracle.LONG: _OracleLong,
1070
+ oracle.RAW: _OracleRaw,
1071
+ sqltypes.Unicode: _OracleUnicodeStringCHAR,
1072
+ sqltypes.NVARCHAR: _OracleUnicodeStringNCHAR,
1073
+ sqltypes.Uuid: _OracleUUID,
1074
+ oracle.NCLOB: _OracleUnicodeTextNCLOB,
1075
+ oracle.ROWID: _OracleRowid,
1076
+ },
1077
+ )
1078
+
1079
+ execute_sequence_format = list
1080
+
1081
+ _cursor_var_unicode_kwargs = util.immutabledict()
1082
+
1083
+ def __init__(
1084
+ self,
1085
+ auto_convert_lobs=True,
1086
+ coerce_to_decimal=True,
1087
+ arraysize=None,
1088
+ encoding_errors=None,
1089
+ **kwargs,
1090
+ ):
1091
+ OracleDialect.__init__(self, **kwargs)
1092
+ self.arraysize = arraysize
1093
+ self.encoding_errors = encoding_errors
1094
+ if encoding_errors:
1095
+ self._cursor_var_unicode_kwargs = {
1096
+ "encodingErrors": encoding_errors
1097
+ }
1098
+ self.auto_convert_lobs = auto_convert_lobs
1099
+ self.coerce_to_decimal = coerce_to_decimal
1100
+ if self._use_nchar_for_unicode:
1101
+ self.colspecs = self.colspecs.copy()
1102
+ self.colspecs[sqltypes.Unicode] = _OracleUnicodeStringNCHAR
1103
+ self.colspecs[sqltypes.UnicodeText] = _OracleUnicodeTextNCLOB
1104
+
1105
+ dbapi_module = self.dbapi
1106
+ self._load_version(dbapi_module)
1107
+
1108
+ if dbapi_module is not None:
1109
+ # these constants will first be seen in SQLAlchemy datatypes
1110
+ # coming from the get_dbapi_type() method. We then
1111
+ # will place the following types into setinputsizes() calls
1112
+ # on each statement. Oracle constants that are not in this
1113
+ # list will not be put into setinputsizes().
1114
+ self.include_set_input_sizes = {
1115
+ dbapi_module.DATETIME,
1116
+ dbapi_module.DB_TYPE_NVARCHAR, # used for CLOB, NCLOB
1117
+ dbapi_module.DB_TYPE_RAW, # used for BLOB
1118
+ dbapi_module.NCLOB, # not currently used except for OUT param
1119
+ dbapi_module.CLOB, # not currently used except for OUT param
1120
+ dbapi_module.LOB, # not currently used
1121
+ dbapi_module.BLOB, # not currently used except for OUT param
1122
+ dbapi_module.NCHAR,
1123
+ dbapi_module.FIXED_NCHAR,
1124
+ dbapi_module.FIXED_CHAR,
1125
+ dbapi_module.TIMESTAMP,
1126
+ int, # _OracleInteger,
1127
+ # _OracleBINARY_FLOAT, _OracleBINARY_DOUBLE,
1128
+ dbapi_module.NATIVE_FLOAT,
1129
+ }
1130
+
1131
+ self._paramval = lambda value: value.getvalue()
1132
+
1133
+ def _load_version(self, dbapi_module):
1134
+ version = (0, 0, 0)
1135
+ if dbapi_module is not None:
1136
+ m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", dbapi_module.version)
1137
+ if m:
1138
+ version = tuple(
1139
+ int(x) for x in m.group(1, 2, 3) if x is not None
1140
+ )
1141
+ self.cx_oracle_ver = version
1142
+ if self.cx_oracle_ver < (8,) and self.cx_oracle_ver > (0, 0, 0):
1143
+ raise exc.InvalidRequestError(
1144
+ "cx_Oracle version 8 and above are supported"
1145
+ )
1146
+
1147
+ @classmethod
1148
+ def import_dbapi(cls):
1149
+ import cx_Oracle
1150
+
1151
+ return cx_Oracle
1152
+
1153
+ def initialize(self, connection):
1154
+ super().initialize(connection)
1155
+ self._detect_decimal_char(connection)
1156
+
1157
+ def get_isolation_level(self, dbapi_connection):
1158
+ # sources:
1159
+
1160
+ # general idea of transaction id, have to start one, etc.
1161
+ # https://stackoverflow.com/questions/10711204/how-to-check-isoloation-level
1162
+
1163
+ # how to decode xid cols from v$transaction to match
1164
+ # https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:9532779900346079444
1165
+
1166
+ # Oracle tuple comparison without using IN:
1167
+ # https://www.sql-workbench.eu/comparison/tuple_comparison.html
1168
+
1169
+ with dbapi_connection.cursor() as cursor:
1170
+ # this is the only way to ensure a transaction is started without
1171
+ # actually running DML. There's no way to see the configured
1172
+ # isolation level without getting it from v$transaction which
1173
+ # means transaction has to be started.
1174
+ outval = cursor.var(str)
1175
+ cursor.execute(
1176
+ """
1177
+ begin
1178
+ :trans_id := dbms_transaction.local_transaction_id( TRUE );
1179
+ end;
1180
+ """,
1181
+ {"trans_id": outval},
1182
+ )
1183
+ trans_id = outval.getvalue()
1184
+ xidusn, xidslot, xidsqn = trans_id.split(".", 2)
1185
+
1186
+ cursor.execute(
1187
+ "SELECT CASE BITAND(t.flag, POWER(2, 28)) "
1188
+ "WHEN 0 THEN 'READ COMMITTED' "
1189
+ "ELSE 'SERIALIZABLE' END AS isolation_level "
1190
+ "FROM v$transaction t WHERE "
1191
+ "(t.xidusn, t.xidslot, t.xidsqn) = "
1192
+ "((:xidusn, :xidslot, :xidsqn))",
1193
+ {"xidusn": xidusn, "xidslot": xidslot, "xidsqn": xidsqn},
1194
+ )
1195
+ row = cursor.fetchone()
1196
+ if row is None:
1197
+ raise exc.InvalidRequestError(
1198
+ "could not retrieve isolation level"
1199
+ )
1200
+ result = row[0]
1201
+
1202
+ return result
1203
+
1204
+ def get_isolation_level_values(self, dbapi_connection):
1205
+ return super().get_isolation_level_values(dbapi_connection) + [
1206
+ "AUTOCOMMIT"
1207
+ ]
1208
+
1209
+ def set_isolation_level(self, dbapi_connection, level):
1210
+ if level == "AUTOCOMMIT":
1211
+ dbapi_connection.autocommit = True
1212
+ else:
1213
+ dbapi_connection.autocommit = False
1214
+ dbapi_connection.rollback()
1215
+ with dbapi_connection.cursor() as cursor:
1216
+ cursor.execute(f"ALTER SESSION SET ISOLATION_LEVEL={level}")
1217
+
1218
+ def detect_autocommit_setting(self, dbapi_conn) -> bool:
1219
+ return bool(dbapi_conn.autocommit)
1220
+
1221
+ def _detect_decimal_char(self, connection):
1222
+ # we have the option to change this setting upon connect,
1223
+ # or just look at what it is upon connect and convert.
1224
+ # to minimize the chance of interference with changes to
1225
+ # NLS_TERRITORY or formatting behavior of the DB, we opt
1226
+ # to just look at it
1227
+
1228
+ dbapi_connection = connection.connection
1229
+
1230
+ with dbapi_connection.cursor() as cursor:
1231
+ # issue #8744
1232
+ # nls_session_parameters is not available in some Oracle
1233
+ # modes like "mount mode". But then, v$nls_parameters is not
1234
+ # available if the connection doesn't have SYSDBA priv.
1235
+ #
1236
+ # simplify the whole thing and just use the method that we were
1237
+ # doing in the test suite already, selecting a number
1238
+
1239
+ def output_type_handler(
1240
+ cursor, name, defaultType, size, precision, scale
1241
+ ):
1242
+ return cursor.var(
1243
+ self.dbapi.STRING, 255, arraysize=cursor.arraysize
1244
+ )
1245
+
1246
+ cursor.outputtypehandler = output_type_handler
1247
+ cursor.execute("SELECT 1.1 FROM DUAL")
1248
+ value = cursor.fetchone()[0]
1249
+
1250
+ decimal_char = value.lstrip("0")[1]
1251
+ assert not decimal_char[0].isdigit()
1252
+
1253
+ self._decimal_char = decimal_char
1254
+
1255
+ if self._decimal_char != ".":
1256
+ _detect_decimal = self._detect_decimal
1257
+ _to_decimal = self._to_decimal
1258
+
1259
+ self._detect_decimal = lambda value: _detect_decimal(
1260
+ value.replace(self._decimal_char, ".")
1261
+ )
1262
+ self._to_decimal = lambda value: _to_decimal(
1263
+ value.replace(self._decimal_char, ".")
1264
+ )
1265
+
1266
+ def _detect_decimal(self, value):
1267
+ if "." in value:
1268
+ return self._to_decimal(value)
1269
+ else:
1270
+ return int(value)
1271
+
1272
+ _to_decimal = decimal.Decimal
1273
+
1274
+ def _generate_connection_outputtype_handler(self):
1275
+ """establish the default outputtypehandler established at the
1276
+ connection level.
1277
+
1278
+ """
1279
+
1280
+ dialect = self
1281
+ cx_Oracle = dialect.dbapi
1282
+
1283
+ number_handler = _OracleNUMBER(
1284
+ asdecimal=True
1285
+ )._cx_oracle_outputtypehandler(dialect)
1286
+ float_handler = _OracleNUMBER(
1287
+ asdecimal=False
1288
+ )._cx_oracle_outputtypehandler(dialect)
1289
+
1290
+ def output_type_handler(
1291
+ cursor, name, default_type, size, precision, scale
1292
+ ):
1293
+ if (
1294
+ default_type == cx_Oracle.NUMBER
1295
+ and default_type is not cx_Oracle.NATIVE_FLOAT
1296
+ ):
1297
+ if not dialect.coerce_to_decimal:
1298
+ return None
1299
+ elif precision == 0 and scale in (0, -127):
1300
+ # ambiguous type, this occurs when selecting
1301
+ # numbers from deep subqueries
1302
+ return cursor.var(
1303
+ cx_Oracle.STRING,
1304
+ 255,
1305
+ outconverter=dialect._detect_decimal,
1306
+ arraysize=cursor.arraysize,
1307
+ )
1308
+ elif precision and scale > 0:
1309
+ return number_handler(
1310
+ cursor, name, default_type, size, precision, scale
1311
+ )
1312
+ else:
1313
+ return float_handler(
1314
+ cursor, name, default_type, size, precision, scale
1315
+ )
1316
+
1317
+ # if unicode options were specified, add a decoder, otherwise
1318
+ # cx_Oracle should return Unicode
1319
+ elif (
1320
+ dialect._cursor_var_unicode_kwargs
1321
+ and default_type
1322
+ in (
1323
+ cx_Oracle.STRING,
1324
+ cx_Oracle.FIXED_CHAR,
1325
+ )
1326
+ and default_type is not cx_Oracle.CLOB
1327
+ and default_type is not cx_Oracle.NCLOB
1328
+ ):
1329
+ return cursor.var(
1330
+ str,
1331
+ size,
1332
+ cursor.arraysize,
1333
+ **dialect._cursor_var_unicode_kwargs,
1334
+ )
1335
+
1336
+ elif dialect.auto_convert_lobs and default_type in (
1337
+ cx_Oracle.CLOB,
1338
+ cx_Oracle.NCLOB,
1339
+ ):
1340
+ typ = (
1341
+ cx_Oracle.DB_TYPE_VARCHAR
1342
+ if default_type is cx_Oracle.CLOB
1343
+ else cx_Oracle.DB_TYPE_NVARCHAR
1344
+ )
1345
+ return cursor.var(
1346
+ typ,
1347
+ _CX_ORACLE_MAGIC_LOB_SIZE,
1348
+ cursor.arraysize,
1349
+ **dialect._cursor_var_unicode_kwargs,
1350
+ )
1351
+
1352
+ elif dialect.auto_convert_lobs and default_type in (
1353
+ cx_Oracle.BLOB,
1354
+ ):
1355
+ return cursor.var(
1356
+ cx_Oracle.DB_TYPE_RAW,
1357
+ _CX_ORACLE_MAGIC_LOB_SIZE,
1358
+ cursor.arraysize,
1359
+ )
1360
+
1361
+ return output_type_handler
1362
+
1363
+ def on_connect(self):
1364
+ output_type_handler = self._generate_connection_outputtype_handler()
1365
+
1366
+ def on_connect(conn):
1367
+ conn.outputtypehandler = output_type_handler
1368
+
1369
+ return on_connect
1370
+
1371
+ def create_connect_args(self, url):
1372
+ opts = dict(url.query)
1373
+
1374
+ database = url.database
1375
+ service_name = opts.pop("service_name", None)
1376
+ if database or service_name:
1377
+ # if we have a database, then we have a remote host
1378
+ port = url.port
1379
+ if port:
1380
+ port = int(port)
1381
+ else:
1382
+ port = 1521
1383
+
1384
+ if database and service_name:
1385
+ raise exc.InvalidRequestError(
1386
+ '"service_name" option shouldn\'t '
1387
+ 'be used with a "database" part of the url'
1388
+ )
1389
+ if database:
1390
+ makedsn_kwargs = {"sid": database}
1391
+ if service_name:
1392
+ makedsn_kwargs = {"service_name": service_name}
1393
+
1394
+ dsn = self.dbapi.makedsn(url.host, port, **makedsn_kwargs)
1395
+ else:
1396
+ # we have a local tnsname
1397
+ dsn = url.host
1398
+
1399
+ if dsn is not None:
1400
+ opts["dsn"] = dsn
1401
+ if url.password is not None:
1402
+ opts["password"] = url.password
1403
+ if url.username is not None:
1404
+ opts["user"] = url.username
1405
+
1406
+ def convert_cx_oracle_constant(value):
1407
+ if isinstance(value, str):
1408
+ try:
1409
+ int_val = int(value)
1410
+ except ValueError:
1411
+ value = value.upper()
1412
+ return getattr(self.dbapi, value)
1413
+ else:
1414
+ return int_val
1415
+ else:
1416
+ return value
1417
+
1418
+ util.coerce_kw_type(opts, "mode", convert_cx_oracle_constant)
1419
+ util.coerce_kw_type(opts, "threaded", bool)
1420
+ util.coerce_kw_type(opts, "events", bool)
1421
+ util.coerce_kw_type(opts, "purity", convert_cx_oracle_constant)
1422
+ return ([], opts)
1423
+
1424
+ def _get_server_version_info(self, connection):
1425
+ return tuple(int(x) for x in connection.connection.version.split("."))
1426
+
1427
+ def is_disconnect(self, e, connection, cursor):
1428
+ (error,) = e.args
1429
+ if isinstance(
1430
+ e, (self.dbapi.InterfaceError, self.dbapi.DatabaseError)
1431
+ ) and "not connected" in str(e):
1432
+ return True
1433
+
1434
+ if hasattr(error, "code") and error.code in {
1435
+ 28,
1436
+ 3114,
1437
+ 3113,
1438
+ 3135,
1439
+ 1033,
1440
+ 2396,
1441
+ }:
1442
+ # ORA-00028: your session has been killed
1443
+ # ORA-03114: not connected to ORACLE
1444
+ # ORA-03113: end-of-file on communication channel
1445
+ # ORA-03135: connection lost contact
1446
+ # ORA-01033: ORACLE initialization or shutdown in progress
1447
+ # ORA-02396: exceeded maximum idle time, please connect again
1448
+ # TODO: Others ?
1449
+ return True
1450
+
1451
+ if re.match(r"^(?:DPI-1010|DPI-1080|DPY-1001|DPY-4011)", str(e)):
1452
+ # DPI-1010: not connected
1453
+ # DPI-1080: connection was closed by ORA-3113
1454
+ # python-oracledb's DPY-1001: not connected to database
1455
+ # python-oracledb's DPY-4011: the database or network closed the
1456
+ # connection
1457
+ # TODO: others?
1458
+ return True
1459
+
1460
+ return False
1461
+
1462
+ def create_xid(self):
1463
+ id_ = random.randint(0, 2**128)
1464
+ return (0x1234, "%032x" % id_, "%032x" % 9)
1465
+
1466
+ def do_executemany(self, cursor, statement, parameters, context=None):
1467
+ if isinstance(parameters, tuple):
1468
+ parameters = list(parameters)
1469
+ cursor.executemany(statement, parameters)
1470
+
1471
+ def do_begin_twophase(self, connection, xid):
1472
+ connection.connection.begin(*xid)
1473
+ connection.connection.info["cx_oracle_xid"] = xid
1474
+
1475
+ def do_prepare_twophase(self, connection, xid):
1476
+ result = connection.connection.prepare()
1477
+ connection.info["cx_oracle_prepared"] = result
1478
+
1479
+ def do_rollback_twophase(
1480
+ self, connection, xid, is_prepared=True, recover=False
1481
+ ):
1482
+ self.do_rollback(connection.connection)
1483
+ # TODO: need to end XA state here
1484
+
1485
+ def do_commit_twophase(
1486
+ self, connection, xid, is_prepared=True, recover=False
1487
+ ):
1488
+ if not is_prepared:
1489
+ self.do_commit(connection.connection)
1490
+ else:
1491
+ if recover:
1492
+ raise NotImplementedError(
1493
+ "2pc recovery not implemented for cx_Oracle"
1494
+ )
1495
+ oci_prepared = connection.info["cx_oracle_prepared"]
1496
+ if oci_prepared:
1497
+ self.do_commit(connection.connection)
1498
+ # TODO: need to end XA state here
1499
+
1500
+ def do_set_input_sizes(self, cursor, list_of_tuples, context):
1501
+ if self.positional:
1502
+ # not usually used, here to support if someone is modifying
1503
+ # the dialect to use positional style
1504
+ cursor.setinputsizes(
1505
+ *[dbtype for key, dbtype, sqltype in list_of_tuples]
1506
+ )
1507
+ else:
1508
+ collection = (
1509
+ (key, dbtype)
1510
+ for key, dbtype, sqltype in list_of_tuples
1511
+ if dbtype
1512
+ )
1513
+
1514
+ cursor.setinputsizes(**{key: dbtype for key, dbtype in collection})
1515
+
1516
+ def do_recover_twophase(self, connection):
1517
+ raise NotImplementedError(
1518
+ "recover two phase query for cx_Oracle not implemented"
1519
+ )
1520
+
1521
+
1522
+ dialect = OracleDialect_cx_oracle