o
    [hc                    @   s
  d Z ddlZddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddlm
Z dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z! ddlm"Z" ddlm#Z# ddlm$Z$ dd lm%Z% dd!l&m'Z' d"Z(d#Z)d$Z*d%Z+d&Z,d'Z-e.g d(Z/G d)d* d*ej0Z0G d+d, d,ej1Z2G d-d. d.ej3Z4G d/d0 d0ej5Z5e5Z6G d1d2 d2e7Z8G d3d4 d4e8ej9Z:G d5d6 d6e8ej9Z;G d7d8 d8e8ej9Z<G d9d: d:ej=Z>G d;d< d<e7Z?G d=d> d>e?ej@ZAG d?d@ d@e?ejBZCG dAdB dBejDZEG dCdD dDeEZFG dEdF dFejBZGG dGdH dHejHejIZHG dIdJ dJejIZJG dKdL dLejKZLG dMdN dNej=ZMG dOdP dPej=ZNG dQdR dRej=ZOG dSdT dTej=ZPG dUdV dVej=ZQG dWdX dXejRjSZTe'eTdYZUe:ZVe4ZWe0ZXe2ZYe5ZZe;Z[e<Z\e>Z]e#Z^eGZ_e$Z`e!ZaeZbeZceZdeHZeeJZfeMZgeNZheOZiePZjeQZki dZed[ed\e"d]e2d^e$d_e!d`edaedbe#dceGddedee dfedgedhe<die>djee5e;eeHeMe0eJeLeEeNeOePeQdkZlG dldm dmejmZnG dndo doejoZpG dpdq dqejqZrG drds dserZsG dtdu duejtZuG dvdw dwejvZwdxdy Zxdzd{ Zyd|d} Zzd~d Z{e| Z}dd Z~G dd dejZdS )aY  
.. dialect:: mssql
    :name: Microsoft SQL Server


.. _mssql_identity:

Auto Increment Behavior / IDENTITY Columns
------------------------------------------

SQL Server provides so-called "auto incrementing" behavior using the
``IDENTITY`` construct, which can be placed on any single integer column in a
table. SQLAlchemy considers ``IDENTITY`` within its default "autoincrement"
behavior for an integer primary key column, described at
:paramref:`_schema.Column.autoincrement`.  This means that by default,
the first
integer primary key column in a :class:`_schema.Table`
will be considered to be the
identity column and will generate DDL as such::

    from sqlalchemy import Table, MetaData, Column, Integer

    m = MetaData()
    t = Table('t', m,
            Column('id', Integer, primary_key=True),
            Column('x', Integer))
    m.create_all(engine)

The above example will generate DDL as:

.. sourcecode:: sql

    CREATE TABLE t (
        id INTEGER NOT NULL IDENTITY(1,1),
        x INTEGER NULL,
        PRIMARY KEY (id)
    )

For the case where this default generation of ``IDENTITY`` is not desired,
specify ``False`` for the :paramref:`_schema.Column.autoincrement` flag,
on the first integer primary key column::

    m = MetaData()
    t = Table('t', m,
            Column('id', Integer, primary_key=True, autoincrement=False),
            Column('x', Integer))
    m.create_all(engine)

To add the ``IDENTITY`` keyword to a non-primary key column, specify
``True`` for the :paramref:`_schema.Column.autoincrement` flag on the desired
:class:`_schema.Column` object, and ensure that
:paramref:`_schema.Column.autoincrement`
is set to ``False`` on any integer primary key column::

    m = MetaData()
    t = Table('t', m,
            Column('id', Integer, primary_key=True, autoincrement=False),
            Column('x', Integer, autoincrement=True))
    m.create_all(engine)

.. versionchanged::  1.3   Added ``mssql_identity_start`` and
   ``mssql_identity_increment`` parameters to :class:`_schema.Column`.
   These replace
   the use of the :class:`.Sequence` object in order to specify these values.

.. deprecated:: 1.3

   The use of :class:`.Sequence` to specify IDENTITY characteristics is
   deprecated and will be removed in a future release.   Please use
   the ``mssql_identity_start`` and ``mssql_identity_increment`` parameters
   documented at :ref:`mssql_identity`.

.. note::

    There can only be one IDENTITY column on the table.  When using
    ``autoincrement=True`` to enable the IDENTITY keyword, SQLAlchemy does not
    guard against multiple columns specifying the option simultaneously.  The
    SQL Server database will instead reject the ``CREATE TABLE`` statement.

.. note::

    An INSERT statement which attempts to provide a value for a column that is
    marked with IDENTITY will be rejected by SQL Server.   In order for the
    value to be accepted, a session-level option "SET IDENTITY_INSERT" must be
    enabled.   The SQLAlchemy SQL Server dialect will perform this operation
    automatically when using a core :class:`_expression.Insert`
    construct; if the
    execution specifies a value for the IDENTITY column, the "IDENTITY_INSERT"
    option will be enabled for the span of that statement's invocation.However,
    this scenario is not high performing and should not be relied upon for
    normal use.   If a table doesn't actually require IDENTITY behavior in its
    integer primary key column, the keyword should be disabled when creating
    the table by ensuring that ``autoincrement=False`` is set.

Controlling "Start" and "Increment"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Specific control over the "start" and "increment" values for
the ``IDENTITY`` generator are provided using the
``mssql_identity_start`` and ``mssql_identity_increment`` parameters
passed to the :class:`_schema.Column` object::

    from sqlalchemy import Table, Integer, Column

    test = Table(
        'test', metadata,
        Column(
            'id', Integer, primary_key=True, mssql_identity_start=100,
             mssql_identity_increment=10
        ),
        Column('name', String(20))
    )

The CREATE TABLE for the above :class:`_schema.Table` object would be:

.. sourcecode:: sql

   CREATE TABLE test (
     id INTEGER NOT NULL IDENTITY(100,10) PRIMARY KEY,
     name VARCHAR(20) NULL,
     )

.. versionchanged:: 1.3  The ``mssql_identity_start`` and
   ``mssql_identity_increment`` parameters are now used to affect the
   ``IDENTITY`` generator for a :class:`_schema.Column` under  SQL Server.
   Previously, the :class:`.Sequence` object was used.  As SQL Server now
   supports real sequences as a separate construct, :class:`.Sequence` will be
   functional in the normal way in a future SQLAlchemy version.

INSERT behavior
^^^^^^^^^^^^^^^^

Handling of the ``IDENTITY`` column at INSERT time involves two key
techniques. The most common is being able to fetch the "last inserted value"
for a given ``IDENTITY`` column, a process which SQLAlchemy performs
implicitly in many cases, most importantly within the ORM.

The process for fetching this value has several variants:

* In the vast majority of cases, RETURNING is used in conjunction with INSERT
  statements on SQL Server in order to get newly generated primary key values:

  .. sourcecode:: sql

    INSERT INTO t (x) OUTPUT inserted.id VALUES (?)

* When RETURNING is not available or has been disabled via
  ``implicit_returning=False``, either the ``scope_identity()`` function or
  the ``@@identity`` variable is used; behavior varies by backend:

  * when using PyODBC, the phrase ``; select scope_identity()`` will be
    appended to the end of the INSERT statement; a second result set will be
    fetched in order to receive the value.  Given a table as::

        t = Table('t', m, Column('id', Integer, primary_key=True),
                Column('x', Integer),
                implicit_returning=False)

    an INSERT will look like:

    .. sourcecode:: sql

        INSERT INTO t (x) VALUES (?); select scope_identity()

  * Other dialects such as pymssql will call upon
    ``SELECT scope_identity() AS lastrowid`` subsequent to an INSERT
    statement. If the flag ``use_scope_identity=False`` is passed to
    :func:`_sa.create_engine`,
    the statement ``SELECT @@identity AS lastrowid``
    is used instead.

A table that contains an ``IDENTITY`` column will prohibit an INSERT statement
that refers to the identity column explicitly.  The SQLAlchemy dialect will
detect when an INSERT construct, created using a core
:func:`_expression.insert`
construct (not a plain string SQL), refers to the identity column, and
in this case will emit ``SET IDENTITY_INSERT ON`` prior to the insert
statement proceeding, and ``SET IDENTITY_INSERT OFF`` subsequent to the
execution.  Given this example::

    m = MetaData()
    t = Table('t', m, Column('id', Integer, primary_key=True),
                    Column('x', Integer))
    m.create_all(engine)

    with engine.begin() as conn:
        conn.execute(t.insert(), {'id': 1, 'x':1}, {'id':2, 'x':2})

The above column will be created with IDENTITY, however the INSERT statement
we emit is specifying explicit values.  In the echo output we can see
how SQLAlchemy handles this:

.. sourcecode:: sql

    CREATE TABLE t (
        id INTEGER NOT NULL IDENTITY(1,1),
        x INTEGER NULL,
        PRIMARY KEY (id)
    )

    COMMIT
    SET IDENTITY_INSERT t ON
    INSERT INTO t (id, x) VALUES (?, ?)
    ((1, 1), (2, 2))
    SET IDENTITY_INSERT t OFF
    COMMIT



This
is an auxiliary use case suitable for testing and bulk insert scenarios.

MAX on VARCHAR / NVARCHAR
-------------------------

SQL Server supports the special string "MAX" within the
:class:`_types.VARCHAR` and :class:`_types.NVARCHAR` datatypes,
to indicate "maximum length possible".   The dialect currently handles this as
a length of "None" in the base type, rather than supplying a
dialect-specific version of these types, so that a base type
specified such as ``VARCHAR(None)`` can assume "unlengthed" behavior on
more than one backend without using dialect-specific types.

To build a SQL Server VARCHAR or NVARCHAR with MAX length, use None::

    my_table = Table(
        'my_table', metadata,
        Column('my_data', VARCHAR(None)),
        Column('my_n_data', NVARCHAR(None))
    )


Collation Support
-----------------

Character collations are supported by the base string types,
specified by the string argument "collation"::

    from sqlalchemy import VARCHAR
    Column('login', VARCHAR(32, collation='Latin1_General_CI_AS'))

When such a column is associated with a :class:`_schema.Table`, the
CREATE TABLE statement for this column will yield::

    login VARCHAR(32) COLLATE Latin1_General_CI_AS NULL

LIMIT/OFFSET Support
--------------------

MSSQL has no support for the LIMIT or OFFSET keywords. LIMIT is
supported directly through the ``TOP`` Transact SQL keyword::

    select.limit

will yield::

    SELECT TOP n

If using SQL Server 2005 or above, LIMIT with OFFSET
support is available through the ``ROW_NUMBER OVER`` construct.
For versions below 2005, LIMIT with OFFSET usage will fail.

.. _mssql_isolation_level:

Transaction Isolation Level
---------------------------

All SQL Server dialects support setting of transaction isolation level
both via a dialect-specific parameter
:paramref:`_sa.create_engine.isolation_level`
accepted by :func:`_sa.create_engine`,
as well as the :paramref:`.Connection.execution_options.isolation_level`
argument as passed to
:meth:`_engine.Connection.execution_options`.
This feature works by issuing the
command ``SET TRANSACTION ISOLATION LEVEL <level>`` for
each new connection.

To set isolation level using :func:`_sa.create_engine`::

    engine = create_engine(
        "mssql+pyodbc://scott:tiger@ms_2008",
        isolation_level="REPEATABLE READ"
    )

To set using per-connection execution options::

    connection = engine.connect()
    connection = connection.execution_options(
        isolation_level="READ COMMITTED"
    )

Valid values for ``isolation_level`` include:

* ``AUTOCOMMIT`` - pyodbc / pymssql-specific
* ``READ COMMITTED``
* ``READ UNCOMMITTED``
* ``REPEATABLE READ``
* ``SERIALIZABLE``
* ``SNAPSHOT`` - specific to SQL Server

.. versionadded:: 1.2 added AUTOCOMMIT isolation level setting

.. seealso::

    :ref:`dbapi_autocommit`

Nullability
-----------
MSSQL has support for three levels of column nullability. The default
nullability allows nulls and is explicit in the CREATE TABLE
construct::

    name VARCHAR(20) NULL

If ``nullable=None`` is specified then no specification is made. In
other words the database's configured default is used. This will
render::

    name VARCHAR(20)

If ``nullable`` is ``True`` or ``False`` then the column will be
``NULL`` or ``NOT NULL`` respectively.

Date / Time Handling
--------------------
DATE and TIME are supported.   Bind parameters are converted
to datetime.datetime() objects as required by most MSSQL drivers,
and results are processed from strings if needed.
The DATE and TIME types are not available for MSSQL 2005 and
previous - if a server version below 2008 is detected, DDL
for these types will be issued as DATETIME.

.. _mssql_large_type_deprecation:

Large Text/Binary Type Deprecation
----------------------------------

Per
`SQL Server 2012/2014 Documentation <http://technet.microsoft.com/en-us/library/ms187993.aspx>`_,
the ``NTEXT``, ``TEXT`` and ``IMAGE`` datatypes are to be removed from SQL
Server in a future release.   SQLAlchemy normally relates these types to the
:class:`.UnicodeText`, :class:`_expression.TextClause` and
:class:`.LargeBinary` datatypes.

In order to accommodate this change, a new flag ``deprecate_large_types``
is added to the dialect, which will be automatically set based on detection
of the server version in use, if not otherwise set by the user.  The
behavior of this flag is as follows:

* When this flag is ``True``, the :class:`.UnicodeText`,
  :class:`_expression.TextClause` and
  :class:`.LargeBinary` datatypes, when used to render DDL, will render the
  types ``NVARCHAR(max)``, ``VARCHAR(max)``, and ``VARBINARY(max)``,
  respectively.  This is a new behavior as of the addition of this flag.

* When this flag is ``False``, the :class:`.UnicodeText`,
  :class:`_expression.TextClause` and
  :class:`.LargeBinary` datatypes, when used to render DDL, will render the
  types ``NTEXT``, ``TEXT``, and ``IMAGE``,
  respectively.  This is the long-standing behavior of these types.

* The flag begins with the value ``None``, before a database connection is
  established.   If the dialect is used to render DDL without the flag being
  set, it is interpreted the same as ``False``.

* On first connection, the dialect detects if SQL Server version 2012 or
  greater is in use; if the flag is still at ``None``, it sets it to ``True``
  or ``False`` based on whether 2012 or greater is detected.

* The flag can be set to either ``True`` or ``False`` when the dialect
  is created, typically via :func:`_sa.create_engine`::

        eng = create_engine("mssql+pymssql://user:pass@host/db",
                        deprecate_large_types=True)

* Complete control over whether the "old" or "new" types are rendered is
  available in all SQLAlchemy versions by using the UPPERCASE type objects
  instead: :class:`_types.NVARCHAR`, :class:`_types.VARCHAR`,
  :class:`_types.VARBINARY`, :class:`_types.TEXT`, :class:`_mssql.NTEXT`,
  :class:`_mssql.IMAGE`
  will always remain fixed and always output exactly that
  type.

.. versionadded:: 1.0.0

.. _multipart_schema_names:

Multipart Schema Names
----------------------

SQL Server schemas sometimes require multiple parts to their "schema"
qualifier, that is, including the database name and owner name as separate
tokens, such as ``mydatabase.dbo.some_table``. These multipart names can be set
at once using the :paramref:`_schema.Table.schema` argument of
:class:`_schema.Table`::

    Table(
        "some_table", metadata,
        Column("q", String(50)),
        schema="mydatabase.dbo"
    )

When performing operations such as table or component reflection, a schema
argument that contains a dot will be split into separate
"database" and "owner"  components in order to correctly query the SQL
Server information schema tables, as these two values are stored separately.
Additionally, when rendering the schema name for DDL or SQL, the two
components will be quoted separately for case sensitive names and other
special characters.   Given an argument as below::

    Table(
        "some_table", metadata,
        Column("q", String(50)),
        schema="MyDataBase.dbo"
    )

The above schema would be rendered as ``[MyDataBase].dbo``, and also in
reflection, would be reflected using "dbo" as the owner and "MyDataBase"
as the database name.

To control how the schema name is broken into database / owner,
specify brackets (which in SQL Server are quoting characters) in the name.
Below, the "owner" will be considered as ``MyDataBase.dbo`` and the
"database" will be None::

    Table(
        "some_table", metadata,
        Column("q", String(50)),
        schema="[MyDataBase.dbo]"
    )

To individually specify both database and owner name with special characters
or embedded dots, use two sets of brackets::

    Table(
        "some_table", metadata,
        Column("q", String(50)),
        schema="[MyDataBase.Period].[MyOwner.Dot]"
    )


.. versionchanged:: 1.2 the SQL Server dialect now treats brackets as
   identifier delimeters splitting the schema into separate database
   and owner tokens, to allow dots within either name itself.

.. _legacy_schema_rendering:

Legacy Schema Mode
------------------

Very old versions of the MSSQL dialect introduced the behavior such that a
schema-qualified table would be auto-aliased when used in a
SELECT statement; given a table::

    account_table = Table(
        'account', metadata,
        Column('id', Integer, primary_key=True),
        Column('info', String(100)),
        schema="customer_schema"
    )

this legacy mode of rendering would assume that "customer_schema.account"
would not be accepted by all parts of the SQL statement, as illustrated
below::

    >>> eng = create_engine("mssql+pymssql://mydsn", legacy_schema_aliasing=True)
    >>> print(account_table.select().compile(eng))
    SELECT account_1.id, account_1.info
    FROM customer_schema.account AS account_1

This mode of behavior is now off by default, as it appears to have served
no purpose; however in the case that legacy applications rely upon it,
it is available using the ``legacy_schema_aliasing`` argument to
:func:`_sa.create_engine` as illustrated above.

.. versionchanged:: 1.1 the ``legacy_schema_aliasing`` flag introduced
   in version 1.0.5 to allow disabling of legacy mode for schemas now
   defaults to False.


.. _mssql_indexes:

Clustered Index Support
-----------------------

The MSSQL dialect supports clustered indexes (and primary keys) via the
``mssql_clustered`` option.  This option is available to :class:`.Index`,
:class:`.UniqueConstraint`. and :class:`.PrimaryKeyConstraint`.

To generate a clustered index::

    Index("my_index", table.c.x, mssql_clustered=True)

which renders the index as ``CREATE CLUSTERED INDEX my_index ON table (x)``.

To generate a clustered primary key use::

    Table('my_table', metadata,
          Column('x', ...),
          Column('y', ...),
          PrimaryKeyConstraint("x", "y", mssql_clustered=True))

which will render the table, for example, as::

  CREATE TABLE my_table (x INTEGER NOT NULL, y INTEGER NOT NULL,
                         PRIMARY KEY CLUSTERED (x, y))

Similarly, we can generate a clustered unique constraint using::

    Table('my_table', metadata,
          Column('x', ...),
          Column('y', ...),
          PrimaryKeyConstraint("x"),
          UniqueConstraint("y", mssql_clustered=True),
          )

To explicitly request a non-clustered primary key (for example, when
a separate clustered index is desired), use::

    Table('my_table', metadata,
          Column('x', ...),
          Column('y', ...),
          PrimaryKeyConstraint("x", "y", mssql_clustered=False))

which will render the table, for example, as::

  CREATE TABLE my_table (x INTEGER NOT NULL, y INTEGER NOT NULL,
                         PRIMARY KEY NONCLUSTERED (x, y))

.. versionchanged:: 1.1 the ``mssql_clustered`` option now defaults
   to None, rather than False.  ``mssql_clustered=False`` now explicitly
   renders the NONCLUSTERED clause, whereas None omits the CLUSTERED
   clause entirely, allowing SQL Server defaults to take effect.


MSSQL-Specific Index Options
-----------------------------

In addition to clustering, the MSSQL dialect supports other special options
for :class:`.Index`.

INCLUDE
^^^^^^^

The ``mssql_include`` option renders INCLUDE(colname) for the given string
names::

    Index("my_index", table.c.x, mssql_include=['y'])

would render the index as ``CREATE INDEX my_index ON table (x) INCLUDE (y)``

.. _mssql_index_where:

Filtered Indexes
^^^^^^^^^^^^^^^^

The ``mssql_where`` option renders WHERE(condition) for the given string
names::

    Index("my_index", table.c.x, mssql_where=table.c.x > 10)

would render the index as ``CREATE INDEX my_index ON table (x) WHERE x > 10``.

.. versionadded:: 1.3.4

Index ordering
^^^^^^^^^^^^^^

Index ordering is available via functional expressions, such as::

    Index("my_index", table.c.x.desc())

would render the index as ``CREATE INDEX my_index ON table (x DESC)``

.. seealso::

    :ref:`schema_indexes_functional`

Compatibility Levels
--------------------
MSSQL supports the notion of setting compatibility levels at the
database level. This allows, for instance, to run a database that
is compatible with SQL2000 while running on a SQL2005 database
server. ``server_version_info`` will always return the database
server version information (in this case SQL2005) and not the
compatibility level information. Because of this, if running under
a backwards compatibility mode SQLAlchemy may attempt to use T-SQL
statements that are unable to be parsed by the database server.

Triggers
--------

SQLAlchemy by default uses OUTPUT INSERTED to get at newly
generated primary key values via IDENTITY columns or other
server side defaults.   MS-SQL does not
allow the usage of OUTPUT INSERTED on tables that have triggers.
To disable the usage of OUTPUT INSERTED on a per-table basis,
specify ``implicit_returning=False`` for each :class:`_schema.Table`
which has triggers::

    Table('mytable', metadata,
        Column('id', Integer, primary_key=True),
        # ...,
        implicit_returning=False
    )

Declarative form::

    class MyClass(Base):
        # ...
        __table_args__ = {'implicit_returning':False}


This option can also be specified engine-wide using the
``implicit_returning=False`` argument on :func:`_sa.create_engine`.

.. _mssql_rowcount_versioning:

Rowcount Support / ORM Versioning
---------------------------------

The SQL Server drivers may have limited ability to return the number
of rows updated from an UPDATE or DELETE statement.

As of this writing, the PyODBC driver is not able to return a rowcount when
OUTPUT INSERTED is used.  This impacts the SQLAlchemy ORM's versioning feature
in many cases where server-side value generators are in use in that while the
versioning operations can succeed, the ORM cannot always check that an UPDATE
or DELETE statement matched the number of rows expected, which is how it
verifies that the version identifier matched.   When this condition occurs, a
warning will be emitted but the operation will proceed.

The use of OUTPUT INSERTED can be disabled by setting the
:paramref:`_schema.Table.implicit_returning` flag to ``False`` on a particular
:class:`_schema.Table`, which in declarative looks like::

    class MyTable(Base):
        __tablename__ = 'mytable'
        id = Column(Integer, primary_key=True)
        stuff = Column(String(10))
        timestamp = Column(TIMESTAMP(), default=text('DEFAULT'))
        __mapper_args__ = {
            'version_id_col': timestamp,
            'version_id_generator': False,
        }
        __table_args__ = {
            'implicit_returning': False
        }

Enabling Snapshot Isolation
---------------------------

SQL Server has a default transaction
isolation mode that locks entire tables, and causes even mildly concurrent
applications to have long held locks and frequent deadlocks.
Enabling snapshot isolation for the database as a whole is recommended
for modern levels of concurrency support.  This is accomplished via the
following ALTER DATABASE commands executed at the SQL prompt::

    ALTER DATABASE MyDatabase SET ALLOW_SNAPSHOT_ISOLATION ON

    ALTER DATABASE MyDatabase SET READ_COMMITTED_SNAPSHOT ON

Background on SQL Server snapshot isolation is available at
http://msdn.microsoft.com/en-us/library/ms175095.aspx.

    N   )information_schema   )engine)exc)schema)sql)types)util)default)
