U a[@sdZddlmZddlZddlmZddlmZddlmZddlm Z dd lm Z dd l m Z dd l m Z dd l mZdd l mZddl mZdd l m Zddl mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl mZedZ edZ!Gdddej"Z#e#Z$Gdddej%Z&Gd d!d!eZ'eZ(Gd"d#d#ej)ej*Z+Gd$d%d%ej,Z-Gd&d'd'ej,Z.Gd(d)d)ej,Z/Gd*d+d+ej0Z1Gd,d-d-ej%Z2Gd.d/d/ej3Z4Gd0d1d1ej5ej6Z7Gd2d3d3ej8Z9Gd4d5d5ej:Z;ej:e;ejGd7d8d8ej?Z@Gd9d:d:ejAZBGd;d<dd>ejEZFGd?d@d@e jGZHGdAdBdBe jIZJGdCdDdDe jKZLdS)EaR .. dialect:: oracle :name: Oracle :full_support: 11.2, 18c :normal_support: 11+ :best_effort: 8+ Auto Increment Behavior ----------------------- SQLAlchemy Table objects which include integer primary keys are usually assumed to have "autoincrementing" behavior, meaning they can generate their own primary key values upon INSERT. For use within Oracle, two options are available, which are the use of IDENTITY columns (Oracle 12 and above only) or the association of a SEQUENCE with the column. Specifying GENERATED AS IDENTITY (Oracle 12 and above) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Starting from version 12 Oracle can make use of identity columns using the :class:`_sql.Identity` to specify the autoincrementing behavior:: t = Table('mytable', metadata, Column('id', Integer, Identity(start=3), primary_key=True), Column(...), ... ) The CREATE TABLE for the above :class:`_schema.Table` object would be: .. sourcecode:: sql CREATE TABLE mytable ( id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 3), ..., PRIMARY KEY (id) ) The :class:`_schema.Identity` object support many options to control the "autoincrementing" behavior of the column, like the starting value, the incrementing value, etc. In addition to the standard options, Oracle supports setting :paramref:`_schema.Identity.always` to ``None`` to use the default generated mode, rendering GENERATED AS IDENTITY in the DDL. It also supports setting :paramref:`_schema.Identity.on_null` to ``True`` to specify ON NULL in conjunction with a 'BY DEFAULT' identity column. Using a SEQUENCE (all Oracle versions) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Older version of Oracle had no "autoincrement" feature, SQLAlchemy relies upon sequences to produce these values. With the older Oracle versions, *a sequence must always be explicitly specified to enable autoincrement*. This is divergent with the majority of documentation examples which assume the usage of an autoincrement-capable database. To specify sequences, use the sqlalchemy.schema.Sequence object which is passed to a Column construct:: t = Table('mytable', metadata, Column('id', Integer, Sequence('id_seq'), primary_key=True), Column(...), ... ) This step is also required when using table reflection, i.e. autoload_with=engine:: t = Table('mytable', metadata, Column('id', Integer, Sequence('id_seq'), primary_key=True), autoload_with=engine ) .. versionchanged:: 1.4 Added :class:`_schema.Identity` construct in a :class:`_schema.Column` to specify the option of an autoincrementing column. .. _oracle_isolation_level: Transaction Isolation Level / Autocommit ---------------------------------------- The Oracle database supports "READ COMMITTED" and "SERIALIZABLE" modes of isolation. The AUTOCOMMIT isolation level is also supported by the cx_Oracle dialect. To set using per-connection execution options:: connection = engine.connect() connection = connection.execution_options( isolation_level="AUTOCOMMIT" ) For ``READ COMMITTED`` and ``SERIALIZABLE``, the Oracle dialect sets the level at the session level using ``ALTER SESSION``, which is reverted back to its default setting when the connection is returned to the connection pool. Valid values for ``isolation_level`` include: * ``READ COMMITTED`` * ``AUTOCOMMIT`` * ``SERIALIZABLE`` .. note:: The implementation for the :meth:`_engine.Connection.get_isolation_level` method as implemented by the Oracle dialect necessarily forces the start of a transaction using the Oracle LOCAL_TRANSACTION_ID function; otherwise no level is normally readable. Additionally, the :meth:`_engine.Connection.get_isolation_level` method will raise an exception if the ``v$transaction`` view is not available due to permissions or other reasons, which is a common occurrence in Oracle installations. The cx_Oracle dialect attempts to call the :meth:`_engine.Connection.get_isolation_level` method when the dialect makes its first connection to the database in order to acquire the "default"isolation level. This default level is necessary so that the level can be reset on a connection after it has been temporarily modified using :meth:`_engine.Connection.execution_options` method. In the common event that the :meth:`_engine.Connection.get_isolation_level` method raises an exception due to ``v$transaction`` not being readable as well as any other database-related failure, the level is assumed to be "READ COMMITTED". No warning is emitted for this initial first-connect condition as it is expected to be a common restriction on Oracle databases. .. versionadded:: 1.3.16 added support for AUTOCOMMIT to the cx_oracle dialect as well as the notion of a default isolation level .. versionadded:: 1.3.21 Added support for SERIALIZABLE as well as live reading of the isolation level. .. versionchanged:: 1.3.22 In the event that the default isolation level cannot be read due to permissions on the v$transaction view as is common in Oracle installations, the default isolation level is hardcoded to "READ COMMITTED" which was the behavior prior to 1.3.21. .. seealso:: :ref:`dbapi_autocommit` Identifier Casing ----------------- In Oracle, the data dictionary represents all case insensitive identifier names using UPPERCASE text. SQLAlchemy on the other hand considers an all-lower case identifier name to be case insensitive. The Oracle dialect converts all case insensitive identifiers to and from those two formats during schema level communication, such as reflection of tables and indexes. Using an UPPERCASE name on the SQLAlchemy side indicates a case sensitive identifier, and SQLAlchemy will quote the name - this will cause mismatches against data dictionary data received from Oracle, so unless identifier names have been truly created as case sensitive (i.e. using quoted names), all lowercase names should be used on the SQLAlchemy side. .. _oracle_max_identifier_lengths: Max Identifier Lengths ---------------------- Oracle has changed the default max identifier length as of Oracle Server version 12.2. Prior to this version, the length was 30, and for 12.2 and greater it is now 128. This change impacts SQLAlchemy in the area of generated SQL label names as well as the generation of constraint names, particularly in the case where the constraint naming convention feature described at :ref:`constraint_naming_conventions` is being used. To assist with this change and others, Oracle includes the concept of a "compatibility" version, which is a version number that is independent of the actual server version in order to assist with migration of Oracle databases, and may be configured within the Oracle server itself. This compatibility version is retrieved using the query ``SELECT value FROM v$parameter WHERE name = 'compatible';``. The SQLAlchemy Oracle dialect, when tasked with determining the default max identifier length, will attempt to use this query upon first connect in order to determine the effective compatibility version of the server, which determines what the maximum allowed identifier length is for the server. If the table is not available, the server version information is used instead. As of SQLAlchemy 1.4, the default max identifier length for the Oracle dialect is 128 characters. Upon first connect, the compatibility version is detected and if it is less than Oracle version 12.2, the max identifier length is changed to be 30 characters. In all cases, setting the :paramref:`_sa.create_engine.max_identifier_length` parameter will bypass this change and the value given will be used as is:: engine = create_engine( "oracle+cx_oracle://scott:tiger@oracle122", max_identifier_length=30) The maximum identifier length comes into play both when generating anonymized SQL labels in SELECT statements, but more crucially when generating constraint names from a naming convention. It is this area that has created the need for SQLAlchemy to change this default conservatively. For example, the following naming convention produces two very different constraint names based on the identifier length:: from sqlalchemy import Column from sqlalchemy import Index from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import Table from sqlalchemy.dialects import oracle from sqlalchemy.schema import CreateIndex m = MetaData(naming_convention={"ix": "ix_%(column_0N_name)s"}) t = Table( "t", m, Column("some_column_name_1", Integer), Column("some_column_name_2", Integer), Column("some_column_name_3", Integer), ) ix = Index( None, t.c.some_column_name_1, t.c.some_column_name_2, t.c.some_column_name_3, ) oracle_dialect = oracle.dialect(max_identifier_length=30) print(CreateIndex(ix).compile(dialect=oracle_dialect)) With an identifier length of 30, the above CREATE INDEX looks like:: CREATE INDEX ix_some_column_name_1s_70cd ON t (some_column_name_1, some_column_name_2, some_column_name_3) However with length=128, it becomes:: CREATE INDEX ix_some_column_name_1some_column_name_2some_column_name_3 ON t (some_column_name_1, some_column_name_2, some_column_name_3) Applications which have run versions of SQLAlchemy prior to 1.4 on an Oracle server version 12.2 or greater are therefore subject to the scenario of a database migration that wishes to "DROP CONSTRAINT" on a name that was previously generated with the shorter length. This migration will fail when the identifier length is changed without the name of the index or constraint first being adjusted. Such applications are strongly advised to make use of :paramref:`_sa.create_engine.max_identifier_length` in order to maintain control of the generation of truncated names, and to fully review and test all database migrations in a staging environment when changing this value to ensure that the impact of this change has been mitigated. .. versionchanged:: 1.4 the default max_identifier_length for Oracle is 128 characters, which is adjusted down to 30 upon first connect if an older version of Oracle server (compatibility version < 12.2) is detected. LIMIT/OFFSET Support -------------------- Oracle has no direct support for LIMIT and OFFSET until version 12c. To achieve this behavior across all widely used versions of Oracle starting with the 8 series, SQLAlchemy currently makes use of ROWNUM to achieve LIMIT/OFFSET; the exact methodology is taken from https://blogs.oracle.com/oraclemagazine/on-rownum-and-limiting-results . There is currently a single option to affect its behavior: * the "FIRST_ROWS()" optimization keyword is not used by default. To enable the usage of this optimization directive, specify ``optimize_limits=True`` to :func:`_sa.create_engine`. .. versionchanged:: 1.4 The Oracle dialect renders limit/offset integer values using a "post compile" scheme which renders the integer directly before passing the statement to the cursor for execution. The ``use_binds_for_limits`` flag no longer has an effect. .. seealso:: :ref:`change_4808`. Support for changing the row number strategy, which would include one that makes use of the ``row_number()`` window function as well as one that makes use of the Oracle 12c "FETCH FIRST N ROW / OFFSET N ROWS" keywords may be added in a future release. .. _oracle_returning: RETURNING Support ----------------- The Oracle database supports a limited form of RETURNING, in order to retrieve result sets of matched rows from INSERT, UPDATE and DELETE statements. Oracle's RETURNING..INTO syntax only supports one row being returned, as it relies upon OUT parameters in order to function. In addition, supported DBAPIs have further limitations (see :ref:`cx_oracle_returning`). SQLAlchemy's "implicit returning" feature, which employs RETURNING within an INSERT and sometimes an UPDATE statement in order to fetch newly generated primary key values and other SQL defaults and expressions, is normally enabled on the Oracle backend. By default, "implicit returning" typically only fetches the value of a single ``nextval(some_seq)`` expression embedded into an INSERT in order to increment a sequence within an INSERT statement and get the value back at the same time. To disable this feature across the board, specify ``implicit_returning=False`` to :func:`_sa.create_engine`:: engine = create_engine("oracle://scott:tiger@dsn", implicit_returning=False) Implicit returning can also be disabled on a table-by-table basis as a table option:: # Core Table my_table = Table("my_table", metadata, ..., implicit_returning=False) # declarative class MyClass(Base): __tablename__ = 'my_table' __table_args__ = {"implicit_returning": False} .. seealso:: :ref:`cx_oracle_returning` - additional cx_oracle-specific restrictions on implicit returning. ON UPDATE CASCADE ----------------- Oracle doesn't have native ON UPDATE CASCADE functionality. A trigger based solution is available at https://asktom.oracle.com/tkyte/update_cascade/index.html . When using the SQLAlchemy ORM, the ORM has limited ability to manually issue cascading updates - specify ForeignKey objects using the "deferrable=True, initially='deferred'" keyword arguments, and specify "passive_updates=False" on each relationship(). Oracle 8 Compatibility ---------------------- When Oracle 8 is detected, the dialect internally configures itself to the following behaviors: * the use_ansi flag is set to False. This has the effect of converting all JOIN phrases into the WHERE clause, and in the case of LEFT OUTER JOIN makes use of Oracle's (+) operator. * the NVARCHAR2 and NCLOB datatypes are no longer generated as DDL when the :class:`~sqlalchemy.types.Unicode` is used - VARCHAR2 and CLOB are issued instead. This because these types don't seem to work correctly on Oracle 8 even though they are available. The :class:`~sqlalchemy.types.NVARCHAR` and :class:`~sqlalchemy.dialects.oracle.NCLOB` types will always generate NVARCHAR2 and NCLOB. * the "native unicode" mode is disabled when using cx_oracle, i.e. SQLAlchemy encodes all Python unicode objects to "string" before passing in as bind parameters. Synonym/DBLINK Reflection ------------------------- When using reflection with Table objects, the dialect can optionally search for tables indicated by synonyms, either in local or remote schemas or accessed over DBLINK, by passing the flag ``oracle_resolve_synonyms=True`` as a keyword argument to the :class:`_schema.Table` construct:: some_table = Table('some_table', autoload_with=some_engine, oracle_resolve_synonyms=True) When this flag is set, the given name (such as ``some_table`` above) will be searched not just in the ``ALL_TABLES`` view, but also within the ``ALL_SYNONYMS`` view to see if this name is actually a synonym to another name. If the synonym is located and refers to a DBLINK, the oracle dialect knows how to locate the table's information using DBLINK syntax(e.g. ``@dblink``). ``oracle_resolve_synonyms`` is accepted wherever reflection arguments are accepted, including methods such as :meth:`_schema.MetaData.reflect` and :meth:`_reflection.Inspector.get_columns`. If synonyms are not in use, this flag should be left disabled. .. _oracle_constraint_reflection: Constraint Reflection --------------------- The Oracle dialect can return information about foreign key, unique, and CHECK constraints, as well as indexes on tables. Raw information regarding these constraints can be acquired using :meth:`_reflection.Inspector.get_foreign_keys`, :meth:`_reflection.Inspector.get_unique_constraints`, :meth:`_reflection.Inspector.get_check_constraints`, and :meth:`_reflection.Inspector.get_indexes`. .. versionchanged:: 1.2 The Oracle dialect can now reflect UNIQUE and CHECK constraints. When using reflection at the :class:`_schema.Table` level, the :class:`_schema.Table` will also include these constraints. Note the following caveats: * When using the :meth:`_reflection.Inspector.get_check_constraints` method, Oracle builds a special "IS NOT NULL" constraint for columns that specify "NOT NULL". This constraint is **not** returned by default; to include the "IS NOT NULL" constraints, pass the flag ``include_all=True``:: from sqlalchemy import create_engine, inspect engine = create_engine("oracle+cx_oracle://s:t@dsn") inspector = inspect(engine) all_check_constraints = inspector.get_check_constraints( "some_table", include_all=True) * in most cases, when reflecting a :class:`_schema.Table`, a UNIQUE constraint will **not** be available as a :class:`.UniqueConstraint` object, as Oracle mirrors unique constraints with a UNIQUE index in most cases (the exception seems to be when two or more unique constraints represent the same columns); the :class:`_schema.Table` will instead represent these using :class:`.Index` with the ``unique=True`` flag set. * Oracle creates an implicit index for the primary key of a table; this index is **excluded** from all index results. * the list of columns reflected for an index will not include column names that start with SYS_NC. Table names with SYSTEM/SYSAUX tablespaces ------------------------------------------- The :meth:`_reflection.Inspector.get_table_names` and :meth:`_reflection.Inspector.get_temp_table_names` methods each return a list of table names for the current engine. These methods are also part of the reflection which occurs within an operation such as :meth:`_schema.MetaData.reflect`. By default, these operations exclude the ``SYSTEM`` and ``SYSAUX`` tablespaces from the operation. In order to change this, the default list of tablespaces excluded can be changed at the engine level using the ``exclude_tablespaces`` parameter:: # exclude SYSAUX and SOME_TABLESPACE, but not SYSTEM e = create_engine( "oracle://scott:tiger@xe", exclude_tablespaces=["SYSAUX", "SOME_TABLESPACE"]) .. versionadded:: 1.1 DateTime Compatibility ---------------------- Oracle has no datatype known as ``DATETIME``, it instead has only ``DATE``, which can actually store a date and time value. For this reason, the Oracle dialect provides a type :class:`_oracle.DATE` which is a subclass of :class:`.DateTime`. This type has no special behavior, and is only present as a "marker" for this type; additionally, when a database column is reflected and the type is reported as ``DATE``, the time-supporting :class:`_oracle.DATE` type is used. .. versionchanged:: 0.9.4 Added :class:`_oracle.DATE` to subclass :class:`.DateTime`. This is a change as previous versions would reflect a ``DATE`` column as :class:`_types.DATE`, which subclasses :class:`.Date`. The only significance here is for schemes that are examining the type of column for use in special Python translations or for migrating schemas to other database backends. .. _oracle_table_options: Oracle Table Options ------------------------- The CREATE TABLE phrase supports the following options with Oracle in conjunction with the :class:`_schema.Table` construct: * ``ON COMMIT``:: Table( "some_table", metadata, ..., prefixes=['GLOBAL TEMPORARY'], oracle_on_commit='PRESERVE ROWS') .. versionadded:: 1.0.0 * ``COMPRESS``:: Table('mytable', metadata, Column('data', String(32)), oracle_compress=True) Table('mytable', metadata, Column('data', String(32)), oracle_compress=6) The ``oracle_compress`` parameter accepts either an integer compression level, or ``True`` to use the default compression level. .. versionadded:: 1.0.0 .. _oracle_index_options: Oracle Specific Index Options ----------------------------- Bitmap Indexes ~~~~~~~~~~~~~~ You can specify the ``oracle_bitmap`` parameter to create a bitmap index instead of a B-tree index:: Index('my_index', my_table.c.data, oracle_bitmap=True) Bitmap indexes cannot be unique and cannot be compressed. SQLAlchemy will not check for such limitations, only the database will. .. versionadded:: 1.0.0 Index compression ~~~~~~~~~~~~~~~~~ Oracle has a more efficient storage mode for indexes containing lots of repeated values. Use the ``oracle_compress`` parameter to turn on key compression:: Index('my_index', my_table.c.data, oracle_compress=True) Index('my_index', my_table.c.data1, my_table.c.data2, unique=True, oracle_compress=1) The ``oracle_compress`` parameter accepts either an integer specifying the number of prefix columns to compress, or ``True`` to use the default (all columns for non-unique indexes, all but the last column for unique indexes). .. versionadded:: 1.0.0 )groupbyN)Computed)excschema)sql)util)default) reflection)compiler) expression)sqltypes)visitors)BLOB)CHAR)CLOB)FLOAT)INTEGER)NCHAR)NVARCHAR) TIMESTAMP)VARCHAR)compata SHARE RAW DROP BETWEEN FROM DESC OPTION PRIOR LONG THEN DEFAULT ALTER IS INTO MINUS INTEGER NUMBER GRANT IDENTIFIED ALL TO ORDER ON FLOAT DATE HAVING CLUSTER NOWAIT RESOURCE ANY TABLE INDEX FOR UPDATE WHERE CHECK SMALLINT WITH DELETE BY ASC REVOKE LIKE SIZE RENAME NOCOMPRESS NULL GROUP VALUES AS IN VIEW EXCLUSIVE COMPRESS SYNONYM SELECT INSERT EXISTS NOT TRIGGER ELSE CREATE INTERSECT PCTFREE DISTINCT USER CONNECT SET MODE OF UNIQUE VARCHAR2 VARCHAR LOCK OR CHAR DECIMAL UNION PUBLIC AND START UID COMMENT CURRENT LEVELzddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Z d.d/Z!d0d1Z"d2d3Z#d4d5Z$d6d7Z%d8d9Z&d:d;Z'dsz6OracleCompiler.get_select_hint_text..)joinitems)r+Zbyfromsr r r!get_select_hint_textsz#OracleCompiler.get_select_hint_textcKs6t|jdks|jtkr.tjj||f|SdSdS)Nrrb)lenclausesroupper NO_ARG_FNSr SQLCompilerrrr r r!rszOracleCompiler.function_argspecc s,tt|j|f|}|ddr(d|}|S)NasfromFz TABLE (%s))r)rvisit_functionget)r+funcrYrr,r r!rs zOracleCompiler.visit_functionc s tt|j|f|}d|}|S)Nz COLUMN_VALUE )r)rvisit_table_valued_column)r+elementrYrr,r r!rs z(OracleCompiler.visit_table_valued_columncCsdS)zCalled when a ``SELECT`` statement has no froms, and no ``FROM`` clause is to be appended. The Oracle compiler tacks a "FROM DUAL" to the statement. z FROM DUALr r3r r r! default_fromszOracleCompiler.default_fromNcKs|jjr"tjj||fd|i|S|r:|j|j|jfd|d<t |jt j rZ|jj }n|j}|j |jfd|i|d|j |fd|i|SdS)N from_linterTr, )r]use_ansir r visit_joinedgesaddrr isinstancer FromGroupingrr)r+rrrrr r r!rs* zOracleCompiler.visit_joincsFgfdd|D]}t|tjr|qs8dStjSdS)Ncs|jr.fdd}tjid|in jjjfD]0}t|tj r`|qFt|tj rF|j qFdS)NcsZt|jtjr,j|jjr,t|j|_n*t|jtjrVj|jjrVt|j|_dSr=)rrr Z ColumnClauserZis_derived_fromr_OuterJoinColumn)rrr r! visit_binaryszVOracleCompiler._get_nonansi_join_whereclause..visit_join..visit_binaryr) ZisouterappendrZcloned_traverseZonclauserrrr Joinrr)rrjrrrr!rs     z@OracleCompiler._get_nonansi_join_whereclause..visit_join)rr rrand_)r+fromsfr rr!_get_nonansi_join_whereclauses  z,OracleCompiler._get_nonansi_join_whereclausecKs|j|jf|dS)Nz(+))rcolumn)r+ZvcrYr r r!visit_outer_join_columnsz&OracleCompiler.visit_outer_join_columncKs|j|dS)Nz.nextval)preparerformat_sequence)r+seqrYr r r!visit_sequenceszOracleCompiler.visit_sequencecCsd|S)z+Oracle doesn't like ``FROM table AS alias``rr )r+Zalias_name_textr r r!get_render_as_alias_suffixsz)OracleCompiler.get_render_as_alias_suffixc Csg}g}tt|D]\}}|jrNt|tjrNt|jtrN|j j sNt d|j jrd|j |}n|}tjd||j d}||j|j<||||d|_||j|dd|t|d|jt|d|j|t|ddt|ddf|j qdd |d d |S) NakComputed columns don't work with Oracle UPDATE statements that use RETURNING; the value of the column *before* the UPDATE takes place is returned. It is advised to not use RETURNING with an Oracle computed column. Consider setting implicit_returning to False on the Table object in order to avoid implicit RETURNING clauses from being generated for this Table.zret_%d)rXF)Zwithin_columns_clauserokeyz RETURNING rz INTO ) enumerater Z_select_iterablesZisupdater sa_schemaZColumnZserver_defaultrr](_supports_update_returning_computed_colsr warntypeZ_has_column_expressionZcolumn_expressionroutparambindsrrZbindparam_stringZ_truncate_bindparamZhas_out_parametersrZ_add_to_result_maprpZ_anon_name_labelr) r+ZstmtZreturning_colscolumnsrirZcol_exprrr r r!returning_clausesH          zOracleCompiler.returning_clausec s|}t|dds|jjsP|||dd}||}|dk rP||}d|_|jr|j dkr|j }|j }| |r| }| |r| }||}d|_|j}|dk r|jr|}||jD]} |j| s|| }q|} tjfdd| jD} |dk rL|jjrL| |rL| td|j|f|} d| _d| _|dk r|jrt !| fdd|jD|_|dk r| |r|dks| |r|} |dk r| |} n|} |dk r| |} | t"d | k} |dkr|| _| }n| t"d #d } d| _d| _|dk rp|jrp| j} |jD] } | $| dkrN| | } qN| }jtjfd d|jD}d|_d|_|dk r|jrt !|fd d|jD|_|t"d |k}||_|}|S) N _oracle_visitrFTcs g|]}j|dk r|qSr=)selected_columnscorresponding_columnrc) orig_selectr r! es  z=OracleCompiler.translate_select_structure..z/*+ FIRST_ROWS(%s) */csg|]}|qSr Ztraverserelemadapterr r!rsZROWNUMZora_rncsg|]}|dk r|qSr=)rr)origselect_colsr r!rs csg|]}|qSr rrrr r!rs)%rpr]rZ_display_froms_for_selectrrwhererZ_has_row_limiting_clauseZ _fetch_clauseZ _limit_clauseZ_offset_clauseZ_simple_int_clauseZrender_literal_executeZ _generate_for_update_argofZ_cloneZ_copy_internalsrZcontains_columnZ add_columnsaliasrselectroptimize_limitsZ prefix_withr rr _is_wrappersql_utilZ ClauseAdapterliteral_columnlabelr)r+Z select_stmtrrrZ whereclause limit_clauseZ offset_clauseZ for_updaterZinner_subqueryZ limitselectZmax_rowZlimitselect_colsZlimit_subqueryZ offsetselectr )rrrr!translate_select_structure5s                          z)OracleCompiler.translate_select_structurecKsdSrwr )r+rrYr r r!rszOracleCompiler.limit_clausecCsdS)NzSELECT 1 FROM DUAL WHERE 1!=1r )r+rXr r r!visit_empty_set_exprsz#OracleCompiler.visit_empty_set_exprc sbr dSd}|jjr>|ddfdd|jjD7}|jjrN|d7}|jjr^|d7}|S) Nrbz FOR UPDATEz OF rc3s|]}j|fVqdSr=)rrrYr+r r!rsz3OracleCompiler.for_update_clause..z NOWAITz SKIP LOCKED)Z is_subqueryrrrZnowaitZ skip_locked)r+rrYtmpr rr!for_update_clauses z OracleCompiler.for_update_clausecKsd||j||jfS)NzDECODE(%s, %s, 0, 1) = 1rrr r r!visit_is_distinct_from_binarys  z,OracleCompiler.visit_is_distinct_from_binarycKsd||j||jfS)NzDECODE(%s, %s, 0, 1) = 0rrr r r!!visit_is_not_distinct_from_binarys  z0OracleCompiler.visit_is_not_distinct_from_binarycCsJ|j|jf|}|j|jf|}|jd}|dk r@|j|f|}|||fS)Nflags)rrr modifiers)r+rrYstringpatternrr r r!_get_regexp_argss  zOracleCompiler._get_regexp_argscKs8|||\}}}|dkr&d||fSd|||fSdS)NzREGEXP_LIKE(%s, %s)zREGEXP_LIKE(%s, %s, %s))r)r+rrrYrrrr r r!visit_regexp_match_op_binarys z+OracleCompiler.visit_regexp_match_op_binarycKsd|j||f|S)NzNOT %s)rrr r r! visit_not_regexp_match_op_binarys z/OracleCompiler.visit_not_regexp_match_op_binarycKsP|||\}}}|j|jdf|}|dkr|d7}|dj|dd|j|jdd d fd d |j Df7}|jdd dk r|jdd dkr|d7}n|d|jdd 7}|S)NzCREATE zUNIQUE oraclebitmapzBITMAP zINDEX %s ON %s (%s)T)Zinclude_schema)Z use_schemarc3s |]}jj|dddVqdS)FTZ include_tableZ literal_bindsN) sql_compilerr)rrr3r r!r7s z7OracleDDLCompiler.visit_create_index..compressFz COMPRESSz COMPRESS %d) rZ_verify_index_tableruniquedialect_optionsZ_prepared_index_namerrrZ expressions)r+createindexrrr r3r!visit_create_index+s,     z$OracleDDLCompiler.visit_create_indexcCstg}|jd}|dr8|ddd}|d||drj|ddkrX|dn|d |dd |S) Nr on_commit_rz ON COMMIT %sr Tz COMPRESSz COMPRESS FOR %srb)r replacerrr)r+rZ table_optsoptsZon_commit_optionsr r r!post_create_tableGs   z#OracleDDLCompiler.post_create_tablecsDtt||}|dd}|dd}|dd}|dd}|S) Nz NO MINVALUEZ NOMINVALUEz NO MAXVALUEZ NOMAXVALUEzNO CYCLEZNOCYCLEzNO ORDERZNOORDER)r)rget_identity_optionsr)r+identity_optionsrr,r r!rWs     z&OracleDDLCompiler.get_identity_optionscCsDd|jj|jddd}|jdkr.tdn|jdkr@|d7}|S)NzGENERATED ALWAYS AS (%s)FTr zzOracle computed columns do not support 'stored' persistence; set the 'persisted' flag to None or False for Oracle support.z VIRTUAL)r rsqltextZ persistedr CompileError)r+ generatedrr r r!visit_computed_columnas  z'OracleDDLCompiler.visit_computed_columncKsZ|jdkrd}n|jrdnd}d|}|jr4|d7}|d7}||}|rV|d|7}|S)NrbALWAYSz BY DEFAULTz GENERATED %sz ON NULLz AS IDENTITYz (%s))alwayson_nullr)r+identityrYkindroptionsr r r!visit_identity_columnns   z'OracleDDLCompiler.visit_identity_column) rrrrrrrrrr"r6r r r,r!rs  rcsPeZdZddeDZddeddDddgZdd Zfd d Z Z S) OracleIdentifierPreparercCsh|] }|qSr )lowerrxr r r! sz"OracleIdentifierPreparer.cCsh|] }t|qSr )str)rdigr r r!r'sr r$cCs4|}||jkp2|d|jkp2|jt| S)z5Return True if the given identifier requires quoting.r)r$reserved_wordsillegal_initial_charactersZlegal_charactersmatchr text_type)r+rMZlc_valuer r r!_bindparam_requires_quotess   z3OracleIdentifierPreparer._bindparam_requires_quotescs|jd}tt|||S)Nr)identlstripr)r#format_savepoint)r+Z savepointror,r r!r3s   z)OracleIdentifierPreparer.format_savepoint) rrrRESERVED_WORDSr,rangeunionr-r0r3r6r r r,r!r#}s  r#c@seZdZddZdS)OracleExecutionContextcCs|d|j|d|S)NzSELECT z.nextval FROM DUAL)Z_execute_scalarZidentifier_preparerr)r+rrXr r r! fire_sequences z$OracleExecutionContext.fire_sequenceN)rrrr8r r r r!r7sr7csjeZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZeZeZdZdZdZdZdZdZeZeZeZeZeZ dZ!dZ"e#j$ddddfe#j%ddd fgZ&e'j(d d dVd dZ)fddZ*ddZ+e,ddZ-e,ddZ.e,ddZ/e,ddZ0e,ddZ1ddZ2dd Z3fd!d"Z4d#d$gZ5d%d&Z6d'd(Z7d)d*Z8dWd+d,Z9dXd-d.Z:d/d0Z;dYd1d2ZdZd4d5Z?e=j>d6d7Z@e=j>d[d8d9ZAe=j>d:d;ZBe=j>d\dd]d>d?ZDe=j>d^d@dAZEe=j>d_dBdCZFdDdEZGe=j>d`dFdGZHe=j>dadHdIZIe=j>dbdJdKZJe=j>dcdLdMZKe=j>dddNdOZLe=j>dedPdQZMe=j>dfdRdSZNe=j>dgdTdUZOZPS)h OracleDialectrTFnamed)oracle_resolve_synonymsN)resolve_synonymsrr )rr )z1.4aThe ``use_binds_for_limits`` Oracle dialect parameter is deprecated. The dialect now renders LIMIT /OFFSET integers inline in all cases using a post-compilation hook, so that the value is still represented by a 'bound parameter' on the Core Expression side.)use_binds_for_limitsZSYSTEMZSYSAUXcKs,tjj|f|||_||_||_||_dSr=)r DefaultDialectr*r^rrexclude_tablespaces)r+rrr>Zuse_nchar_for_unicoderArr r r!r*s zOracleDialect.__init__cs\tt|||jd|jdk|_|jrL|j |_|j t j d|_ |jdk|_dS)Nimplicit_returning)r*F )r)r9 initialize__dict__rserver_version_inforB _is_oracle_8colspecscopypoprrJrsupports_identity_columnsr+ connectionr,r r!rEs zOracleDialect.initializecCs||jdkr|jSz|d}Wntjk r<d}YnX|rrztdd|dDWS|jYSXn|jSdS)NrDz7SELECT value FROM v$parameter WHERE name = 'compatible'css|]}t|VqdSr=)intr%r r r!rszJOracleDialect._get_effective_compat_server_version_info...)rGexec_driver_sqlscalarrZ DBAPIErrortuplesplit)r+rNrr r r!)_get_effective_compat_server_version_infos   z7OracleDialect._get_effective_compat_server_version_infocCs|jo|jdkS)N) rGr3r r r!rHszOracleDialect._is_oracle_8cCs|jo|jdkS)N)r*rYr3r r r!_supports_table_compression sz)OracleDialect._supports_table_compressioncCs|jo|jdkS)N) rYr3r r r!_supports_table_compress_forsz*OracleDialect._supports_table_compress_forcCs|j Sr=)rHr3r r r!r{sz#OracleDialect._supports_char_lengthcCs|jo|jdkS)N)rYr3r r r!rsz6OracleDialect._supports_update_returning_computed_colscCsdSr=r )r+rNror r r!do_release_savepointsz"OracleDialect.do_release_savepointcCs||dkrdSdSdS)NrO)rWrMr r r!_check_max_identifier_length!sz*OracleDialect._check_max_identifier_lengthcs,ttdtdg}tt|||S)Nz'test nvarchar2 returns'<)r castrrrr)r9_check_unicode_returns)r+rNZadditional_testsr,r r!rd+s z$OracleDialect._check_unicode_returnsREAD COMMITTEDZ SERIALIZABLEcCs tddSNz implemented by cx_Oracle dialectNotImplementedErrorrMr r r!get_isolation_level8sz!OracleDialect.get_isolation_levelcCs4z ||WStk r"YnYdSXdS)Nre)rirh)r+Z dbapi_connr r r!get_default_isolation_level;s  z)OracleDialect.get_default_isolation_levelcCs tddSrfrg)r+rNlevelr r r!set_isolation_levelCsz!OracleDialect.set_isolation_levelcCsF|||s|j}|tdt||||d}|dk S)NzSSELECT table_name FROM all_tables WHERE table_name = :name AND owner = :schema_namero schema_name)Z_ensure_has_table_connectiondefault_schema_nameexecuterrdictdenormalize_namefirst)r+rN table_namercursorr r r! has_tableFs  zOracleDialect.has_tablecCs<|s |j}|tdt||||d}|dk S)NzeSELECT sequence_name FROM all_sequences WHERE sequence_name = :name AND sequence_owner = :schema_namerm)rorprrrqrrrs)r+rNZ sequence_namerrur r r! has_sequenceWs zOracleDialect.has_sequencecCs||dS)Nz;select sys_context( 'userenv', 'current_schema' ) from dual)normalize_namerSrTrMr r r!_get_default_schema_namegs z&OracleDialect._get_default_schema_namec Csd}g}i}|r"|d||d<|r8|d||d<|rN|d||d<|d|7}|jd d t||}|r|} | r| d | d | d | dfSdSnX|} t | dkrt dn6t | dkr| d} | d | d | d | dfSdSdS)zsearch for a local synonym matching the given desired owner/name. if desired_owner is None, attempts to locate a distinct owner. returns the actual name, owner, dblink name, and synonym name if found. zUSELECT owner, table_owner, table_name, db_link, synonym_name FROM all_synonyms WHERE zsynonym_name = :synonym_nameZ synonym_namezowner = :desired_owner desired_ownerztable_name = :tnameZtnamez AND T)Z future_resultrtZ table_ownerZdb_linkNNNNrZzGThere are multiple tables visible to the schema, you must specify ownerrN) rrZexecution_optionsrprrZmappingsrsallrAssertionError) r+rNrzdesired_synonym desired_tableqrparamsresultrowrowsr r r!_resolve_synonymnsP       zOracleDialect._resolve_synonymrbc Ks|r*|j|||||d\}}}} n d\}}}} |sD||}|rj|tdt|d}d|}n|s~||pz|j}|||pd| fS)N)rzr~r{z6SELECT username FROM user_db_links WHERE db_link=:link)link@rb)rrrrTrrrqro) r+rNrtrr=dblinkrYZ actual_nameownersynonymr r r!_prepare_reflection_argss(    z&OracleDialect._prepare_reflection_argsc s d}||}fdd|DS)Nz0SELECT username FROM all_users ORDER BY usernamecsg|]}|dqSrrxrrr3r r!rsz2OracleDialect.get_schema_names..)rS)r+rNrYsrur r3r!get_schema_namess zOracleDialect.get_schema_namesc sx|p j}|dkrj}d}jrF|ddddjD7}|d7}|t|t|d}fdd|DS) N(SELECT table_name FROM all_tables WHERE 6nvl(tablespace_name, 'no tablespace') NOT IN (%s) AND rcSsg|] }d|qSz'%s'r rtsr r r!rsz1OracleDialect.get_table_names..z8OWNER = :owner AND IOT_NAME IS NULL AND DURATION IS NULLrcsg|]}|dqSrrrr3r r!rsrrrorArrprrrq)r+rNrrYsql_strrur r3r!get_table_namesszOracleDialect.get_table_namesc sfj}d}jr4|ddddjD7}|d7}|t|t|d}fdd|DS) NrrrcSsg|] }d|qSrr rr r r!rsz6OracleDialect.get_temp_table_names..z.)rrrorrrprq)r+rNrrYrrur r3r!get_view_namess zOracleDialect.get_view_namesc s:|s j}|tdt|d}fdd|DS)NzKSELECT sequence_name FROM all_sequences WHERE sequence_owner = :schema_name)rncsg|]}|dqSrrrr3r r!rsz4OracleDialect.get_sequence_names..)rorprrrqrr)r+rNrrYrur r3r!get_sequence_namessz OracleDialect.get_sequence_namescKsi}|dd}|dd}|d}|j||||||d\}}}} d|i} dg} |jrb| d|jrr| d d } |dk r|| d <| d 7} | |d | d} |t| | } t ddd}| }|r d|j kr ||j dr d |j kr|j |d<nd|d<|S)Nr<Frrb info_cacherrt compression compress_forzKSELECT %(columns)s FROM ALL_TABLES%(dblink)s WHERE table_name = :table_namerz AND owner = :owner r)rrTZDISABLEDZENABLEDoracle_compress)rrr[rr]rrprrrqrs_fieldsrr)r+rNrtrrYr!r=rrrrrrrenabledrr r r!get_table_optionssH         zOracleDialect.get_table_optionsc Ks|dd}|dd}|d}|j||||||d\}}}}g} |jrPd} nd} |jd krld d|i} nd } d |i} d } |dk r|| d<| d7} | d7} | || | d} |t| | }|D]}||d}|d}|d}|d}|d}|d}|ddk}|d}|d}|d}|d}|d}|dkrd|dkrX|dkrXt}n t ||}n|d krvt }n~|d!kr|j ||}nbd"|krt d#d$}nLt d%d|}z|j |}Wn.tk rtd&||ftj}YnX|d'krt|d(}d}nd}|dk r.|||}d}nd}||||d)|d*}||krZd#|d+<|dk rl||d,<|dk r~||d-<| |q| S).a kw arguments can be: oracle_resolve_synonyms dblink r<FrrbrrZ char_lengthZ data_lengthrCa col.default_on_null, ( SELECT id.generation_type || ',' || id.IDENTITY_OPTIONS FROM ALL_TAB_IDENTITY_COLS%(dblink)s id WHERE col.table_name = id.table_name AND col.column_name = id.column_name AND col.owner = id.owner ) AS identity_optionsz1NULL as default_on_null, NULL as identity_optionsrta SELECT col.column_name, col.data_type, col.%(char_length_col)s, col.data_precision, col.data_scale, col.nullable, col.data_default, com.comments, col.virtual_column, %(identity_cols)s FROM all_tab_cols%(dblink)s col LEFT JOIN all_col_comments%(dblink)s com ON col.table_name = com.table_name AND col.column_name = com.column_name AND col.owner = com.owner WHERE col.table_name = :table_name AND col.hidden_column = 'NO' Nrz AND col.owner = :owner z ORDER BY col.column_id)rchar_length_col identity_colsrrZrPrYrXr*r$r)r#rSrrzWITH TIME ZONETrez\(\d+\)z*Did not recognize type '%s' of column '%s'YES)rauto)rornullabler Z autoincrementcommentquotecomputedr)rrr{rGrprrrxrr$r ischema_namesrresubKeyErrorr rrZNULLTYPErq_parse_identity_optionsr$r)r+rNrtrrYr=rrrrrrrrrrZcolnameZ orig_colnameZcoltyperzr%r&rr rrdefault_on_nulrrrZcdictr r r! get_columnsQs                     zOracleDialect.get_columnscCsdd|dD}|ddk|dkd}|ddD]}|d \}}|}d |krht||d <q6d |krt||d <q6d|krt||d<q6d|krt||d<q6d|kr|dk|d<q6d|krt||d<q6d|kr6|dk|d<q6|S)NcSsg|] }|qSr )strip)rpr r r!rsz9OracleDialect._parse_identity_options..,rrr)rrrZ:z START WITHstartz INCREMENT BY incrementZ MAX_VALUEZmaxvalueZ MIN_VALUEZminvalueZ CYCLE_FLAGrcycleZ CACHE_SIZEcacheZ ORDER_FLAGorder)rVrrZ long_type)r+rrpartsrpartoptionrMr r r!rs, z%OracleDialect._parse_identity_optionsc Ks\|d}|j||||||d\}}}}|s2|j}d} |t| t||d} d| iS)Nrrz SELECT comments FROM all_tab_comments WHERE table_name = :table_name AND owner = :schema_name )rtrnr)rrrorprrrqrT) r+rNrtrr=rrYrrZ COMMENT_SQLrr r r!get_table_comments"   zOracleDialect.get_table_commentc Ks|d}|j||||||d\}}}}g} d|i} d} |dk rP|| d<| d7} | d7} | d|i} t| } || | } g} d}|j||||||dd }td d d }td d d }tdtj }d}| D]}| |j }|r||dkrq|j |krt|gid}| |||j d |d<|jdkr.rP)constrained_columnsro)rrrrUrxr)r+rNrtrrYr=rrrZpkeysZconstraint_namerr cons_name cons_type local_column remote_table remote_column remote_ownerr r3r!rsD   (  zOracleDialect.get_pk_constraintc s|}|dd}|dd}|d}j||||||d\}}}} j|||||dd} dd} t| } | D]4} | d d tfd d | d d D\}}}}}}|}|dkrt|dkrtdd|iqt| |}||d<|d|d}}|ds|rNj| | |d\}}}}|rN|}|}||d<|dk sp ||krx||d<| ddkr| d|dd<| || |qtt | S)rr<FrrbrrcSsdgddgidS)N)rorreferred_schemareferred_tablereferred_columnsr!r r r r r!fkey_rec sz0OracleDialect.get_foreign_keys..fkey_recrrPcsg|]}|qSr rr%r3r r!r sz2OracleDialect.get_foreign_keys..rRNzqGot 'None' querying 'table_name' from all_cons_columns%(dblink)s - does the user have proper rights to the table?rorrr)rzrrrXz NO ACTIONr!r) rrrr defaultdictrUrxrrrrrlistvalues)r+rNrtrrYZrequested_schemar=rrrrrZfkeysrrrrrrrZrecZ local_colsZ remote_colsZref_remote_nameZref_remote_ownerZ ref_dblinkZ ref_synonymr r3r!get_foreign_keyss       (      zOracleDialect.get_foreign_keysc  s|dd}|dd}|d}j||||||d\}}}}j|||||dd} tdd| } t| d d} d d j|||d Dfd dfdd| DDS)Nr<FrrbrrcSs |ddkS)NrZUr r&r r r!i z6OracleDialect.get_unique_constraints..cSs|dSr0r rr r r!rj rcSsh|] }|dqS)ror )rixr r r!r'l sz7OracleDialect.get_unique_constraints..rcs(g|] \}}|||kr|nddqS)N)rorZduplicates_indexr )rrocols) index_namesr r!rp s z8OracleDialect.get_unique_constraints..cs0g|](}|dfdd|dDgqS)rcsg|]}|dqS)rPrr%r3r r!ry szCOracleDialect.get_unique_constraints...rZr)rrr3r r!rv s )rrrfilterrr) r+rNrtrrYr=rrrrZ unique_keysZ uniques_groupr )rr+r!get_unique_constraintsP s8      z$OracleDialect.get_unique_constraintsc Ks|d}|j||||||d\}}}}d|i} d} |dk rL| d7} || d<|t| | } | r|tjrx| |j } | SdSdS)Nrr view_namez5SELECT text FROM all_views WHERE view_name=:view_namez AND owner = :schemar) rrrprrrTr Zpy2kdecodeencoding) r+rNrrr=rrYrrrrrr r r!get_view_definition s(   z!OracleDialect.get_view_definitionc  s||dd}|dd}|d}j||||||d\}}}} j|||||dd} tdd| } fd d | DS) Nr<FrrbrrcSs |ddkS)NrZCr rr r r!r rz5OracleDialect.get_check_constraints..cs8g|]0}std|ds|d|ddqS)z..+?. IS NOT NULL$rr)ror)rr.rx)rZcons include_allr+r r!r sz7OracleDialect.get_check_constraints..)rrrr) r+rNrtrrrYr=rrrrZcheck_constraintsr rr!get_check_constraints s,     z#OracleDialect.get_check_constraints)TFNFr?)N)N)NNN)NFrb)N)N)N)N)N)NFrb)NFrb)Nrb)N)N)N)NFrb)NF)QrrrroZsupports_statement_cacheZsupports_alterZsupports_unicode_statementsZsupports_unicode_bindsZmax_identifier_lengthZsupports_simple_order_by_labelZcte_follows_insertZsupports_sequencesZsequences_optionalZpostfetch_lastrowidZdefault_paramstylerIrZrequires_name_normalizeZsupports_commentsZsupports_default_valuesZsupports_default_metavalueZsupports_empty_insertrLrZstatement_compilerrZ ddl_compilerrVZ type_compilerr#rr7Zexecution_ctx_clsZreflection_optionsr^rZTableZIndexZconstruct_argumentsr Zdeprecated_paramsr*rErWr5rHr[r]r{rr_rardZ_isolation_lookuprirjrlrvrwryrr rrrrrrrrrrrrrrrrrrr6r r r,r!r9s              A '      3   # e + & n . "r9c@seZdZdZddZdS)rZouter_join_columncCs ||_dSr=)r)r+rr r r!r* sz_OuterJoinColumn.__init__N)rrrrr*r r r r!r sr)MrB itertoolsrrrbrrrrrr Zenginer r r r rrrtypesrrrrrrrrrrsetrVr4rZ_BinaryrZ OracleRawTextr"r#rSr1r2r$ZFloatr7r8r9Z LargeBinaryr:r;r>r<ZNativeForEmulatedZ_AbstractIntervalrCZ TypeEnginerPBooleanrQrJrIrZGenericTypeCompilerrVrrZ DDLCompilerrZIdentifierPreparerr#ZDefaultExecutionContextr7r@r9Z ClauseElementrr r r r!s                        * }(j .