base.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602
  1. # oracle/base.py
  2. # Copyright (C) 2005-2017 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: http://www.opensource.org/licenses/mit-license.php
  7. """
  8. .. dialect:: oracle
  9. :name: Oracle
  10. Oracle version 8 through current (11g at the time of this writing) are
  11. supported.
  12. Connect Arguments
  13. -----------------
  14. The dialect supports several :func:`~sqlalchemy.create_engine()` arguments
  15. which affect the behavior of the dialect regardless of driver in use.
  16. * ``use_ansi`` - Use ANSI JOIN constructs (see the section on Oracle 8).
  17. Defaults to ``True``. If ``False``, Oracle-8 compatible constructs are used
  18. for joins.
  19. * ``optimize_limits`` - defaults to ``False``. see the section on
  20. LIMIT/OFFSET.
  21. * ``use_binds_for_limits`` - defaults to ``True``. see the section on
  22. LIMIT/OFFSET.
  23. Auto Increment Behavior
  24. -----------------------
  25. SQLAlchemy Table objects which include integer primary keys are usually
  26. assumed to have "autoincrementing" behavior, meaning they can generate their
  27. own primary key values upon INSERT. Since Oracle has no "autoincrement"
  28. feature, SQLAlchemy relies upon sequences to produce these values. With the
  29. Oracle dialect, *a sequence must always be explicitly specified to enable
  30. autoincrement*. This is divergent with the majority of documentation
  31. examples which assume the usage of an autoincrement-capable database. To
  32. specify sequences, use the sqlalchemy.schema.Sequence object which is passed
  33. to a Column construct::
  34. t = Table('mytable', metadata,
  35. Column('id', Integer, Sequence('id_seq'), primary_key=True),
  36. Column(...), ...
  37. )
  38. This step is also required when using table reflection, i.e. autoload=True::
  39. t = Table('mytable', metadata,
  40. Column('id', Integer, Sequence('id_seq'), primary_key=True),
  41. autoload=True
  42. )
  43. Identifier Casing
  44. -----------------
  45. In Oracle, the data dictionary represents all case insensitive identifier
  46. names using UPPERCASE text. SQLAlchemy on the other hand considers an
  47. all-lower case identifier name to be case insensitive. The Oracle dialect
  48. converts all case insensitive identifiers to and from those two formats during
  49. schema level communication, such as reflection of tables and indexes. Using
  50. an UPPERCASE name on the SQLAlchemy side indicates a case sensitive
  51. identifier, and SQLAlchemy will quote the name - this will cause mismatches
  52. against data dictionary data received from Oracle, so unless identifier names
  53. have been truly created as case sensitive (i.e. using quoted names), all
  54. lowercase names should be used on the SQLAlchemy side.
  55. LIMIT/OFFSET Support
  56. --------------------
  57. Oracle has no support for the LIMIT or OFFSET keywords. SQLAlchemy uses
  58. a wrapped subquery approach in conjunction with ROWNUM. The exact methodology
  59. is taken from
  60. http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html .
  61. There are two options which affect its behavior:
  62. * the "FIRST ROWS()" optimization keyword is not used by default. To enable
  63. the usage of this optimization directive, specify ``optimize_limits=True``
  64. to :func:`.create_engine`.
  65. * the values passed for the limit/offset are sent as bound parameters. Some
  66. users have observed that Oracle produces a poor query plan when the values
  67. are sent as binds and not rendered literally. To render the limit/offset
  68. values literally within the SQL statement, specify
  69. ``use_binds_for_limits=False`` to :func:`.create_engine`.
  70. Some users have reported better performance when the entirely different
  71. approach of a window query is used, i.e. ROW_NUMBER() OVER (ORDER BY), to
  72. provide LIMIT/OFFSET (note that the majority of users don't observe this).
  73. To suit this case the method used for LIMIT/OFFSET can be replaced entirely.
  74. See the recipe at
  75. http://www.sqlalchemy.org/trac/wiki/UsageRecipes/WindowFunctionsByDefault
  76. which installs a select compiler that overrides the generation of limit/offset
  77. with a window function.
  78. .. _oracle_returning:
  79. RETURNING Support
  80. -----------------
  81. The Oracle database supports a limited form of RETURNING, in order to retrieve
  82. result sets of matched rows from INSERT, UPDATE and DELETE statements.
  83. Oracle's RETURNING..INTO syntax only supports one row being returned, as it
  84. relies upon OUT parameters in order to function. In addition, supported
  85. DBAPIs have further limitations (see :ref:`cx_oracle_returning`).
  86. SQLAlchemy's "implicit returning" feature, which employs RETURNING within an
  87. INSERT and sometimes an UPDATE statement in order to fetch newly generated
  88. primary key values and other SQL defaults and expressions, is normally enabled
  89. on the Oracle backend. By default, "implicit returning" typically only
  90. fetches the value of a single ``nextval(some_seq)`` expression embedded into
  91. an INSERT in order to increment a sequence within an INSERT statement and get
  92. the value back at the same time. To disable this feature across the board,
  93. specify ``implicit_returning=False`` to :func:`.create_engine`::
  94. engine = create_engine("oracle://scott:tiger@dsn",
  95. implicit_returning=False)
  96. Implicit returning can also be disabled on a table-by-table basis as a table
  97. option::
  98. # Core Table
  99. my_table = Table("my_table", metadata, ..., implicit_returning=False)
  100. # declarative
  101. class MyClass(Base):
  102. __tablename__ = 'my_table'
  103. __table_args__ = {"implicit_returning": False}
  104. .. seealso::
  105. :ref:`cx_oracle_returning` - additional cx_oracle-specific restrictions on
  106. implicit returning.
  107. ON UPDATE CASCADE
  108. -----------------
  109. Oracle doesn't have native ON UPDATE CASCADE functionality. A trigger based
  110. solution is available at
  111. http://asktom.oracle.com/tkyte/update_cascade/index.html .
  112. When using the SQLAlchemy ORM, the ORM has limited ability to manually issue
  113. cascading updates - specify ForeignKey objects using the
  114. "deferrable=True, initially='deferred'" keyword arguments,
  115. and specify "passive_updates=False" on each relationship().
  116. Oracle 8 Compatibility
  117. ----------------------
  118. When Oracle 8 is detected, the dialect internally configures itself to the
  119. following behaviors:
  120. * the use_ansi flag is set to False. This has the effect of converting all
  121. JOIN phrases into the WHERE clause, and in the case of LEFT OUTER JOIN
  122. makes use of Oracle's (+) operator.
  123. * the NVARCHAR2 and NCLOB datatypes are no longer generated as DDL when
  124. the :class:`~sqlalchemy.types.Unicode` is used - VARCHAR2 and CLOB are
  125. issued instead. This because these types don't seem to work correctly on
  126. Oracle 8 even though they are available. The
  127. :class:`~sqlalchemy.types.NVARCHAR` and
  128. :class:`~sqlalchemy.dialects.oracle.NCLOB` types will always generate
  129. NVARCHAR2 and NCLOB.
  130. * the "native unicode" mode is disabled when using cx_oracle, i.e. SQLAlchemy
  131. encodes all Python unicode objects to "string" before passing in as bind
  132. parameters.
  133. Synonym/DBLINK Reflection
  134. -------------------------
  135. When using reflection with Table objects, the dialect can optionally search
  136. for tables indicated by synonyms, either in local or remote schemas or
  137. accessed over DBLINK, by passing the flag ``oracle_resolve_synonyms=True`` as
  138. a keyword argument to the :class:`.Table` construct::
  139. some_table = Table('some_table', autoload=True,
  140. autoload_with=some_engine,
  141. oracle_resolve_synonyms=True)
  142. When this flag is set, the given name (such as ``some_table`` above) will
  143. be searched not just in the ``ALL_TABLES`` view, but also within the
  144. ``ALL_SYNONYMS`` view to see if this name is actually a synonym to another
  145. name. If the synonym is located and refers to a DBLINK, the oracle dialect
  146. knows how to locate the table's information using DBLINK syntax(e.g.
  147. ``@dblink``).
  148. ``oracle_resolve_synonyms`` is accepted wherever reflection arguments are
  149. accepted, including methods such as :meth:`.MetaData.reflect` and
  150. :meth:`.Inspector.get_columns`.
  151. If synonyms are not in use, this flag should be left disabled.
  152. Table names with SYSTEM/SYSAUX tablespaces
  153. -------------------------------------------
  154. The :meth:`.Inspector.get_table_names` and
  155. :meth:`.Inspector.get_temp_table_names`
  156. methods each return a list of table names for the current engine. These methods
  157. are also part of the reflection which occurs within an operation such as
  158. :meth:`.MetaData.reflect`. By default, these operations exclude the ``SYSTEM``
  159. and ``SYSAUX`` tablespaces from the operation. In order to change this, the
  160. default list of tablespaces excluded can be changed at the engine level using
  161. the ``exclude_tablespaces`` parameter::
  162. # exclude SYSAUX and SOME_TABLESPACE, but not SYSTEM
  163. e = create_engine(
  164. "oracle://scott:tiger@xe",
  165. exclude_tablespaces=["SYSAUX", "SOME_TABLESPACE"])
  166. .. versionadded:: 1.1
  167. DateTime Compatibility
  168. ----------------------
  169. Oracle has no datatype known as ``DATETIME``, it instead has only ``DATE``,
  170. which can actually store a date and time value. For this reason, the Oracle
  171. dialect provides a type :class:`.oracle.DATE` which is a subclass of
  172. :class:`.DateTime`. This type has no special behavior, and is only
  173. present as a "marker" for this type; additionally, when a database column
  174. is reflected and the type is reported as ``DATE``, the time-supporting
  175. :class:`.oracle.DATE` type is used.
  176. .. versionchanged:: 0.9.4 Added :class:`.oracle.DATE` to subclass
  177. :class:`.DateTime`. This is a change as previous versions
  178. would reflect a ``DATE`` column as :class:`.types.DATE`, which subclasses
  179. :class:`.Date`. The only significance here is for schemes that are
  180. examining the type of column for use in special Python translations or
  181. for migrating schemas to other database backends.
  182. .. _oracle_table_options:
  183. Oracle Table Options
  184. -------------------------
  185. The CREATE TABLE phrase supports the following options with Oracle
  186. in conjunction with the :class:`.Table` construct:
  187. * ``ON COMMIT``::
  188. Table(
  189. "some_table", metadata, ...,
  190. prefixes=['GLOBAL TEMPORARY'], oracle_on_commit='PRESERVE ROWS')
  191. .. versionadded:: 1.0.0
  192. * ``COMPRESS``::
  193. Table('mytable', metadata, Column('data', String(32)),
  194. oracle_compress=True)
  195. Table('mytable', metadata, Column('data', String(32)),
  196. oracle_compress=6)
  197. The ``oracle_compress`` parameter accepts either an integer compression
  198. level, or ``True`` to use the default compression level.
  199. .. versionadded:: 1.0.0
  200. .. _oracle_index_options:
  201. Oracle Specific Index Options
  202. -----------------------------
  203. Bitmap Indexes
  204. ~~~~~~~~~~~~~~
  205. You can specify the ``oracle_bitmap`` parameter to create a bitmap index
  206. instead of a B-tree index::
  207. Index('my_index', my_table.c.data, oracle_bitmap=True)
  208. Bitmap indexes cannot be unique and cannot be compressed. SQLAlchemy will not
  209. check for such limitations, only the database will.
  210. .. versionadded:: 1.0.0
  211. Index compression
  212. ~~~~~~~~~~~~~~~~~
  213. Oracle has a more efficient storage mode for indexes containing lots of
  214. repeated values. Use the ``oracle_compress`` parameter to turn on key c
  215. ompression::
  216. Index('my_index', my_table.c.data, oracle_compress=True)
  217. Index('my_index', my_table.c.data1, my_table.c.data2, unique=True,
  218. oracle_compress=1)
  219. The ``oracle_compress`` parameter accepts either an integer specifying the
  220. number of prefix columns to compress, or ``True`` to use the default (all
  221. columns for non-unique indexes, all but the last column for unique indexes).
  222. .. versionadded:: 1.0.0
  223. """
  224. import re
  225. from sqlalchemy import util, sql
  226. from sqlalchemy.engine import default, reflection
  227. from sqlalchemy.sql import compiler, visitors, expression, util as sql_util
  228. from sqlalchemy.sql import operators as sql_operators
  229. from sqlalchemy.sql.elements import quoted_name
  230. from sqlalchemy import types as sqltypes, schema as sa_schema
  231. from sqlalchemy.types import VARCHAR, NVARCHAR, CHAR, \
  232. BLOB, CLOB, TIMESTAMP, FLOAT
  233. RESERVED_WORDS = \
  234. set('SHARE RAW DROP BETWEEN FROM DESC OPTION PRIOR LONG THEN '
  235. 'DEFAULT ALTER IS INTO MINUS INTEGER NUMBER GRANT IDENTIFIED '
  236. 'ALL TO ORDER ON FLOAT DATE HAVING CLUSTER NOWAIT RESOURCE '
  237. 'ANY TABLE INDEX FOR UPDATE WHERE CHECK SMALLINT WITH DELETE '
  238. 'BY ASC REVOKE LIKE SIZE RENAME NOCOMPRESS NULL GROUP VALUES '
  239. 'AS IN VIEW EXCLUSIVE COMPRESS SYNONYM SELECT INSERT EXISTS '
  240. 'NOT TRIGGER ELSE CREATE INTERSECT PCTFREE DISTINCT USER '
  241. 'CONNECT SET MODE OF UNIQUE VARCHAR2 VARCHAR LOCK OR CHAR '
  242. 'DECIMAL UNION PUBLIC AND START UID COMMENT CURRENT LEVEL'.split())
  243. NO_ARG_FNS = set('UID CURRENT_DATE SYSDATE USER '
  244. 'CURRENT_TIME CURRENT_TIMESTAMP'.split())
  245. class RAW(sqltypes._Binary):
  246. __visit_name__ = 'RAW'
  247. OracleRaw = RAW
  248. class NCLOB(sqltypes.Text):
  249. __visit_name__ = 'NCLOB'
  250. class VARCHAR2(VARCHAR):
  251. __visit_name__ = 'VARCHAR2'
  252. NVARCHAR2 = NVARCHAR
  253. class NUMBER(sqltypes.Numeric, sqltypes.Integer):
  254. __visit_name__ = 'NUMBER'
  255. def __init__(self, precision=None, scale=None, asdecimal=None):
  256. if asdecimal is None:
  257. asdecimal = bool(scale and scale > 0)
  258. super(NUMBER, self).__init__(
  259. precision=precision, scale=scale, asdecimal=asdecimal)
  260. def adapt(self, impltype):
  261. ret = super(NUMBER, self).adapt(impltype)
  262. # leave a hint for the DBAPI handler
  263. ret._is_oracle_number = True
  264. return ret
  265. @property
  266. def _type_affinity(self):
  267. if bool(self.scale and self.scale > 0):
  268. return sqltypes.Numeric
  269. else:
  270. return sqltypes.Integer
  271. class DOUBLE_PRECISION(sqltypes.Numeric):
  272. __visit_name__ = 'DOUBLE_PRECISION'
  273. def __init__(self, precision=None, scale=None, asdecimal=None):
  274. if asdecimal is None:
  275. asdecimal = False
  276. super(DOUBLE_PRECISION, self).__init__(
  277. precision=precision, scale=scale, asdecimal=asdecimal)
  278. class BFILE(sqltypes.LargeBinary):
  279. __visit_name__ = 'BFILE'
  280. class LONG(sqltypes.Text):
  281. __visit_name__ = 'LONG'
  282. class DATE(sqltypes.DateTime):
  283. """Provide the oracle DATE type.
  284. This type has no special Python behavior, except that it subclasses
  285. :class:`.types.DateTime`; this is to suit the fact that the Oracle
  286. ``DATE`` type supports a time value.
  287. .. versionadded:: 0.9.4
  288. """
  289. __visit_name__ = 'DATE'
  290. def _compare_type_affinity(self, other):
  291. return other._type_affinity in (sqltypes.DateTime, sqltypes.Date)
  292. class INTERVAL(sqltypes.TypeEngine):
  293. __visit_name__ = 'INTERVAL'
  294. def __init__(self,
  295. day_precision=None,
  296. second_precision=None):
  297. """Construct an INTERVAL.
  298. Note that only DAY TO SECOND intervals are currently supported.
  299. This is due to a lack of support for YEAR TO MONTH intervals
  300. within available DBAPIs (cx_oracle and zxjdbc).
  301. :param day_precision: the day precision value. this is the number of
  302. digits to store for the day field. Defaults to "2"
  303. :param second_precision: the second precision value. this is the
  304. number of digits to store for the fractional seconds field.
  305. Defaults to "6".
  306. """
  307. self.day_precision = day_precision
  308. self.second_precision = second_precision
  309. @classmethod
  310. def _adapt_from_generic_interval(cls, interval):
  311. return INTERVAL(day_precision=interval.day_precision,
  312. second_precision=interval.second_precision)
  313. @property
  314. def _type_affinity(self):
  315. return sqltypes.Interval
  316. class ROWID(sqltypes.TypeEngine):
  317. """Oracle ROWID type.
  318. When used in a cast() or similar, generates ROWID.
  319. """
  320. __visit_name__ = 'ROWID'
  321. class _OracleBoolean(sqltypes.Boolean):
  322. def get_dbapi_type(self, dbapi):
  323. return dbapi.NUMBER
  324. colspecs = {
  325. sqltypes.Boolean: _OracleBoolean,
  326. sqltypes.Interval: INTERVAL,
  327. sqltypes.DateTime: DATE
  328. }
  329. ischema_names = {
  330. 'VARCHAR2': VARCHAR,
  331. 'NVARCHAR2': NVARCHAR,
  332. 'CHAR': CHAR,
  333. 'DATE': DATE,
  334. 'NUMBER': NUMBER,
  335. 'BLOB': BLOB,
  336. 'BFILE': BFILE,
  337. 'CLOB': CLOB,
  338. 'NCLOB': NCLOB,
  339. 'TIMESTAMP': TIMESTAMP,
  340. 'TIMESTAMP WITH TIME ZONE': TIMESTAMP,
  341. 'INTERVAL DAY TO SECOND': INTERVAL,
  342. 'RAW': RAW,
  343. 'FLOAT': FLOAT,
  344. 'DOUBLE PRECISION': DOUBLE_PRECISION,
  345. 'LONG': LONG,
  346. }
  347. class OracleTypeCompiler(compiler.GenericTypeCompiler):
  348. # Note:
  349. # Oracle DATE == DATETIME
  350. # Oracle does not allow milliseconds in DATE
  351. # Oracle does not support TIME columns
  352. def visit_datetime(self, type_, **kw):
  353. return self.visit_DATE(type_, **kw)
  354. def visit_float(self, type_, **kw):
  355. return self.visit_FLOAT(type_, **kw)
  356. def visit_unicode(self, type_, **kw):
  357. if self.dialect._supports_nchar:
  358. return self.visit_NVARCHAR2(type_, **kw)
  359. else:
  360. return self.visit_VARCHAR2(type_, **kw)
  361. def visit_INTERVAL(self, type_, **kw):
  362. return "INTERVAL DAY%s TO SECOND%s" % (
  363. type_.day_precision is not None and
  364. "(%d)" % type_.day_precision or
  365. "",
  366. type_.second_precision is not None and
  367. "(%d)" % type_.second_precision or
  368. "",
  369. )
  370. def visit_LONG(self, type_, **kw):
  371. return "LONG"
  372. def visit_TIMESTAMP(self, type_, **kw):
  373. if type_.timezone:
  374. return "TIMESTAMP WITH TIME ZONE"
  375. else:
  376. return "TIMESTAMP"
  377. def visit_DOUBLE_PRECISION(self, type_, **kw):
  378. return self._generate_numeric(type_, "DOUBLE PRECISION", **kw)
  379. def visit_NUMBER(self, type_, **kw):
  380. return self._generate_numeric(type_, "NUMBER", **kw)
  381. def _generate_numeric(self, type_, name, precision=None, scale=None, **kw):
  382. if precision is None:
  383. precision = type_.precision
  384. if scale is None:
  385. scale = getattr(type_, 'scale', None)
  386. if precision is None:
  387. return name
  388. elif scale is None:
  389. n = "%(name)s(%(precision)s)"
  390. return n % {'name': name, 'precision': precision}
  391. else:
  392. n = "%(name)s(%(precision)s, %(scale)s)"
  393. return n % {'name': name, 'precision': precision, 'scale': scale}
  394. def visit_string(self, type_, **kw):
  395. return self.visit_VARCHAR2(type_, **kw)
  396. def visit_VARCHAR2(self, type_, **kw):
  397. return self._visit_varchar(type_, '', '2')
  398. def visit_NVARCHAR2(self, type_, **kw):
  399. return self._visit_varchar(type_, 'N', '2')
  400. visit_NVARCHAR = visit_NVARCHAR2
  401. def visit_VARCHAR(self, type_, **kw):
  402. return self._visit_varchar(type_, '', '')
  403. def _visit_varchar(self, type_, n, num):
  404. if not type_.length:
  405. return "%(n)sVARCHAR%(two)s" % {'two': num, 'n': n}
  406. elif not n and self.dialect._supports_char_length:
  407. varchar = "VARCHAR%(two)s(%(length)s CHAR)"
  408. return varchar % {'length': type_.length, 'two': num}
  409. else:
  410. varchar = "%(n)sVARCHAR%(two)s(%(length)s)"
  411. return varchar % {'length': type_.length, 'two': num, 'n': n}
  412. def visit_text(self, type_, **kw):
  413. return self.visit_CLOB(type_, **kw)
  414. def visit_unicode_text(self, type_, **kw):
  415. if self.dialect._supports_nchar:
  416. return self.visit_NCLOB(type_, **kw)
  417. else:
  418. return self.visit_CLOB(type_, **kw)
  419. def visit_large_binary(self, type_, **kw):
  420. return self.visit_BLOB(type_, **kw)
  421. def visit_big_integer(self, type_, **kw):
  422. return self.visit_NUMBER(type_, precision=19, **kw)
  423. def visit_boolean(self, type_, **kw):
  424. return self.visit_SMALLINT(type_, **kw)
  425. def visit_RAW(self, type_, **kw):
  426. if type_.length:
  427. return "RAW(%(length)s)" % {'length': type_.length}
  428. else:
  429. return "RAW"
  430. def visit_ROWID(self, type_, **kw):
  431. return "ROWID"
  432. class OracleCompiler(compiler.SQLCompiler):
  433. """Oracle compiler modifies the lexical structure of Select
  434. statements to work under non-ANSI configured Oracle databases, if
  435. the use_ansi flag is False.
  436. """
  437. compound_keywords = util.update_copy(
  438. compiler.SQLCompiler.compound_keywords,
  439. {
  440. expression.CompoundSelect.EXCEPT: 'MINUS'
  441. }
  442. )
  443. def __init__(self, *args, **kwargs):
  444. self.__wheres = {}
  445. self._quoted_bind_names = {}
  446. super(OracleCompiler, self).__init__(*args, **kwargs)
  447. def visit_mod_binary(self, binary, operator, **kw):
  448. return "mod(%s, %s)" % (self.process(binary.left, **kw),
  449. self.process(binary.right, **kw))
  450. def visit_now_func(self, fn, **kw):
  451. return "CURRENT_TIMESTAMP"
  452. def visit_char_length_func(self, fn, **kw):
  453. return "LENGTH" + self.function_argspec(fn, **kw)
  454. def visit_match_op_binary(self, binary, operator, **kw):
  455. return "CONTAINS (%s, %s)" % (self.process(binary.left),
  456. self.process(binary.right))
  457. def visit_true(self, expr, **kw):
  458. return '1'
  459. def visit_false(self, expr, **kw):
  460. return '0'
  461. def get_cte_preamble(self, recursive):
  462. return "WITH"
  463. def get_select_hint_text(self, byfroms):
  464. return " ".join(
  465. "/*+ %s */" % text for table, text in byfroms.items()
  466. )
  467. def function_argspec(self, fn, **kw):
  468. if len(fn.clauses) > 0 or fn.name.upper() not in NO_ARG_FNS:
  469. return compiler.SQLCompiler.function_argspec(self, fn, **kw)
  470. else:
  471. return ""
  472. def default_from(self):
  473. """Called when a ``SELECT`` statement has no froms,
  474. and no ``FROM`` clause is to be appended.
  475. The Oracle compiler tacks a "FROM DUAL" to the statement.
  476. """
  477. return " FROM DUAL"
  478. def visit_join(self, join, **kwargs):
  479. if self.dialect.use_ansi:
  480. return compiler.SQLCompiler.visit_join(self, join, **kwargs)
  481. else:
  482. kwargs['asfrom'] = True
  483. if isinstance(join.right, expression.FromGrouping):
  484. right = join.right.element
  485. else:
  486. right = join.right
  487. return self.process(join.left, **kwargs) + \
  488. ", " + self.process(right, **kwargs)
  489. def _get_nonansi_join_whereclause(self, froms):
  490. clauses = []
  491. def visit_join(join):
  492. if join.isouter:
  493. def visit_binary(binary):
  494. if binary.operator == sql_operators.eq:
  495. if join.right.is_derived_from(binary.left.table):
  496. binary.left = _OuterJoinColumn(binary.left)
  497. elif join.right.is_derived_from(binary.right.table):
  498. binary.right = _OuterJoinColumn(binary.right)
  499. clauses.append(visitors.cloned_traverse(
  500. join.onclause, {}, {'binary': visit_binary}))
  501. else:
  502. clauses.append(join.onclause)
  503. for j in join.left, join.right:
  504. if isinstance(j, expression.Join):
  505. visit_join(j)
  506. elif isinstance(j, expression.FromGrouping):
  507. visit_join(j.element)
  508. for f in froms:
  509. if isinstance(f, expression.Join):
  510. visit_join(f)
  511. if not clauses:
  512. return None
  513. else:
  514. return sql.and_(*clauses)
  515. def visit_outer_join_column(self, vc, **kw):
  516. return self.process(vc.column, **kw) + "(+)"
  517. def visit_sequence(self, seq):
  518. return (self.dialect.identifier_preparer.format_sequence(seq) +
  519. ".nextval")
  520. def get_render_as_alias_suffix(self, alias_name_text):
  521. """Oracle doesn't like ``FROM table AS alias``"""
  522. return " " + alias_name_text
  523. def returning_clause(self, stmt, returning_cols):
  524. columns = []
  525. binds = []
  526. for i, column in enumerate(
  527. expression._select_iterables(returning_cols)):
  528. if column.type._has_column_expression:
  529. col_expr = column.type.column_expression(column)
  530. else:
  531. col_expr = column
  532. outparam = sql.outparam("ret_%d" % i, type_=column.type)
  533. self.binds[outparam.key] = outparam
  534. binds.append(
  535. self.bindparam_string(self._truncate_bindparam(outparam)))
  536. columns.append(
  537. self.process(col_expr, within_columns_clause=False))
  538. self._add_to_result_map(
  539. outparam.key, outparam.key,
  540. (column, getattr(column, 'name', None),
  541. getattr(column, 'key', None)),
  542. column.type
  543. )
  544. return 'RETURNING ' + ', '.join(columns) + " INTO " + ", ".join(binds)
  545. def _TODO_visit_compound_select(self, select):
  546. """Need to determine how to get ``LIMIT``/``OFFSET`` into a
  547. ``UNION`` for Oracle.
  548. """
  549. pass
  550. def visit_select(self, select, **kwargs):
  551. """Look for ``LIMIT`` and OFFSET in a select statement, and if
  552. so tries to wrap it in a subquery with ``rownum`` criterion.
  553. """
  554. if not getattr(select, '_oracle_visit', None):
  555. if not self.dialect.use_ansi:
  556. froms = self._display_froms_for_select(
  557. select, kwargs.get('asfrom', False))
  558. whereclause = self._get_nonansi_join_whereclause(froms)
  559. if whereclause is not None:
  560. select = select.where(whereclause)
  561. select._oracle_visit = True
  562. limit_clause = select._limit_clause
  563. offset_clause = select._offset_clause
  564. if limit_clause is not None or offset_clause is not None:
  565. # See http://www.oracle.com/technology/oramag/oracle/06-sep/\
  566. # o56asktom.html
  567. #
  568. # Generalized form of an Oracle pagination query:
  569. # select ... from (
  570. # select /*+ FIRST_ROWS(N) */ ...., rownum as ora_rn from
  571. # ( select distinct ... where ... order by ...
  572. # ) where ROWNUM <= :limit+:offset
  573. # ) where ora_rn > :offset
  574. # Outer select and "ROWNUM as ora_rn" can be dropped if
  575. # limit=0
  576. kwargs['select_wraps_for'] = select
  577. select = select._generate()
  578. select._oracle_visit = True
  579. # Wrap the middle select and add the hint
  580. limitselect = sql.select([c for c in select.c])
  581. if limit_clause is not None and \
  582. self.dialect.optimize_limits and \
  583. select._simple_int_limit:
  584. limitselect = limitselect.prefix_with(
  585. "/*+ FIRST_ROWS(%d) */" %
  586. select._limit)
  587. limitselect._oracle_visit = True
  588. limitselect._is_wrapper = True
  589. # add expressions to accommodate FOR UPDATE OF
  590. for_update = select._for_update_arg
  591. if for_update is not None and for_update.of:
  592. for_update = for_update._clone()
  593. for_update._copy_internals()
  594. for elem in for_update.of:
  595. select.append_column(elem)
  596. adapter = sql_util.ClauseAdapter(select)
  597. for_update.of = [
  598. adapter.traverse(elem)
  599. for elem in for_update.of]
  600. # If needed, add the limiting clause
  601. if limit_clause is not None:
  602. if not self.dialect.use_binds_for_limits:
  603. # use simple int limits, will raise an exception
  604. # if the limit isn't specified this way
  605. max_row = select._limit
  606. if offset_clause is not None:
  607. max_row += select._offset
  608. max_row = sql.literal_column("%d" % max_row)
  609. else:
  610. max_row = limit_clause
  611. if offset_clause is not None:
  612. max_row = max_row + offset_clause
  613. limitselect.append_whereclause(
  614. sql.literal_column("ROWNUM") <= max_row)
  615. # If needed, add the ora_rn, and wrap again with offset.
  616. if offset_clause is None:
  617. limitselect._for_update_arg = for_update
  618. select = limitselect
  619. else:
  620. limitselect = limitselect.column(
  621. sql.literal_column("ROWNUM").label("ora_rn"))
  622. limitselect._oracle_visit = True
  623. limitselect._is_wrapper = True
  624. offsetselect = sql.select(
  625. [c for c in limitselect.c if c.key != 'ora_rn'])
  626. offsetselect._oracle_visit = True
  627. offsetselect._is_wrapper = True
  628. if for_update is not None and for_update.of:
  629. for elem in for_update.of:
  630. if limitselect.corresponding_column(elem) is None:
  631. limitselect.append_column(elem)
  632. if not self.dialect.use_binds_for_limits:
  633. offset_clause = sql.literal_column(
  634. "%d" % select._offset)
  635. offsetselect.append_whereclause(
  636. sql.literal_column("ora_rn") > offset_clause)
  637. offsetselect._for_update_arg = for_update
  638. select = offsetselect
  639. return compiler.SQLCompiler.visit_select(self, select, **kwargs)
  640. def limit_clause(self, select, **kw):
  641. return ""
  642. def for_update_clause(self, select, **kw):
  643. if self.is_subquery():
  644. return ""
  645. tmp = ' FOR UPDATE'
  646. if select._for_update_arg.of:
  647. tmp += ' OF ' + ', '.join(
  648. self.process(elem, **kw) for elem in
  649. select._for_update_arg.of
  650. )
  651. if select._for_update_arg.nowait:
  652. tmp += " NOWAIT"
  653. if select._for_update_arg.skip_locked:
  654. tmp += " SKIP LOCKED"
  655. return tmp
  656. class OracleDDLCompiler(compiler.DDLCompiler):
  657. def define_constraint_cascades(self, constraint):
  658. text = ""
  659. if constraint.ondelete is not None:
  660. text += " ON DELETE %s" % constraint.ondelete
  661. # oracle has no ON UPDATE CASCADE -
  662. # its only available via triggers
  663. # http://asktom.oracle.com/tkyte/update_cascade/index.html
  664. if constraint.onupdate is not None:
  665. util.warn(
  666. "Oracle does not contain native UPDATE CASCADE "
  667. "functionality - onupdates will not be rendered for foreign "
  668. "keys. Consider using deferrable=True, initially='deferred' "
  669. "or triggers.")
  670. return text
  671. def visit_create_index(self, create):
  672. index = create.element
  673. self._verify_index_table(index)
  674. preparer = self.preparer
  675. text = "CREATE "
  676. if index.unique:
  677. text += "UNIQUE "
  678. if index.dialect_options['oracle']['bitmap']:
  679. text += "BITMAP "
  680. text += "INDEX %s ON %s (%s)" % (
  681. self._prepared_index_name(index, include_schema=True),
  682. preparer.format_table(index.table, use_schema=True),
  683. ', '.join(
  684. self.sql_compiler.process(
  685. expr,
  686. include_table=False, literal_binds=True)
  687. for expr in index.expressions)
  688. )
  689. if index.dialect_options['oracle']['compress'] is not False:
  690. if index.dialect_options['oracle']['compress'] is True:
  691. text += " COMPRESS"
  692. else:
  693. text += " COMPRESS %d" % (
  694. index.dialect_options['oracle']['compress']
  695. )
  696. return text
  697. def post_create_table(self, table):
  698. table_opts = []
  699. opts = table.dialect_options['oracle']
  700. if opts['on_commit']:
  701. on_commit_options = opts['on_commit'].replace("_", " ").upper()
  702. table_opts.append('\n ON COMMIT %s' % on_commit_options)
  703. if opts['compress']:
  704. if opts['compress'] is True:
  705. table_opts.append("\n COMPRESS")
  706. else:
  707. table_opts.append("\n COMPRESS FOR %s" % (
  708. opts['compress']
  709. ))
  710. return ''.join(table_opts)
  711. class OracleIdentifierPreparer(compiler.IdentifierPreparer):
  712. reserved_words = set([x.lower() for x in RESERVED_WORDS])
  713. illegal_initial_characters = set(
  714. (str(dig) for dig in range(0, 10))).union(["_", "$"])
  715. def _bindparam_requires_quotes(self, value):
  716. """Return True if the given identifier requires quoting."""
  717. lc_value = value.lower()
  718. return (lc_value in self.reserved_words
  719. or value[0] in self.illegal_initial_characters
  720. or not self.legal_characters.match(util.text_type(value))
  721. )
  722. def format_savepoint(self, savepoint):
  723. name = savepoint.ident.lstrip('_')
  724. return super(
  725. OracleIdentifierPreparer, self).format_savepoint(savepoint, name)
  726. class OracleExecutionContext(default.DefaultExecutionContext):
  727. def fire_sequence(self, seq, type_):
  728. return self._execute_scalar(
  729. "SELECT " +
  730. self.dialect.identifier_preparer.format_sequence(seq) +
  731. ".nextval FROM DUAL", type_)
  732. class OracleDialect(default.DefaultDialect):
  733. name = 'oracle'
  734. supports_alter = True
  735. supports_unicode_statements = False
  736. supports_unicode_binds = False
  737. max_identifier_length = 30
  738. supports_sane_rowcount = True
  739. supports_sane_multi_rowcount = False
  740. supports_simple_order_by_label = False
  741. supports_sequences = True
  742. sequences_optional = False
  743. postfetch_lastrowid = False
  744. default_paramstyle = 'named'
  745. colspecs = colspecs
  746. ischema_names = ischema_names
  747. requires_name_normalize = True
  748. supports_default_values = False
  749. supports_empty_insert = False
  750. statement_compiler = OracleCompiler
  751. ddl_compiler = OracleDDLCompiler
  752. type_compiler = OracleTypeCompiler
  753. preparer = OracleIdentifierPreparer
  754. execution_ctx_cls = OracleExecutionContext
  755. reflection_options = ('oracle_resolve_synonyms', )
  756. construct_arguments = [
  757. (sa_schema.Table, {
  758. "resolve_synonyms": False,
  759. "on_commit": None,
  760. "compress": False
  761. }),
  762. (sa_schema.Index, {
  763. "bitmap": False,
  764. "compress": False
  765. })
  766. ]
  767. def __init__(self,
  768. use_ansi=True,
  769. optimize_limits=False,
  770. use_binds_for_limits=True,
  771. exclude_tablespaces=('SYSTEM', 'SYSAUX', ),
  772. **kwargs):
  773. default.DefaultDialect.__init__(self, **kwargs)
  774. self.use_ansi = use_ansi
  775. self.optimize_limits = optimize_limits
  776. self.use_binds_for_limits = use_binds_for_limits
  777. self.exclude_tablespaces = exclude_tablespaces
  778. def initialize(self, connection):
  779. super(OracleDialect, self).initialize(connection)
  780. self.implicit_returning = self.__dict__.get(
  781. 'implicit_returning',
  782. self.server_version_info > (10, )
  783. )
  784. if self._is_oracle_8:
  785. self.colspecs = self.colspecs.copy()
  786. self.colspecs.pop(sqltypes.Interval)
  787. self.use_ansi = False
  788. @property
  789. def _is_oracle_8(self):
  790. return self.server_version_info and \
  791. self.server_version_info < (9, )
  792. @property
  793. def _supports_table_compression(self):
  794. return self.server_version_info and \
  795. self.server_version_info >= (10, 1, )
  796. @property
  797. def _supports_table_compress_for(self):
  798. return self.server_version_info and \
  799. self.server_version_info >= (11, )
  800. @property
  801. def _supports_char_length(self):
  802. return not self._is_oracle_8
  803. @property
  804. def _supports_nchar(self):
  805. return not self._is_oracle_8
  806. def do_release_savepoint(self, connection, name):
  807. # Oracle does not support RELEASE SAVEPOINT
  808. pass
  809. def has_table(self, connection, table_name, schema=None):
  810. if not schema:
  811. schema = self.default_schema_name
  812. cursor = connection.execute(
  813. sql.text("SELECT table_name FROM all_tables "
  814. "WHERE table_name = :name AND owner = :schema_name"),
  815. name=self.denormalize_name(table_name),
  816. schema_name=self.denormalize_name(schema))
  817. return cursor.first() is not None
  818. def has_sequence(self, connection, sequence_name, schema=None):
  819. if not schema:
  820. schema = self.default_schema_name
  821. cursor = connection.execute(
  822. sql.text("SELECT sequence_name FROM all_sequences "
  823. "WHERE sequence_name = :name AND "
  824. "sequence_owner = :schema_name"),
  825. name=self.denormalize_name(sequence_name),
  826. schema_name=self.denormalize_name(schema))
  827. return cursor.first() is not None
  828. def normalize_name(self, name):
  829. if name is None:
  830. return None
  831. if util.py2k:
  832. if isinstance(name, str):
  833. name = name.decode(self.encoding)
  834. if name.upper() == name and not \
  835. self.identifier_preparer._requires_quotes(name.lower()):
  836. return name.lower()
  837. elif name.lower() == name:
  838. return quoted_name(name, quote=True)
  839. else:
  840. return name
  841. def denormalize_name(self, name):
  842. if name is None:
  843. return None
  844. elif name.lower() == name and not \
  845. self.identifier_preparer._requires_quotes(name.lower()):
  846. name = name.upper()
  847. if util.py2k:
  848. if not self.supports_unicode_binds:
  849. name = name.encode(self.encoding)
  850. else:
  851. name = unicode(name)
  852. return name
  853. def _get_default_schema_name(self, connection):
  854. return self.normalize_name(
  855. connection.execute('SELECT USER FROM DUAL').scalar())
  856. def _resolve_synonym(self, connection, desired_owner=None,
  857. desired_synonym=None, desired_table=None):
  858. """search for a local synonym matching the given desired owner/name.
  859. if desired_owner is None, attempts to locate a distinct owner.
  860. returns the actual name, owner, dblink name, and synonym name if
  861. found.
  862. """
  863. q = "SELECT owner, table_owner, table_name, db_link, "\
  864. "synonym_name FROM all_synonyms WHERE "
  865. clauses = []
  866. params = {}
  867. if desired_synonym:
  868. clauses.append("synonym_name = :synonym_name")
  869. params['synonym_name'] = desired_synonym
  870. if desired_owner:
  871. clauses.append("owner = :desired_owner")
  872. params['desired_owner'] = desired_owner
  873. if desired_table:
  874. clauses.append("table_name = :tname")
  875. params['tname'] = desired_table
  876. q += " AND ".join(clauses)
  877. result = connection.execute(sql.text(q), **params)
  878. if desired_owner:
  879. row = result.first()
  880. if row:
  881. return (row['table_name'], row['table_owner'],
  882. row['db_link'], row['synonym_name'])
  883. else:
  884. return None, None, None, None
  885. else:
  886. rows = result.fetchall()
  887. if len(rows) > 1:
  888. raise AssertionError(
  889. "There are multiple tables visible to the schema, you "
  890. "must specify owner")
  891. elif len(rows) == 1:
  892. row = rows[0]
  893. return (row['table_name'], row['table_owner'],
  894. row['db_link'], row['synonym_name'])
  895. else:
  896. return None, None, None, None
  897. @reflection.cache
  898. def _prepare_reflection_args(self, connection, table_name, schema=None,
  899. resolve_synonyms=False, dblink='', **kw):
  900. if resolve_synonyms:
  901. actual_name, owner, dblink, synonym = self._resolve_synonym(
  902. connection,
  903. desired_owner=self.denormalize_name(schema),
  904. desired_synonym=self.denormalize_name(table_name)
  905. )
  906. else:
  907. actual_name, owner, dblink, synonym = None, None, None, None
  908. if not actual_name:
  909. actual_name = self.denormalize_name(table_name)
  910. if dblink:
  911. # using user_db_links here since all_db_links appears
  912. # to have more restricted permissions.
  913. # http://docs.oracle.com/cd/B28359_01/server.111/b28310/ds_admin005.htm
  914. # will need to hear from more users if we are doing
  915. # the right thing here. See [ticket:2619]
  916. owner = connection.scalar(
  917. sql.text("SELECT username FROM user_db_links "
  918. "WHERE db_link=:link"), link=dblink)
  919. dblink = "@" + dblink
  920. elif not owner:
  921. owner = self.denormalize_name(schema or self.default_schema_name)
  922. return (actual_name, owner, dblink or '', synonym)
  923. @reflection.cache
  924. def get_schema_names(self, connection, **kw):
  925. s = "SELECT username FROM all_users ORDER BY username"
  926. cursor = connection.execute(s,)
  927. return [self.normalize_name(row[0]) for row in cursor]
  928. @reflection.cache
  929. def get_table_names(self, connection, schema=None, **kw):
  930. schema = self.denormalize_name(schema or self.default_schema_name)
  931. # note that table_names() isn't loading DBLINKed or synonym'ed tables
  932. if schema is None:
  933. schema = self.default_schema_name
  934. sql_str = "SELECT table_name FROM all_tables WHERE "
  935. if self.exclude_tablespaces:
  936. sql_str += (
  937. "nvl(tablespace_name, 'no tablespace') "
  938. "NOT IN (%s) AND " % (
  939. ', '.join(["'%s'" % ts for ts in self.exclude_tablespaces])
  940. )
  941. )
  942. sql_str += (
  943. "OWNER = :owner "
  944. "AND IOT_NAME IS NULL "
  945. "AND DURATION IS NULL")
  946. cursor = connection.execute(sql.text(sql_str), owner=schema)
  947. return [self.normalize_name(row[0]) for row in cursor]
  948. @reflection.cache
  949. def get_temp_table_names(self, connection, **kw):
  950. schema = self.denormalize_name(self.default_schema_name)
  951. sql_str = "SELECT table_name FROM all_tables WHERE "
  952. if self.exclude_tablespaces:
  953. sql_str += (
  954. "nvl(tablespace_name, 'no tablespace') "
  955. "NOT IN (%s) AND " % (
  956. ', '.join(["'%s'" % ts for ts in self.exclude_tablespaces])
  957. )
  958. )
  959. sql_str += (
  960. "OWNER = :owner "
  961. "AND IOT_NAME IS NULL "
  962. "AND DURATION IS NOT NULL")
  963. cursor = connection.execute(sql.text(sql_str), owner=schema)
  964. return [self.normalize_name(row[0]) for row in cursor]
  965. @reflection.cache
  966. def get_view_names(self, connection, schema=None, **kw):
  967. schema = self.denormalize_name(schema or self.default_schema_name)
  968. s = sql.text("SELECT view_name FROM all_views WHERE owner = :owner")
  969. cursor = connection.execute(s, owner=self.denormalize_name(schema))
  970. return [self.normalize_name(row[0]) for row in cursor]
  971. @reflection.cache
  972. def get_table_options(self, connection, table_name, schema=None, **kw):
  973. options = {}
  974. resolve_synonyms = kw.get('oracle_resolve_synonyms', False)
  975. dblink = kw.get('dblink', '')
  976. info_cache = kw.get('info_cache')
  977. (table_name, schema, dblink, synonym) = \
  978. self._prepare_reflection_args(connection, table_name, schema,
  979. resolve_synonyms, dblink,
  980. info_cache=info_cache)
  981. params = {"table_name": table_name}
  982. columns = ["table_name"]
  983. if self._supports_table_compression:
  984. columns.append("compression")
  985. if self._supports_table_compress_for:
  986. columns.append("compress_for")
  987. text = "SELECT %(columns)s "\
  988. "FROM ALL_TABLES%(dblink)s "\
  989. "WHERE table_name = :table_name"
  990. if schema is not None:
  991. params['owner'] = schema
  992. text += " AND owner = :owner "
  993. text = text % {'dblink': dblink, 'columns': ", ".join(columns)}
  994. result = connection.execute(sql.text(text), **params)
  995. enabled = dict(DISABLED=False, ENABLED=True)
  996. row = result.first()
  997. if row:
  998. if "compression" in row and enabled.get(row.compression, False):
  999. if "compress_for" in row:
  1000. options['oracle_compress'] = row.compress_for
  1001. else:
  1002. options['oracle_compress'] = True
  1003. return options
  1004. @reflection.cache
  1005. def get_columns(self, connection, table_name, schema=None, **kw):
  1006. """
  1007. kw arguments can be:
  1008. oracle_resolve_synonyms
  1009. dblink
  1010. """
  1011. resolve_synonyms = kw.get('oracle_resolve_synonyms', False)
  1012. dblink = kw.get('dblink', '')
  1013. info_cache = kw.get('info_cache')
  1014. (table_name, schema, dblink, synonym) = \
  1015. self._prepare_reflection_args(connection, table_name, schema,
  1016. resolve_synonyms, dblink,
  1017. info_cache=info_cache)
  1018. columns = []
  1019. if self._supports_char_length:
  1020. char_length_col = 'char_length'
  1021. else:
  1022. char_length_col = 'data_length'
  1023. params = {"table_name": table_name}
  1024. text = "SELECT column_name, data_type, %(char_length_col)s, "\
  1025. "data_precision, data_scale, "\
  1026. "nullable, data_default FROM ALL_TAB_COLUMNS%(dblink)s "\
  1027. "WHERE table_name = :table_name"
  1028. if schema is not None:
  1029. params['owner'] = schema
  1030. text += " AND owner = :owner "
  1031. text += " ORDER BY column_id"
  1032. text = text % {'dblink': dblink, 'char_length_col': char_length_col}
  1033. c = connection.execute(sql.text(text), **params)
  1034. for row in c:
  1035. (colname, orig_colname, coltype, length, precision, scale, nullable, default) = \
  1036. (self.normalize_name(row[0]), row[0], row[1], row[
  1037. 2], row[3], row[4], row[5] == 'Y', row[6])
  1038. if coltype == 'NUMBER':
  1039. coltype = NUMBER(precision, scale)
  1040. elif coltype in ('VARCHAR2', 'NVARCHAR2', 'CHAR'):
  1041. coltype = self.ischema_names.get(coltype)(length)
  1042. elif 'WITH TIME ZONE' in coltype:
  1043. coltype = TIMESTAMP(timezone=True)
  1044. else:
  1045. coltype = re.sub(r'\(\d+\)', '', coltype)
  1046. try:
  1047. coltype = self.ischema_names[coltype]
  1048. except KeyError:
  1049. util.warn("Did not recognize type '%s' of column '%s'" %
  1050. (coltype, colname))
  1051. coltype = sqltypes.NULLTYPE
  1052. cdict = {
  1053. 'name': colname,
  1054. 'type': coltype,
  1055. 'nullable': nullable,
  1056. 'default': default,
  1057. 'autoincrement': 'auto',
  1058. }
  1059. if orig_colname.lower() == orig_colname:
  1060. cdict['quote'] = True
  1061. columns.append(cdict)
  1062. return columns
  1063. @reflection.cache
  1064. def get_indexes(self, connection, table_name, schema=None,
  1065. resolve_synonyms=False, dblink='', **kw):
  1066. info_cache = kw.get('info_cache')
  1067. (table_name, schema, dblink, synonym) = \
  1068. self._prepare_reflection_args(connection, table_name, schema,
  1069. resolve_synonyms, dblink,
  1070. info_cache=info_cache)
  1071. indexes = []
  1072. params = {'table_name': table_name}
  1073. text = \
  1074. "SELECT a.index_name, a.column_name, "\
  1075. "\nb.index_type, b.uniqueness, b.compression, b.prefix_length "\
  1076. "\nFROM ALL_IND_COLUMNS%(dblink)s a, "\
  1077. "\nALL_INDEXES%(dblink)s b "\
  1078. "\nWHERE "\
  1079. "\na.index_name = b.index_name "\
  1080. "\nAND a.table_owner = b.table_owner "\
  1081. "\nAND a.table_name = b.table_name "\
  1082. "\nAND a.table_name = :table_name "
  1083. if schema is not None:
  1084. params['schema'] = schema
  1085. text += "AND a.table_owner = :schema "
  1086. text += "ORDER BY a.index_name, a.column_position"
  1087. text = text % {'dblink': dblink}
  1088. q = sql.text(text)
  1089. rp = connection.execute(q, **params)
  1090. indexes = []
  1091. last_index_name = None
  1092. pk_constraint = self.get_pk_constraint(
  1093. connection, table_name, schema, resolve_synonyms=resolve_synonyms,
  1094. dblink=dblink, info_cache=kw.get('info_cache'))
  1095. pkeys = pk_constraint['constrained_columns']
  1096. uniqueness = dict(NONUNIQUE=False, UNIQUE=True)
  1097. enabled = dict(DISABLED=False, ENABLED=True)
  1098. oracle_sys_col = re.compile(r'SYS_NC\d+\$', re.IGNORECASE)
  1099. def upper_name_set(names):
  1100. return set([i.upper() for i in names])
  1101. pk_names = upper_name_set(pkeys)
  1102. def remove_if_primary_key(index):
  1103. # don't include the primary key index
  1104. if index is not None and \
  1105. upper_name_set(index['column_names']) == pk_names:
  1106. indexes.pop()
  1107. index = None
  1108. for rset in rp:
  1109. if rset.index_name != last_index_name:
  1110. remove_if_primary_key(index)
  1111. index = dict(name=self.normalize_name(rset.index_name),
  1112. column_names=[], dialect_options={})
  1113. indexes.append(index)
  1114. index['unique'] = uniqueness.get(rset.uniqueness, False)
  1115. if rset.index_type in ('BITMAP', 'FUNCTION-BASED BITMAP'):
  1116. index['dialect_options']['oracle_bitmap'] = True
  1117. if enabled.get(rset.compression, False):
  1118. index['dialect_options']['oracle_compress'] = rset.prefix_length
  1119. # filter out Oracle SYS_NC names. could also do an outer join
  1120. # to the all_tab_columns table and check for real col names there.
  1121. if not oracle_sys_col.match(rset.column_name):
  1122. index['column_names'].append(
  1123. self.normalize_name(rset.column_name))
  1124. last_index_name = rset.index_name
  1125. remove_if_primary_key(index)
  1126. return indexes
  1127. @reflection.cache
  1128. def _get_constraint_data(self, connection, table_name, schema=None,
  1129. dblink='', **kw):
  1130. params = {'table_name': table_name}
  1131. text = \
  1132. "SELECT"\
  1133. "\nac.constraint_name,"\
  1134. "\nac.constraint_type,"\
  1135. "\nloc.column_name AS local_column,"\
  1136. "\nrem.table_name AS remote_table,"\
  1137. "\nrem.column_name AS remote_column,"\
  1138. "\nrem.owner AS remote_owner,"\
  1139. "\nloc.position as loc_pos,"\
  1140. "\nrem.position as rem_pos"\
  1141. "\nFROM all_constraints%(dblink)s ac,"\
  1142. "\nall_cons_columns%(dblink)s loc,"\
  1143. "\nall_cons_columns%(dblink)s rem"\
  1144. "\nWHERE ac.table_name = :table_name"\
  1145. "\nAND ac.constraint_type IN ('R','P')"
  1146. if schema is not None:
  1147. params['owner'] = schema
  1148. text += "\nAND ac.owner = :owner"
  1149. text += \
  1150. "\nAND ac.owner = loc.owner"\
  1151. "\nAND ac.constraint_name = loc.constraint_name"\
  1152. "\nAND ac.r_owner = rem.owner(+)"\
  1153. "\nAND ac.r_constraint_name = rem.constraint_name(+)"\
  1154. "\nAND (rem.position IS NULL or loc.position=rem.position)"\
  1155. "\nORDER BY ac.constraint_name, loc.position"
  1156. text = text % {'dblink': dblink}
  1157. rp = connection.execute(sql.text(text), **params)
  1158. constraint_data = rp.fetchall()
  1159. return constraint_data
  1160. @reflection.cache
  1161. def get_pk_constraint(self, connection, table_name, schema=None, **kw):
  1162. resolve_synonyms = kw.get('oracle_resolve_synonyms', False)
  1163. dblink = kw.get('dblink', '')
  1164. info_cache = kw.get('info_cache')
  1165. (table_name, schema, dblink, synonym) = \
  1166. self._prepare_reflection_args(connection, table_name, schema,
  1167. resolve_synonyms, dblink,
  1168. info_cache=info_cache)
  1169. pkeys = []
  1170. constraint_name = None
  1171. constraint_data = self._get_constraint_data(
  1172. connection, table_name, schema, dblink,
  1173. info_cache=kw.get('info_cache'))
  1174. for row in constraint_data:
  1175. (cons_name, cons_type, local_column, remote_table, remote_column, remote_owner) = \
  1176. row[0:2] + tuple([self.normalize_name(x) for x in row[2:6]])
  1177. if cons_type == 'P':
  1178. if constraint_name is None:
  1179. constraint_name = self.normalize_name(cons_name)
  1180. pkeys.append(local_column)
  1181. return {'constrained_columns': pkeys, 'name': constraint_name}
  1182. @reflection.cache
  1183. def get_foreign_keys(self, connection, table_name, schema=None, **kw):
  1184. """
  1185. kw arguments can be:
  1186. oracle_resolve_synonyms
  1187. dblink
  1188. """
  1189. requested_schema = schema # to check later on
  1190. resolve_synonyms = kw.get('oracle_resolve_synonyms', False)
  1191. dblink = kw.get('dblink', '')
  1192. info_cache = kw.get('info_cache')
  1193. (table_name, schema, dblink, synonym) = \
  1194. self._prepare_reflection_args(connection, table_name, schema,
  1195. resolve_synonyms, dblink,
  1196. info_cache=info_cache)
  1197. constraint_data = self._get_constraint_data(
  1198. connection, table_name, schema, dblink,
  1199. info_cache=kw.get('info_cache'))
  1200. def fkey_rec():
  1201. return {
  1202. 'name': None,
  1203. 'constrained_columns': [],
  1204. 'referred_schema': None,
  1205. 'referred_table': None,
  1206. 'referred_columns': []
  1207. }
  1208. fkeys = util.defaultdict(fkey_rec)
  1209. for row in constraint_data:
  1210. (cons_name, cons_type, local_column, remote_table, remote_column, remote_owner) = \
  1211. row[0:2] + tuple([self.normalize_name(x) for x in row[2:6]])
  1212. if cons_type == 'R':
  1213. if remote_table is None:
  1214. # ticket 363
  1215. util.warn(
  1216. ("Got 'None' querying 'table_name' from "
  1217. "all_cons_columns%(dblink)s - does the user have "
  1218. "proper rights to the table?") % {'dblink': dblink})
  1219. continue
  1220. rec = fkeys[cons_name]
  1221. rec['name'] = cons_name
  1222. local_cols, remote_cols = rec[
  1223. 'constrained_columns'], rec['referred_columns']
  1224. if not rec['referred_table']:
  1225. if resolve_synonyms:
  1226. ref_remote_name, ref_remote_owner, ref_dblink, ref_synonym = \
  1227. self._resolve_synonym(
  1228. connection,
  1229. desired_owner=self.denormalize_name(
  1230. remote_owner),
  1231. desired_table=self.denormalize_name(
  1232. remote_table)
  1233. )
  1234. if ref_synonym:
  1235. remote_table = self.normalize_name(ref_synonym)
  1236. remote_owner = self.normalize_name(
  1237. ref_remote_owner)
  1238. rec['referred_table'] = remote_table
  1239. if requested_schema is not None or \
  1240. self.denormalize_name(remote_owner) != schema:
  1241. rec['referred_schema'] = remote_owner
  1242. local_cols.append(local_column)
  1243. remote_cols.append(remote_column)
  1244. return list(fkeys.values())
  1245. @reflection.cache
  1246. def get_view_definition(self, connection, view_name, schema=None,
  1247. resolve_synonyms=False, dblink='', **kw):
  1248. info_cache = kw.get('info_cache')
  1249. (view_name, schema, dblink, synonym) = \
  1250. self._prepare_reflection_args(connection, view_name, schema,
  1251. resolve_synonyms, dblink,
  1252. info_cache=info_cache)
  1253. params = {'view_name': view_name}
  1254. text = "SELECT text FROM all_views WHERE view_name=:view_name"
  1255. if schema is not None:
  1256. text += " AND owner = :schema"
  1257. params['schema'] = schema
  1258. rp = connection.execute(sql.text(text), **params).scalar()
  1259. if rp:
  1260. if util.py2k:
  1261. rp = rp.decode(self.encoding)
  1262. return rp
  1263. else:
  1264. return None
  1265. class _OuterJoinColumn(sql.ClauseElement):
  1266. __visit_name__ = 'outer_join_column'
  1267. def __init__(self, column):
  1268. self.column = column