reflection)compiler)
expression)func)quoted_name)BIGINT)BINARY)CHAR)DATE)DATETIME)DECIMAL)FLOAT)INTEGER)NCHAR)NUMERIC)NVARCHAR)SMALLINT)TEXT)VARCHARupdate_wrapper)public_factory)   )   )   )
   )	   )   )addallZalterandanyasascauthorizationbackupbeginZbetweenbreakZbrowseZbulkZbyZcascadecasecheck
checkpointclose	clusteredZcoalesceZcollatecolumncommitZcompute
constraintcontainsZcontainstablecontinueconvertcreatecrosscurrentZcurrent_datecurrent_timeZcurrent_timestampcurrent_usercursorZdatabaseZdbccZ
deallocateZdeclarer   deleteZdenyZdescZdiskZdistinctdistributeddoubledropdumpelseendZerrlvlescapeexceptexecexecuteexistsexitZexternalfetchfileZ
fillfactorforZforeignZfreetextZfreetexttablefromfullfunctionZgotoZgrantgroupZhavingZholdlockidentityZidentity_insertZidentitycolifinindexinnerinsertZ	intersectZintoisjoinkeykillleftlikelinenoloadmergeZnationalZnocheckZnonclusterednotnullZnullifZofoffoffsetsonopenZopendatasourceZ	openqueryZ
openrowsetZopenxmloptionororderouteroverpercentZpivotZplan	precisionprimaryprintprocZ	procedurepublicZ	raiserrorreadZreadtextreconfigureZ
referencesZreplicationZrestoreZrestrictreturnrevertZrevokerightrollbackZrowcountZ
rowguidcolrulesaver   ZsecurityauditselectZsession_usersetZsetusershutdownZsome
statisticsZsystem_usertableZtablesampleZtextsizeZthentotopZtranZtransactiontriggertruncateZtsequalunionuniqueZunpivotupdateZ
updatetextZuseuservaluesZvaryingviewZwaitforwhenwherewhilewithZ	writetextc                       s    e Zd Zd Z fddZ  ZS )REALc                    s&   | dd tt| jdi | d S )Nrr       )
setdefaultsuperr   __init__)selfkw	__class__r   /home/ubuntu/experiments/live_experiments/Pythonexperiments/Otree/venv/lib/python3.10/site-packages/sqlalchemy/dialects/mssql/base.pyr     s   zREAL.__init____name__
__module____qualname____visit_name__r   __classcell__r   r   r   r   r     s    r   c                   @      e Zd Zd ZdS )TINYINTNr   r   r   r   r   r   r   r   r         r   c                   @   s&   e Zd Zdd ZedZdd ZdS )_MSDatec                 C      dd }|S )Nc                 S   &   t | tjkrt| j| j| jS | S Ntypedatetimedateyearmonthdayvaluer   r   r   process     z'_MSDate.bind_processor.<locals>.processr   r   dialectr   r   r   r   bind_processor     z_MSDate.bind_processorz(\d+)-(\d+)-(\d+)c                        fdd}|S )Nc                    Z   t | tjr
|  S t | tjr+ j| }|std| f tjdd | D  S | S )Nz"could not parse %r as a date valuec                 S      g | ]}t |pd qS r   int.0xr   r   r   
<listcomp>      z=_MSDate.result_processor.<locals>.process.<locals>.<listcomp>)	
isinstancer   r   r
   string_types_regmatch
ValueErrorgroupsr   mr   r   r   r        z)_MSDate.result_processor.<locals>.processr   r   r   coltyper   r   r   r   result_processor     z_MSDate.result_processorN)r   r   r   r   recompiler   r   r   r   r   r   r     s    
	r   c                       sF   e Zd Zd fdd	ZedddZdd Ze	dZ
d	d
 Z  ZS )TIMENc                    s   || _ tt|   d S r   )rr   r   r   r   r   rr   kwargsr   r   r   r     s   zTIME.__init__il  r   c                        fdd}|S )Nc                    s>   t | tjrtj j|  } | S t | tjr	 t| } | S r   )r   r   combine_TIME__zero_datetimestrr   r   r   r   r     s   
	z$TIME.bind_processor.<locals>.processr   r   r   r   r   r     r   zTIME.bind_processorz!(\d+):(\d+):(\d+)(?:\.(\d{0,6}))?c                    r   )Nc                    r   )Nz"could not parse %r as a time valuec                 S   r   r   r   r   r   r   r   r     r   z:TIME.result_processor.<locals>.process.<locals>.<listcomp>)	r   r   r   r
   r   r   r   r   r   r   r   r   r   r     r   z&TIME.result_processor.<locals>.processr   r   r   r   r   r     r   zTIME.result_processorr   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s    
r   c                   @      e Zd Zdd ZdS )_DateTimeBasec                 C   r   )Nc                 S   r   r   r   r   r   r   r   r     r   z-_DateTimeBase.bind_processor.<locals>.processr   r   r   r   r   r     r   z_DateTimeBase.bind_processorN)r   r   r   r   r   r   r   r   r         r   c                   @      e Zd ZdS )_MSDateTimeNr   r   r   r   r   r   r   r         r   c                   @   r   )SMALLDATETIMENr   r   r   r   r   r     r   r   c                       s"   e Zd Zd Zd fdd	Z  ZS )	DATETIME2Nc                    s    t t| jdi | || _d S )Nr   )r   r   r   rr   )r   rr   r   r   r   r   r      s   
zDATETIME2.__init__r   r   r   r   r   r   r     s    r   c                   @   s   e Zd Zd ZdddZdS )DATETIMEOFFSETNc                 K   s
   || _ d S r   rr   r   r   r   r   r   	     
zDATETIMEOFFSET.__init__r   )r   r   r   r   r   r   r   r   r   r     s    r   c                   @   r   )_UnicodeLiteralc                    r   )Nc                    s(   |  dd}  jjr|  dd} d|  S )N'z''%z%%zN'%s')replaceidentifier_preparerZ_double_percentsr   r   r   r   r     s   z2_UnicodeLiteral.literal_processor.<locals>.processr   r   r   r   r   literal_processor  s   	z!_UnicodeLiteral.literal_processorN)r   r   r   r   r   r   r   r   r     r   r   c                   @   r   )
_MSUnicodeNr   r   r   r   r   r     r   r   c                   @   r   )_MSUnicodeTextNr   r   r   r   r   r     r   r   c                       s2   e Zd ZdZd ZdZdddZ fddZ  ZS )		TIMESTAMPaB  Implement the SQL Server TIMESTAMP type.

    Note this is **completely different** than the SQL Standard
    TIMESTAMP type, which is not supported by SQL Server.  It
    is a read-only datatype that does not support INSERT of values.

    .. versionadded:: 1.2

    .. seealso::

        :class:`_mssql.ROWVERSION`

    NFc                 C   s
   || _ dS )zConstruct a TIMESTAMP or ROWVERSION type.

        :param convert_int: if True, binary integer values will
         be converted to integers on read.

        .. versionadded:: 1.2

        N)convert_int)r   r   r   r   r   r   7  s   
	zTIMESTAMP.__init__c                    s,   t t| || | jr fdd}|S  S )Nc                    s&    | } | d urt t| dd} | S )Nhex   )r   codecsencoder   super_r   r   r   F  s   z+TIMESTAMP.result_processor.<locals>.process)r   r   r   r   r   r   r   r   r   B  s
   zTIMESTAMP.result_processorF)	r   r   r   __doc__r   lengthr   r   r   r   r   r   r   r   #  s    
r   c                   @      e Zd ZdZd ZdS )
ROWVERSIONa(  Implement the SQL Server ROWVERSION type.

    The ROWVERSION datatype is a SQL Server synonym for the TIMESTAMP
    datatype, however current SQL Server documentation suggests using
    ROWVERSION for new datatypes going forward.

    The ROWVERSION datatype does **not** reflect (e.g. introspect) from the
    database as itself; the returned datatype will be
    :class:`_mssql.TIMESTAMP`.

    This is a read-only datatype that does not support INSERT of values.

    .. versionadded:: 1.2

    .. seealso::

        :class:`_mssql.TIMESTAMP`

    Nr   r   r   r   r   r   r   r   r   r   R  s    r   c                   @   r   )NTEXTzMMSSQL NTEXT type, for variable-length unicode text up to 2^30
    characters.Nr   r   r   r   r   r   j  s    r   c                   @   r   )	VARBINARYaG  The MSSQL VARBINARY type.

    This type is present to support "deprecate_large_types" mode where
    either ``VARBINARY(max)`` or IMAGE is rendered.   Otherwise, this type
    object is redundant vs. :class:`_types.VARBINARY`.

    .. versionadded:: 1.0.0

    .. seealso::

        :ref:`mssql_large_type_deprecation`



    Nr   r   r   r   r   r  r  s    r  c                   @   r   )IMAGENr   r   r   r   r   r    r   r  c                   @   r   )XMLa"  MSSQL XML type.

    This is a placeholder type for reflection purposes that does not include
    any Python-side datatype support.   It also does not currently support
    additional arguments, such as "CONTENT", "DOCUMENT",
    "xml_schema_collection".

    .. versionadded:: 1.1.11

    Nr   r   r   r   r   r    s    r  c                   @   r   )BITNr   r   r   r   r   r    r   r  c                   @   r   )MONEYNr   r   r   r   r   r    r   r  c                   @   r   )
SMALLMONEYNr   r   r   r   r   r    r   r  c                   @   r   )UNIQUEIDENTIFIERNr   r   r   r   r   r    r   r  c                   @   r   )SQL_VARIANTNr   r   r   r   r   r    r   r  c                       s$   e Zd ZdZdZ fddZ  ZS )TryCastz+Represent a SQL Server TRY_CAST expression.try_castc                    s   t t| j|i | dS )a  Create a TRY_CAST expression.

        :class:`.TryCast` is a subclass of SQLAlchemy's :class:`.Cast`
        construct, and works in the same way, except that the SQL expression
        rendered is "TRY_CAST" rather than "CAST"::

            from sqlalchemy import select
            from sqlalchemy import Numeric
            from sqlalchemy.dialects.mssql import try_cast

            stmt = select([
                try_cast(product_table.c.unit_price, Numeric(10, 4))
            ])

        The above would render::

            SELECT TRY_CAST (product_table.unit_price AS NUMERIC(10, 4))
            FROM product_table

        .. versionadded:: 1.3.7

        N)r   r	  r   )r   argr   r   r   r   r     s   zTryCast.__init__)r   r   r   r   r   r   r   r   r   r   r   r	    s    r	  z.dialects.mssql.try_castr   ZbigintZsmallintZtinyintZvarcharZnvarcharcharZnchartextZntextdecimalnumericfloatr   Z	datetime2Zdatetimeoffsetr   )r   ZsmalldatetimebinaryZ	varbinarybitrealimagexml	timestampZmoneyZ
smallmoneyZuniqueidentifierZsql_variantc                   @   s   e Zd Zd>ddZdd Zdd Zdd	 Zd
d Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Zd<d= Z dS )?MSTypeCompilerNc                 C   sN   t |ddrd|j }nd}|s|j}|r|d|  }ddd ||fD S )zYExtend a string-type declaration with standard SQL
        COLLATE annotations.

        	collationNz
COLLATE %s(%s) c                 S   s   g | ]}|d ur|qS r   r   r   cr   r   r   r     r   z*MSTypeCompiler._extend.<locals>.<listcomp>)getattrr  r   r^   )r   spectype_r   r  r   r   r   _extend	  s   zMSTypeCompiler._extendc                 K   s$   t |dd }|d u rdS dd|i S )Nrr   r   zFLOAT(%(precision)s)r  r   r  r   rr   r   r   r   visit_FLOAT  s   zMSTypeCompiler.visit_FLOATc                 K      dS )Nr   r   r   r  r   r   r   r   visit_TINYINT#     zMSTypeCompiler.visit_TINYINTc                 K   s   |j d ur
d|j  S dS )NzDATETIMEOFFSET(%s)r   r   r%  r   r   r   visit_DATETIMEOFFSET&  s   

z#MSTypeCompiler.visit_DATETIMEOFFSETc                 K       t |dd }|d urd| S dS )Nrr   zTIME(%s)r   r!  r"  r   r   r   
visit_TIME,     zMSTypeCompiler.visit_TIMEc                 K   r$  )Nr   r   r%  r   r   r   visit_TIMESTAMP3  r'  zMSTypeCompiler.visit_TIMESTAMPc                 K   r$  )Nr   r   r%  r   r   r   visit_ROWVERSION6  r'  zMSTypeCompiler.visit_ROWVERSIONc                 K   r)  )Nrr   zDATETIME2(%s)r   r!  r"  r   r   r   visit_DATETIME29  r+  zMSTypeCompiler.visit_DATETIME2c                 K   r$  )Nr   r   r%  r   r   r   visit_SMALLDATETIME@  r'  z"MSTypeCompiler.visit_SMALLDATETIMEc                 K   s   | j |fi |S r   )visit_NVARCHARr%  r   r   r   visit_unicodeC     zMSTypeCompiler.visit_unicodec                 K   ,   | j jr| j|fi |S | j|fi |S r   )r   deprecate_large_typesvisit_VARCHAR
visit_TEXTr%  r   r   r   
visit_textF     zMSTypeCompiler.visit_textc                 K   r3  r   )r   r4  r0  visit_NTEXTr%  r   r   r   visit_unicode_textL  r8  z!MSTypeCompiler.visit_unicode_textc                 K      |  d|S )Nr   r   r%  r   r   r   r9  R     zMSTypeCompiler.visit_NTEXTc                 K   r;  )Nr   r<  r%  r   r   r   r6  U  r=  zMSTypeCompiler.visit_TEXTc                 K      | j d||jpddS )Nr   maxr   r   r   r%  r   r   r   r5  X     zMSTypeCompiler.visit_VARCHARc                 K   r;  )Nr   r<  r%  r   r   r   
visit_CHAR[  r=  zMSTypeCompiler.visit_CHARc                 K   r;  )Nr   r<  r%  r   r   r   visit_NCHAR^  r=  zMSTypeCompiler.visit_NCHARc                 K   r>  )Nr   r?  r@  rA  r%  r   r   r   r0  a  rB  zMSTypeCompiler.visit_NVARCHARc                 K   0   | j jtk r| j|fi |S | j|fi |S r   )r   server_version_infoMS_2008_VERSIONvisit_DATETIMEZ
visit_DATEr%  r   r   r   
visit_dated     zMSTypeCompiler.visit_datec                 K   rE  r   )r   rF  rG  rH  r*  r%  r   r   r   
visit_timej  rJ  zMSTypeCompiler.visit_timec                 K   r3  r   )r   r4  visit_VARBINARYvisit_IMAGEr%  r   r   r   visit_large_binaryp  r8  z!MSTypeCompiler.visit_large_binaryc                 K   r$  )Nr  r   r%  r   r   r   rM  v  r'  zMSTypeCompiler.visit_IMAGEc                 K   r$  )Nr  r   r%  r   r   r   	visit_XMLy  r'  zMSTypeCompiler.visit_XMLc                 K   r>  )Nr  r?  r@  rA  r%  r   r   r   rL  |  rB  zMSTypeCompiler.visit_VARBINARYc                 K   s
   |  |S r   )	visit_BITr%  r   r   r   visit_boolean  r   zMSTypeCompiler.visit_booleanc                 K   r$  )Nr  r   r%  r   r   r   rP    r'  zMSTypeCompiler.visit_BITc                 K   r$  )Nr  r   r%  r   r   r   visit_MONEY  r'  zMSTypeCompiler.visit_MONEYc                 K   r$  )Nr  r   r%  r   r   r   visit_SMALLMONEY  r'  zMSTypeCompiler.visit_SMALLMONEYc                 K   r$  )Nr  r   r%  r   r   r   visit_UNIQUEIDENTIFIER  r'  z%MSTypeCompiler.visit_UNIQUEIDENTIFIERc                 K   r$  )Nr  r   r%  r   r   r   visit_SQL_VARIANT  r'  z MSTypeCompiler.visit_SQL_VARIANTr   )!r   r   r   r   r#  r&  r(  r*  r,  r-  r.  r/  r1  r7  r:  r9  r6  r5  rC  rD  r0  rI  rK  rN  rM  rO  rL  rQ  rP  rR  rS  rT  rU  r   r   r   r   r    s>    
r  c                   @   sL   e Zd ZdZdZdZdZdd Zdd Zdd Z	d	d
 Z
dd Zdd ZdS )MSExecutionContextFNc                 C   s   | j js| j |d S |S )Nr   )r   Zsupports_unicode_statements_encoder)r   	statementr   r   r   _opt_encode  s   zMSExecutionContext._opt_encodec              	   C   s  | j r~| jjj}|j}|du}|rM|j| jd v pJ| jjjoJ| jjjo5|j| jjjd v p5|| jjjd v pJ| jjj oJ|j| jjjv pJ|| jjjv | _	nd| _	| jj
 oc|oc| jj oc| j	 oc| j | _| j	r| j| j| d| jj| d|  dS dS dS )z#Activate IDENTITY_INSERT if needed.Nr   FzSET IDENTITY_INSERT %s ONr   )isinsertcompiledrX  r   _autoincrement_columnr_   Zcompiled_parameters
parametersZ_has_multi_parameters_enable_identity_insertinline	returningZexecutemany_select_lastrowidroot_connection_cursor_executerB   rY  r   r   format_table)r   ZtblZ
seq_columnZinsert_has_sequencer   r   r   pre_exec  s^   




*zMSExecutionContext.pre_execc              	   C   s   | j }| jr+| jjr|| jdd|  n	|| jdd|  | j d }t|d | _| j	s4| j
s4| jr>| jjr>t| | _| jrY|| j| d| jj| jjj d|  dS dS )z#Disable IDENTITY_INSERT if enabled.z$SELECT scope_identity() AS lastrowidr   zSELECT @@identity AS lastrowidr   SET IDENTITY_INSERT %s OFFN)rb  ra  r   use_scope_identityrc  rB   fetchallr   
_lastrowidrZ  isupdateisdeleter[  r`  r   ZFullyBufferedResultProxy_result_proxyr^  rY  r   rd  rX  r   )r   connrowr   r   r   	post_exec  sJ   
zMSExecutionContext.post_execc                 C   s   | j S r   )ri  r   r   r   r   get_lastrowid  s   z MSExecutionContext.get_lastrowidc                 C   sL   | j r$z| j| d| jj| jjj	  W d S  t
y#   Y d S w d S )Nrf  )r^  rB   rM   rY  r   r   rd  r[  rX  r   	Exception)r   er   r   r   handle_dbapi_exception  s   
z)MSExecutionContext.handle_dbapi_exceptionc                 C   s   | j r| j S t| S r   )rl  r   ZResultProxyr   r   r   r   get_result_proxy  s   
z#MSExecutionContext.get_result_proxy)r   r   r   r^  ra  rl  ri  rY  re  ro  rp  rs  rt  r   r   r   r   rV    s    8&rV  c                       sr  e Zd ZdZeejjdddddZ fddZ	 fd	d
Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Ze
dO fd(d)	Ze
 fd*d+Ze
dP fd-d.	Zd/d0 Zd1d2 Zd3d4 Zd5d6 Z fd7d8Z d9d: Z!d;d< Z" fd=d>Z#d?d@ Z$dAdB Z%dCdD Z&dEdF Z'dGdH Z(dIdJ Z)dKdL Z*dMdN Z+  Z,S )QMSSQLCompilerTZ	dayofyearweekdayZmillisecondmicrosecond)ZdoyZdowZmillisecondsmicrosecondsc                    s    i | _ tt| j|i | d S r   )tablealiasesr   ru  r   )r   argsr   r   r   r   r   !  s   zMSSQLCompiler.__init__c                    s    fdd}|S )Nc                    s>   | j jr| g|R i |S ttt| j}||i |S r   )r   legacy_schema_aliasingr  r   ru  r   )r   r  r   r   )r   fnr   r   decorate&  s   z<MSSQLCompiler._with_legacy_schema_aliasing.<locals>.decorater   )r|  r}  r   r|  r   _with_legacy_schema_aliasing%  s   z*MSSQLCompiler._with_legacy_schema_aliasingc                 K   r$  )NZCURRENT_TIMESTAMPr   r   r|  r   r   r   r   visit_now_func/  r'  zMSSQLCompiler.visit_now_funcc                 K   r$  )Nz	GETDATE()r   r  r   r   r   visit_current_date_func2  r'  z%MSSQLCompiler.visit_current_date_funcc                 K      d| j |fi | S NzLEN%sZfunction_argspecr  r   r   r   visit_length_func5  rB  zMSSQLCompiler.visit_length_funcc                 K   r  r  r  r  r   r   r   visit_char_length_func8  rB  z$MSSQLCompiler.visit_char_length_funcc                 K   ,   d| j |jfi || j |jfi |f S )Nz%s + %sr   ra   r{   r   r  operatorr   r   r   r   visit_concat_op_binary;     z$MSSQLCompiler.visit_concat_op_binaryc                 K   r$  )N1r   r   exprr   r   r   r   
visit_trueA  r'  zMSSQLCompiler.visit_truec                 K   r$  )N0r   r  r   r   r   visit_falseD  r'  zMSSQLCompiler.visit_falsec                 K   r  )NzCONTAINS (%s, %s)r  r  r   r   r   visit_match_op_binaryG  r  z#MSSQLCompiler.visit_match_op_binaryc                 K   s^   d}|j r	|d7 }|jr |jdu s|jr |jdkr |d|j 7 }|r$|S tjj| |fi |S )z- MS-SQL puts TOP, it's version of LIMIT here  z	DISTINCT Nr   zTOP %d )	Z	_distinct_simple_int_limit_offset_clause_simple_int_offset_offset_limitr   SQLCompilerget_select_precolumns)r   r   r   sr   r   r   r  M  s    

z#MSSQLCompiler.get_select_precolumnsc                 C      |S r   r   r   r   r  r   r   r   get_from_hint_textd  r'  z MSSQLCompiler.get_from_hint_textc                 C   r  r   r   r  r   r   r   get_crud_hint_textg  r'  z MSSQLCompiler.get_crud_hint_textc                 K   r$  Nr  r   )r   r   r   r   r   r   limit_clausej     zMSSQLCompiler.limit_clausec                 K   s,   d| j |jfi || j |jfi |f S )NzTRY_CAST (%s AS %s))r   ZclauseZ
typeclause)r   elementr   r   r   r   visit_try_castn  r  zMSSQLCompiler.visit_try_castc                 K   s(  |j s|jdus|jdur|jr|jrt|dds|jjs"t	ddd |jjD }|j}|j}||d< |
 }d|_|tj j|dd	d }td	}td
d |jD }|dury|||k |durx|||| k n|||k | j|fi |S tjj| |fi |S )zLook for ``LIMIT`` and OFFSET in a select statement, and if
        so tries to wrap it in a subquery with ``row_number()`` criterion.

        N_mssql_visitzLMSSQL requires an order_by when using an OFFSET or a non-simple LIMIT clausec                 S   s   g | ]}t |qS r   )sql_utilZunwrap_label_reference)r   elemr   r   r   r     s    z.MSSQLCompiler.visit_select.<locals>.<listcomp>Zselect_wraps_forTorder_bymssql_rnc                 S   s   g | ]	}|j d kr|qS )r  )r_   r  r   r   r   r     s    )r  Z_limit_clauser  r  r  r  _order_by_clauseZclausesr   CompileErrorZ	_generater  r7   r   r   Z
ROW_NUMBERrp   labelr  aliasr   r  Zappend_whereclauser   r   r  visit_select)r   r   r   Z_order_by_clausesr  Zoffset_clauser  Zlimitselectr   r   r   r  t  sZ   





zMSSQLCompiler.visit_selectFc                    sd   ||u s|rt t| j|fi |S | |}|d ur&| j|fd|i|S t t| j|fi |S Nmssql_aliased)r   ru  visit_table_schema_aliased_tabler   )r   r   r  iscrudr   r  r   r   r   r    s   
zMSSQLCompiler.visit_tablec                    s"   |j |d< tt| j|fi |S r  )originalr   ru  visit_alias)r   r  r   r   r   r   r    s   
zMSSQLCompiler.visit_aliasNc                    s   |j d ur| js| jr|  r>| |j }|d ur>t||}|d ur2||j|j||j|jf|j	 t
t| j|fi |S t
t| j|fd|i|S )Nadd_to_result_map)r   rj  rk  is_subqueryr  r   Z_corresponding_column_or_errornamer_   r   r   ru  visit_column)r   r7   r  r   tZ	convertedr   r   r   r    s6   

zMSSQLCompiler.visit_columnc                 C   s6   t |dd d ur|| jvr| | j|< | j| S d S )Nr   )r  ry  r  )r   r   r   r   r   r    s
   

z#MSSQLCompiler._schema_aliased_tablec                 K   s.   | j |j|j}d|| j|jfi |f S )NzDATEPART(%s, %s))extract_mapgetfieldr   r  )r   extractr   r  r   r   r   visit_extract  s   zMSSQLCompiler.visit_extractc                 C      d| j | S )NzSAVE TRANSACTION %spreparerZformat_savepointr   Zsavepoint_stmtr   r   r   visit_savepoint     zMSSQLCompiler.visit_savepointc                 C   r  )NzROLLBACK TRANSACTION %sr  r  r   r   r   visit_rollback_to_savepoint  r  z)MSSQLCompiler.visit_rollback_to_savepointc                    sb   t |jtjr%|jtjkr%t |jtjs%| jt|j|j|jfi |S t	t
| j|fi |S )z]Move bind parameters to the right-hand side of an operator, where
        possible.

        )r   ra   r   ZBindParameterr  eqr{   r   ZBinaryExpressionr   ru  visit_binary)r   r  r   r   r   r   r    s   zMSSQLCompiler.visit_binaryc                    sX   j sjr|jd}n|jd}t|  fddt|D }dd| S )NZinsertedZdeletedc              	      s$   g | ]} d  |ddi qS )NTF)Z_label_select_columntraverser  adapterr   r   r   r     s    z2MSSQLCompiler.returning_clause.<locals>.<listcomp>zOUTPUT , )	rZ  rj  r   r  r  ZClauseAdapterr   Z_select_iterablesr^   )r   stmtZreturning_colstargetcolumnsr   r  r   returning_clause  s   
zMSSQLCompiler.returning_clausec                 C   r$  )NZWITHr   )r   	recursiver   r   r   get_cte_preamble  s   zMSSQLCompiler.get_cte_preamblec                    s*   t |tjr|d S tt| |||S r   )r   r   Functionr  r   ru  label_select_column)r   r   r7   asfromr   r   r   r    s
   

z!MSSQLCompiler.label_select_columnc                 C   r$  r  r   )r   r   r   r   r   for_update_clause$  s   zMSSQLCompiler.for_update_clausec                 K   s6   |   r	|js	dS | j|jfi |}|rd| S dS )Nr  z
 ORDER BY )r  r  r   r  )r   r   r   r  r   r   r   order_by_clause)  s   zMSSQLCompiler.order_by_clausec                    &   dd  fdd|g| D  S )a  Render the UPDATE..FROM clause specific to MSSQL.

        In MSSQL, if the UPDATE statement involves an alias of the table to
        be updated, then the table itself must be added to the FROM list as
        well. Otherwise, it is optional. Here, we add it regardless.

        FROM r  c                 3   (    | ]}|j fd  dV  qdS T)r  Z	fromhintsNZ_compiler_dispatchr   r  
from_hintsr   r   r   r   	<genexpr>B  
    
z3MSSQLCompiler.update_from_clause.<locals>.<genexpr>r^   )r   Zupdate_stmt
from_tableextra_fromsr  r   r   r  r   update_from_clause8  s   

z MSSQLCompiler.update_from_clausec                 C   s   d}|rd}|j | dd|dS )z=If we have extra froms make sure we render any alias as hint.FT)r  r  ashintr  )r   delete_stmtr  r  r  r   r   r   delete_table_clauseG  s   z!MSSQLCompiler.delete_table_clausec                    r  )zjRender the DELETE .. FROM clause specific to MSSQL.

        Yes, it has the FROM keyword twice.

        r  r  c                 3   r  r  r  r  r  r   r   r  X  r  z9MSSQLCompiler.delete_extra_from_clause.<locals>.<genexpr>r  )r   r  r  r  r  r   r   r  r   delete_extra_from_clauseP  s   
z&MSSQLCompiler.delete_extra_from_clausec                 C   r$  )NzSELECT 1 WHERE 1!=1r   )r   r  r   r   r   visit_empty_set_expr]  r'  z"MSSQLCompiler.visit_empty_set_exprc                 K      d|  |j|  |jf S )Nz*NOT EXISTS (SELECT %s INTERSECT SELECT %s)r  r  r   r   r   visit_is_distinct_from_binary`     

z+MSSQLCompiler.visit_is_distinct_from_binaryc                 K   r  )Nz&EXISTS (SELECT %s INTERSECT SELECT %s)r  r  r   r   r    visit_isnot_distinct_from_binaryf  r  z.MSSQLCompiler.visit_isnot_distinct_from_binary)FFr   )-r   r   r   Zreturning_precedes_valuesr
   Zupdate_copyr   r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r   r   r   ru    s`    

:	ru  c                       s4   e Zd ZdZdZdd Zdd Z fddZ  ZS )	MSSQLStrictCompilerzA subclass of MSSQLCompiler which disables the usage of bind
    parameters where not allowed natively by MS-SQL.

    A dialect may use this compiler on a platform where native
    binds are used.

    Tc                 K   4   d|d< d| j |jfi || j |jfi |f S )NTliteral_bindsz%s IN %sr  r  r   r   r   visit_in_op_binaryy  
   z&MSSQLStrictCompiler.visit_in_op_binaryc                 K   r  )NTr  z%s NOT IN %sr  r  r   r   r   visit_notin_op_binary  r  z)MSSQLStrictCompiler.visit_notin_op_binaryc                    s2   t t|tjrdt| d S tt| ||S )a5  
        For date and datetime values, convert to a string
        format acceptable to MSSQL. That seems to be the
        so-called ODBC canonical date format which looks
        like this:

            yyyy-mm-dd hh:mi:ss.mmm(24h)

        For other data types, call the base class implementation.
        r   )
issubclassr   r   r   r   r   r  render_literal_value)r   r   r  r   r   r   r    s
   
z(MSSQLStrictCompiler.render_literal_value)	r   r   r   r   Zansi_bind_rulesr  r  r  r   r   r   r   r   r  m  s    r  c                   @   s>   e Zd Zdd ZdddZdd Zdd	 Zd
d Zdd ZdS )MSDDLCompilerc                 K   s  | j |}|jd ur|d| |j 7 }n|d| jjj|j|d 7 }|jd urI|jr;|js;t	|j
tjs;|jdu r@|d7 }n	|jd u rI|d7 }|jd u rStdt	|j
tjr|j
jd usl|j
jd usl||jjurqtd |j
jdkrzd}n|j
jpd	}|d
||j
jpd	f 7 }|S ||jju s|jdu r|jd d }|jd d }|d
||f 7 }|S | |}|d ur|d| 7 }|S )Nr  )Ztype_expressionTz	 NOT NULLz NULLz;mssql requires Table-bound columns in order to generate DDLa  Use of Sequence with SQL Server in order to affect the parameters of the IDENTITY value is deprecated, as Sequence will correspond to an actual SQL Server CREATE SEQUENCE in a future release.  Please use the mssql_identity_start and mssql_identity_increment parameters.r   r   z IDENTITY(%s,%s)mssqlidentity_startidentity_incrementz	 DEFAULT )r  Zformat_columncomputedr   r   type_compilerr   nullableZprimary_keyr   r   	sa_schemaSequenceautoincrementr   r   r  start	incrementr\  r
   warn_deprecateddialect_optionsZget_column_default_string)r   r7   r   Zcolspecr  r  r   r   r   r   get_column_specification  s\   






	


z&MSDDLCompiler.get_column_specificationFc              	      s  |j    jd} jr|d7 } jd d }|d ur*|r&|d7 }n|d7 }|dj |d jd	fd
d j	D f 7 } jd d rl fdd jd d D }|dd	fdd|D  7 } jd d }|d urj
j|ddd}|d| 7 }|S )NzCREATE UNIQUE r  r6   
CLUSTERED NONCLUSTERED zINDEX %s ON %s (%s)include_schemar  c                 3   s"    | ]} j j|d ddV  qdS )FTZinclude_tabler  N)sql_compilerr   )r   r  r   r   r   r    s    
z3MSDDLCompiler.visit_create_index.<locals>.<genexpr>includec                    s(   g | ]}t |tjr jj| n|qS r   )r   r
   r   r   r  )r   col)rZ   r   r   r      s    
z4MSDDLCompiler.visit_create_index.<locals>.<listcomp>z INCLUDE (%s)c                    s   g | ]}  |jqS r   )quoter  r  )r  r   r   r     r   r   FTr  z WHERE )r  Z_verify_index_tabler  r   r  _prepared_index_namerd  r   r^   Zexpressionsr  r   )r   r=   r  r  r6   Z
inclusionswhereclauseZwhere_compiledr   )rZ   r  r   r   visit_create_index  s@   



z MSDDLCompiler.visit_create_indexc                 C   s$   d| j |jdd| j|jjf S )Nz
DROP INDEX %s ON %sFr  )r  r  r  rd  r   )r   rF   r   r   r   visit_drop_index  s   zMSDDLCompiler.visit_drop_indexc                    s   t |dkrdS d}|jd ur|d j| 7 }|d7 }|jd d }|d ur3|r/|d7 }n|d7 }|d	d
 fdd|D  7 }| |7 }|S )Nr   r  CONSTRAINT %s zPRIMARY KEY r  r6   r
  r  r  r  c                 3       | ]
} j |jV  qd S r   r  r  r  r  r   r   r   r  ,      
z=MSDDLCompiler.visit_primary_key_constraint.<locals>.<genexpr>lenr  r  Zformat_constraintr  r^   Zdefine_constraint_deferrability)r   r9   r  r6   r   r   r   visit_primary_key_constraint  s$   


z*MSDDLCompiler.visit_primary_key_constraintc                    s   t |dkrdS d}|jd ur j|}|d ur|d| 7 }|d7 }|jd d }|d ur9|r5|d7 }n|d7 }|d	d
 fdd|D  7 }| |7 }|S )Nr   r  r  r	  r  r6   r
  r  r  r  c                 3   r  r   r  r  r   r   r   r  C  r  z8MSDDLCompiler.visit_unique_constraint.<locals>.<genexpr>r  )r   r9   r  Zformatted_namer6   r   r   r   visit_unique_constraint2  s$   

z%MSDDLCompiler.visit_unique_constraintc                 C   s.   d| j j|jddd }|jdu r|d7 }|S )NzAS (%s)FTr  z
 PERSISTED)r  r   sqltext	persisted)r   	generatedr  r   r   r   visit_computed_columnI  s   
z#MSDDLCompiler.visit_computed_columnNr   )	r   r   r   r  r  r  r  r  r"  r   r   r   r   r    s    
F2r  c                       s:   e Zd ZeZ fddZdd Zdd Zd
dd	Z  Z	S )MSIdentifierPreparerc                    s   t t| j|dddd d S )N[]F)Zinitial_quoteZfinal_quoteZquote_case_sensitive_collations)r   r#  r   )r   r   r   r   r   r   V  s   

zMSIdentifierPreparer.__init__c                 C      | ddS )Nr%  ]]r   r   r   r   r   r   _escape_identifier^  r=  z'MSIdentifierPreparer._escape_identifierc                 C   r&  )Nr'  r%  r(  r)  r   r   r   _unescape_identifiera  r=  z)MSIdentifierPreparer._unescape_identifierNc                 C   sX   |dur	t d t|\}}|rd| || |f }|S |r(| |}|S d}|S )z'Prepare a quoted table and schema name.NzThe IdentifierPreparer.quote_schema.force parameter is deprecated and will be removed in a future release.  This flag has no effect on the behavior of the IdentifierPreparer.quote method; please refer to quoted_name().%s.%sr  )r
   r  _schema_elementsr  )r   r   forcedbnameownerresultr   r   r   quote_schemad  s   
z!MSIdentifierPreparer.quote_schemar   )
r   r   r   RESERVED_WORDSZreserved_wordsr   r*  r+  r2  r   r   r   r   r   r#  S  s    r#  c                       d fdd	}t | S )Nc              	      s,   t | |\}}t|| | ||||fi |S r   _owner_plus_db
_switch_db)r   
connectionr   r   r/  r0  r~  r   r   wrap  s   	z$_db_plus_owner_listing.<locals>.wrapr   r   r|  r9  r   r~  r   _db_plus_owner_listing~  s   
r;  c                    r4  )Nc              
      s.   t | |\}}t|| | |||||f	i |S r   r5  )r   r8  	tablenamer   r   r/  r0  r~  r   r   r9    s   
z_db_plus_owner.<locals>.wrapr   r   r:  r   r~  r   _db_plus_owner  s   
r=  c                 O   s   | r| d}|| kr|d|jj|   z||i |W | r2|| kr3|d|jj|  S S S | rG|| krH|d|jj|  w w w )Nzselect db_name()zuse %s)scalarrM   r   r   r  )r/  r8  r|  r  r   Z
current_dbr   r   r   r7    s*   
r7  c                 C   s&   |sd | j fS d|v rt|S d |fS )N.)default_schema_namer-  )r   r   r   r   r   r6    s
   
r6  c                 C   sJ  t | tr| jrd | fS | tv rt|  S g }d}d}d}td| D ]3}|s'q"|dkr0d}d}q"|dkr7d}q"|sQ|dkrQ|rG|d|  n|| d}d}q"||7 }q"|r]|| t|d	krd|d
d |d }}t	d|d	d rt|dd}n|
dd}nt|rd |d
 }}nd\}}||ft| < ||fS )Nr  Fz
(\[|\]|\.)r$  Tr%  r?  z[%s]r   r   z
.*\].*\[.*r  )NN)r   r   r  _memoized_schemar   splitappendr  r^   r   lstriprstrip)r   pushsymbolZbracketZhas_bracketstokenr/  r0  r   r   r   r-    sF   	


r-  c                
       s  e Zd ZdZdZdZeZdZdZ	dZ
ejeejeejeejeejeiZejjdejfgZeZdZdZdZ dZ!dZ"dZ#e$Z%e&Z'e(Z)e*Z+e,j-dd	ife,j.dd	ife,j/d	d	d	d
fe,j0dddfgZ1									d4 fdd	Z2 fddZ3dd Z4e5g dZ6dd Z7dd Z8 fddZ9dd Z:dd Z;dd Z<d d! Z=e>d"d# Z?e@jAd$d% ZBe@jAeCd&d' ZDe@jAeCd(d) ZEe@jAe>d*d+ ZFe@jAe>d,d- ZGe@jAe>d.d/ ZHe@jAe>d0d1 ZIe@jAe>d2d3 ZJ  ZKS )5	MSDialectr  TF   dbor{  r   r6   N)r6   r  r   r   )r  r  c                    sF   t |pd| _|| _|| _|| _|| _tt| jdi | || _	d S )Nr   r   )
r   query_timeoutschema_namerg  r4  r{  r   rK  r   isolation_level)r   rN  rg  rO  rP  r4  r{  optsr   r   r   r   "	  s   

zMSDialect.__init__c                    s    | d tt| || d S )Nz$IF @@TRANCOUNT = 0 BEGIN TRANSACTION)rM   r   rK  do_savepointr   r8  r  r   r   r   rR  7	  s   
zMSDialect.do_savepointc                 C   s   d S r   r   rS  r   r   r   do_release_savepoint<	  r  zMSDialect.do_release_savepoint)ZSERIALIZABLEzREAD UNCOMMITTEDzREAD COMMITTEDzREPEATABLE READSNAPSHOTc                 C   sj   | dd}|| jvrtd|| jd| jf | }|d|  |  |dkr3|	  d S d S )N_r  zLInvalid value '%s' for isolation_level. Valid isolation levels for %s are %sr  z"SET TRANSACTION ISOLATION LEVEL %srU  )
r   _isolation_lookupr   ArgumentErrorr  r^   rB   rM   r5   r8   )r   r8  levelrB   r   r   r   set_isolation_levelJ	  s   
zMSDialect.set_isolation_levelc                 C   s   | j tk r	tdd }d}|D ]A}| }z6z|d|  | d }W n | jjy@ } z|}W Y d }~W |  qd }~ww |	 W |    S |  w t
d||f  td||f )Nz4Can't fetch isolation level prior to SQL Server 2005)zsys.dm_exec_sessionszsys.dm_pdw_nodes_exec_sessionsa  
                  SELECT CASE transaction_isolation_level
                    WHEN 0 THEN NULL
                    WHEN 1 THEN 'READ UNCOMMITTED'
                    WHEN 2 THEN 'READ COMMITTED'
                    WHEN 3 THEN 'REPEATABLE READ'
                    WHEN 4 THEN 'SERIALIZABLE'
                    WHEN 5 THEN 'SNAPSHOT' END AS TRANSACTION_ISOLATION_LEVEL
                    FROM %s
                    where session_id = @@SPID
                  r   zQCould not fetch transaction isolation level, tried views: %s; final error was: %szgCan't fetch isolation level on this particular SQL Server version. tried views: %s; final error was: %s)rF  MS_2005_VERSIONNotImplementedErrorrB   rM   fetchoneZdbapiErrorr5   upperr
   warn)r   r8  Z
last_errorZviewsr   rB   valerrr   r   r   get_isolation_levelX	  sB   

zMSDialect.get_isolation_levelc                    s&   t t| | |   | | d S r   )r   rK  
initialize_setup_version_attributes_setup_supports_nvarchar_maxr   r8  r   r   r   rd  	  s   zMSDialect.initializec                    s    j d ur fdd}|S d S )Nc                    s     |  j d S r   )rZ  rP  )rm  r   r   r   connect	  r2  z%MSDialect.on_connect.<locals>.connect)rP  )r   rh  r   r   r   
on_connect	  s   
zMSDialect.on_connectc                 C   s   | j d ttddvrtdddd | j D   | j tkr)d| jvr)d	| _| j t	kr1d	| _
| jd u r>| j tk| _d S d S )
Nr   r'      z[Unrecognized server version info '%s'.  Some SQL Server features may not function properly.r?  c                 s   s    | ]}t |V  qd S r   )r   r   r   r   r   r  	  s    z6MSDialect._setup_version_attributes.<locals>.<genexpr>implicit_returningT)rF  listranger
   r`  r^   r[  __dict__rk  rG  Zsupports_multivalues_insertr4  MS_2012_VERSIONr   r   r   r   re  	  s   



z#MSDialect._setup_version_attributesc                 C   s<   z
| td W n tjy   d| _Y d S w d| _d S )Nz0SELECT CAST('test max support' AS NVARCHAR(max))FT)r>  r   r  r   Z
DBAPIError_supports_nvarchar_maxrg  r   r   r   rf  	  s   
z&MSDialect._setup_supports_nvarchar_maxc                 C   s>   | j tk r| jS td}||}|d urt|ddS | jS )NzSELECT schema_name()TrB  )rF  r[  rO  r   r  r>  r   )r   r8  queryr@  r   r   r   _get_default_schema_name	  s   


z"MSDialect._get_default_schema_namec           
      C   sN   t j}|jj|k}|rt||jj|k}t|g|}||}	|		 d uS r   )
ischemar  r  
table_namer   and_table_schemar   rM   first)
r   r8  r<  r/  r0  r   r  r  r  r  r   r   r   	has_table	  s   
zMSDialect.has_tablec                 K   s6   t jtjjjgtjjjgd}dd ||D }|S )Nr  c                 S      g | ]}|d  qS r   r   r   rr   r   r   r   	      z.MSDialect.get_schema_names.<locals>.<listcomp>)r   r   rs  Zschematar  rO  rM   )r   r8  r   r  Zschema_namesr   r   r   get_schema_names	  s   

zMSDialect.get_schema_namesc           	      K   R   t j}tj|jjgt|jj|k|jjdk|jjgd}dd |	|D }|S )Nz
BASE TABLEr  c                 S   ry  r   r   rz  r   r   r   r   	  r|  z-MSDialect.get_table_names.<locals>.<listcomp>
rs  tablesr   r   r  rt  ru  rv  Z
table_typerM   )	r   r8  r/  r0  r   r   r  r  Ztable_namesr   r   r   get_table_names	  s   

zMSDialect.get_table_namesc           	      K   r~  )NZVIEWr  c                 S   ry  r   r   rz  r   r   r   r   	  r|  z,MSDialect.get_view_names.<locals>.<listcomp>r  )	r   r8  r/  r0  r   r   r  r  Z
view_namesr   r   r   get_view_names	  s   zMSDialect.get_view_namesc           
      K   s   | j tk rg S |tdtd|t td|t j	t
 d}i }|D ]}	|	d |	d dkg d||	d	 < q+|td
td|t td|t j	t
 d}|D ]}	|	d	 |v ru||	d	  d |	d  q`t| S )Na  select ind.index_id, ind.is_unique, ind.name from sys.indexes as ind join sys.tables as tab on ind.object_id=tab.object_id join sys.schemas as sch on sch.schema_id=tab.schema_id where tab.name = :tabname and sch.name=:schname and ind.is_primary_key=0 and ind.type != 0Ztabnameschname)r  r  Z	is_uniquer   )r  r   column_namesZindex_idaR  select ind_col.index_id, ind_col.object_id, col.name from sys.columns as col join sys.tables as tab on tab.object_id=col.object_id join sys.index_columns as ind_col on (ind_col.column_id=col.column_id and ind_col.object_id=tab.object_id) join sys.schemas as sch on sch.schema_id=tab.schema_id where tab.name=:tabname and sch.name=:schnamer  )rF  r[  rM   r   r  
bindparams	bindparamrs  CoerceUnicoder  sqltypesUnicoderE  rl  r   )
r   r8  r<  r/  r0  r   r   rpZindexesrn  r   r   r   get_indexes	  sF   
	
zMSDialect.get_indexesc           	      K   sH   | tdtd|t td|t }|r"| }|S d S )Nzselect definition from sys.sql_modules as mod, sys.views as views, sys.schemas as sch where mod.object_id=views.object_id and views.schema_id=sch.schema_id and views.name=:viewname and sch.name=:schnameviewnamer  )rM   r   r  r  r  rs  r  r>  )	r   r8  r  r/  r0  r   r   r  Zview_defr   r   r   get_view_definition,
  s   zMSDialect.get_view_definitionc           &   
   K   s  t j}t j}|r0t|jj|k|jj|k}	d||f }
|jjd |jj }|jjt	|k}n|jj|k}	|}
|jjt	|jjk}t||jj
|jjk}|j||dd}| jr_|jj}n
t|jjtd}tj|||jjg|	||jjgd}||}g }	 | }|d u rn||jj
 }||jj }||jj dk}||jj }||jj }||jj }||jj }||jj }|| }||jj }| j|d }i }|tt t!t"t#t$t%t&t'j(f	v r|dkrd }||d	< |r||d
< |d u rt)*d||f  t'j+}nt,|t'j-r||d< t,|t'j.s||d< |di |}||||dd}|d ur5|d ur5||d|d< |/| qi } |D ]	}!|!| |!d < q?|t0d||d}"d }#	 |" }|d u rbn(|d |d }$}%|%1dr|$| v r|$}#d| |$ d< ddd| |$ d< nqX|"2  |#d ur| j3t4krd||f }
|d|
|
f }"|"5 }|d ur|d d ur| |# d 6t7|d t7|d d |S )Nr,  r?  T)ZonclauseZisouteri  )Zfrom_objr  ZYESrA  r   r  z*Did not recognize type '%s' of column '%s'rr   scaleF)r  r   r   r   r  )r  r   r  r  zAsp_columns @table_name = :table_name, @table_owner = :table_owner)rt  Ztable_ownerr      rW   r  r   )Zmssql_identity_startZmssql_identity_incrementr  z)select ident_seed('%s'), ident_incr('%s')r   r   )8rs  r  Zcomputed_columnsr   ru  r  rt  rv  Z	object_idr   column_namer  r^   rp  
definitioncastr   r   is_persistedordinal_positionrM   r]  Z	data_typeZis_nullableZcharacter_maximum_lengthZnumeric_precisionZnumeric_scaleZcolumn_defaultZcollation_nameischema_namesr  MSStringMSChar
MSNVarcharMSNCharMSTextMSNTextMSBinaryMSVarBinaryr  LargeBinaryr
   r`  ZNULLTYPEr  ZNumericFloatrE  r  endswithr5   rF  r[  rw  r   r   )&r   r8  r<  r/  r0  r   r   r  Zcomputed_colsr  Ztable_fullnameZ	full_nameZjoin_onr^   Zcomputed_definitionr  r  colsrn  r  r  r   ZcharlenZnumericprecZnumericscaler   r  r  r  r   r   ZcdictZcolmapr  rB   ZicZcol_name	type_namer   r   r   get_columnsD
  s   






A


zMSDialect.get_columnsc              
   K   s   g }t j}t jd}	t|	jj|jj|	jj	gt
|jj	|	jj	k|jj|	jjk|	jj|k|	jj|k|jj	|	jj}
||
}d }|D ]}d||jjj v rb||d  |d u rb||	jj	j }qE||dS )NCZPRIMARYr   )constrained_columnsr  )rs  constraintskey_constraintsr  r   r   r  r  Zconstraint_typeconstraint_nameru  rv  rt  r  r  rM   r  rE  )r   r8  r<  r/  r0  r   r   ZpkeysZTCr  r  r  r  rn  r   r   r   get_pk_constraint
  s.   


	
zMSDialect.get_pk_constraintc                 K   s  t j}t jd}t jd}	tj|jj|	jj|	jj	|	jj|jj
|jj|jj|jjgt|jj	|k|jj|k|jj|jjk|jj
|jj
k|	jj
|jjk|	jj|jjk|jj|	jjk|jj
|	jjgd}
g }dd }t|}||
 D ]C}|\}}}}}}}}|| }||d< |d s||d< |d us||kr|r|d | }||d	< |d
 |d }}|| || qvt| S )Nr  Rr  c                   S   s   d g d d g dS )N)r  r  referred_schemareferred_tablereferred_columnsr   r   r   r   r   fkey_rec  s   z,MSDialect.get_foreign_keys.<locals>.fkey_recr  r  r?  r  r  r  )rs  Zref_constraintsr  r  r   r   r  r  rv  rt  r  Zmatch_optionZupdate_ruleZdelete_ruleru  Zconstraint_schemaZunique_constraint_nameZunique_constraint_schemar  r
   defaultdictrM   rh  rE  rl  r   )r   r8  r<  r/  r0  r   r   ZRRr  r  r  Zfkeysr  r{  ZscolZrschemaZrtblZrcolZrfknmZfkmatchZfkupruleZ	fkdelruleZrecZ
local_colsZremote_colsr   r   r   get_foreign_keys
  sV   


	
	
zMSDialect.get_foreign_keys)NTrM  NNF)Lr   r   r   r  Zsupports_default_valuesZsupports_empty_insertrV  Zexecution_ctx_clsrg  Zmax_identifier_lengthrO  r  DateTimer   Dater   ZTimer   r  r   UnicodeTextr   Zcolspecsr   DefaultDialectZengine_config_typesr   r
   Zasboolr  Zsupports_native_booleanZ#non_native_boolean_check_constraintZsupports_unicode_bindsZpostfetch_lastrowidrp  rF  ru  Zstatement_compilerr  Zddl_compilerr  r  r#  r  r  ZPrimaryKeyConstraintZUniqueConstraintIndexColumnZconstruct_argumentsr   rR  rT  r   rW  rZ  rc  rd  ri  re  rf  rr  r=  rx  r   cacher}  r;  r  r  r  r  r  r  r  r   r   r   r   r   rK    s    
	
0



5 rK  )r   r   r   r  r   r  r   rs  r   r   r   r  r   r	   r  r
   r   r   r   r   r   r   r  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    Zutil.langhelpersr!   ZMS_2016_VERSIONZMS_2014_VERSIONro  rG  r[  ZMS_2000_VERSIONr   r3  r   Integerr   r  r   r   Z_MSTimeobjectr   r  r   r   r   Z
TypeEnginer   r   r  r   r  r   Z_Binaryr   r   r   r  r  r  Textr  r  r  r  r  r  elementsZCastr	  r
  Z
MSDateTimeZMSDateZMSRealZMSTinyIntegerZMSTimeZMSSmallDateTimeZMSDateTime2ZMSDateTimeOffsetr  r  r  r  r  r  r  r  ZMSImageZMSBitZMSMoneyZMSSmallMoneyZMSUniqueIdentifierZ	MSVariantr  ZGenericTypeCompilerr  ZDefaultExecutionContextrV  r  ru  r  ZDDLCompilerr  ZIdentifierPreparerr#  r;  r=  r7  r6  ZLRUCacherC  r-  r  rK  r   r   r   r   <module>   sJ       " ;
*	/
	
"    [/ 8+	7