o
    gi                    @  s  d Z ddlm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/m0Z0 dd#l1m2Z2 dd$l3m4Z4 dd%l3m5Z5 dd&l3m6Z6 dd'l3m7Z7 dd(l3m8Z8 dd)l3m9Z9 dd*l3m:Z: dd+l3m;Z; dd,l3m<Z< dd-l3m=Z= dd.l3m>Z> dd/l3m?Z? dd0l3m@Z@ dd1l3mAZA dd2lmBZB dd3lCmDZD e	rAdd4lEmFZF dd5lGmHZH d6ZId7ZJd8ZKd9ZLd:ZMd;ZNd<ZOh d=ZPG d>d? d?e*jQZQG d@dA dAe*jRZRG dBdC dCe*jSZTG dDdE dEe*jUZVG dFdG dGe*jWZWeWZXG dHdI dIeWZYG dJdK dKZZG dLdM dMeZe*j[Z\G dNdO dOeZe*j[Z]G dPdQ dQeZe*j[Z^G dRdS dSeZe*j[Z_G dTdU dUZ`G dVdW dWe`e*jaZbG dXdY dYe`e*jcZdG dZd[ d[e*jeZfG d\d] d]efZgG d^d_ d_e*jcZhG d`da dae*jie*jjZiG dbdc dce*jjZkG ddde dee*jlZmG dfdg dge*jnZoG dhdi die*jpZqG djdk dke*jpZrG dldm dme*jsZtG dndo doe*jse*ju ZvG dpdq dqe*jpZwe\ZxeVZyeQZzeTZ{eWZ|e]Z}e^Z~e_Ze@ZehZeAZe>Ze6Ze<Ze5ZeiZekZeoZeqZerZevZewZi dre;dse4dte?dueTdveAdwe>dxe6dye<dze@d{ehd|e9d}e=d~e:de8de^de_de7eWe]e5eieoeQeRekemefeqerevewdZG dd de$jZG dd dejZG dd de$jZG dd deZG dd de$jZG dd de$jZdd Zdd Zdd Zdd Ze Zdd ZG dd dejZdS )a  
.. dialect:: mssql
    :name: Microsoft SQL Server
    :normal_support: 2012+
    :best_effort: 2005+

.. _mssql_external_dialects:

External Dialects
-----------------

In addition to the above DBAPI layers with native SQLAlchemy support, there
are third-party dialects for other DBAPI layers that are compatible
with SQL Server. See the "External Dialects" list on the
:ref:`dialect_toplevel` page.

.. _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 - unless it is associated with a
:class:`.Sequence` - 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,
        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.4   Added :class:`_schema.Identity` construct
   in a :class:`_schema.Column` to specify the start and increment
   parameters of an IDENTITY. These replace
   the use of the :class:`.Sequence` object in order to specify these values.

.. deprecated:: 1.4

   The ``mssql_identity_start`` and ``mssql_identity_increment`` parameters
   to :class:`_schema.Column` are deprecated and should we replaced by
   an :class:`_schema.Identity` object. Specifying both ways of configuring
   an IDENTITY will result in a compile error.
   These options are also no longer returned as part of the
   ``dialect_options`` key in :meth:`_reflection.Inspector.get_columns`.
   Use the information in the ``identity`` key instead.

.. 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 :class:`_schema.Identity` object parameters
   :paramref:`_schema.Identity.start` and
   :paramref:`_schema.Identity.increment`.

.. versionchanged::  1.4   Removed the ability to use a :class:`.Sequence`
   object to modify IDENTITY characteristics. :class:`.Sequence` objects
   now only manipulate true T-SQL SEQUENCE types.

.. 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
:paramref:`_schema.Identity.start` and :paramref:`_schema.Identity.increment`
parameters passed to the :class:`_schema.Identity` object::

    from sqlalchemy import Table, Integer, Column, Identity

    test = Table(
        "test",
        metadata,
        Column(
            "id", Integer, primary_key=True, Identity(start=100, 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,
   )

.. note::

   The :class:`_schema.Identity` object supports many other parameter in
   addition to ``start`` and ``increment``. These are not supported by
   SQL Server and will be ignored when generating the CREATE TABLE ddl.

.. versionchanged:: 1.3.19  The :class:`_schema.Identity` object is
   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 starting from SQLAlchemy version 1.4.


Using IDENTITY with Non-Integer numeric types
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

SQL Server also allows ``IDENTITY`` to be used with ``NUMERIC`` columns.  To
implement this pattern smoothly in SQLAlchemy, the primary datatype of the
column should remain as ``Integer``, however the underlying implementation
type deployed to the SQL Server database can be specified as ``Numeric`` using
:meth:`.TypeEngine.with_variant`::

    from sqlalchemy import Column
    from sqlalchemy import Integer
    from sqlalchemy import Numeric
    from sqlalchemy import String
    from sqlalchemy.ext.declarative import declarative_base

    Base = declarative_base()


    class TestTable(Base):
        __tablename__ = "test"
        id = Column(
            Integer().with_variant(Numeric(10, 0), "mssql"),
            primary_key=True,
            autoincrement=True,
        )
        name = Column(String)

In the above example, ``Integer().with_variant()`` provides clear usage
information that accurately describes the intent of the code. The general
restriction that ``autoincrement`` only applies to ``Integer`` is established
at the metadata level and not at the per-dialect level.

When using the above pattern, the primary key identifier that comes back from
the insertion of a row, which is also the value that would be assigned to an
ORM object such as ``TestTable`` above, will be an instance of ``Decimal()``
and not ``int`` when using SQL Server. The numeric return type of the
:class:`_types.Numeric` type can be changed to return floats by passing False
to :paramref:`_types.Numeric.asdecimal`. To normalize the return type of the
above ``Numeric(10, 0)`` to return Python ints (which also support "long"
integer values in Python 3), use :class:`_types.TypeDecorator` as follows::

    from sqlalchemy import TypeDecorator


    class NumericAsInteger(TypeDecorator):
        "normalize floating point return values into ints"

        impl = Numeric(10, 0, asdecimal=False)
        cache_ok = True

        def process_result_value(self, value, dialect):
            if value is not None:
                value = int(value)
            return value


    class TestTable(Base):
        __tablename__ = "test"
        id = Column(
            Integer().with_variant(NumericAsInteger, "mssql"),
            primary_key=True,
            autoincrement=True,
        )
        name = Column(String)

.. _mssql_insert_behavior:

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 (?)

  As of SQLAlchemy 2.0, the :ref:`engine_insertmanyvalues` feature is also
  used by default to optimize many-row INSERT statements; for SQL Server
  the feature takes place for both RETURNING and-non RETURNING
  INSERT statements.

  .. versionchanged:: 2.0.10 The :ref:`engine_insertmanyvalues` feature for
     SQL Server was temporarily disabled for SQLAlchemy version 2.0.9 due to
     issues with row ordering. As of 2.0.10 the feature is re-enabled, with
     special case handling for the unit of work's requirement for RETURNING to
     be ordered.

* 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",
            metadata,
            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.

SEQUENCE support
----------------

The :class:`.Sequence` object creates "real" sequences, i.e.,
``CREATE SEQUENCE``:

.. sourcecode:: pycon+sql

    >>> from sqlalchemy import Sequence
    >>> from sqlalchemy.schema import CreateSequence
    >>> from sqlalchemy.dialects import mssql
    >>> print(
    ...     CreateSequence(Sequence("my_seq", start=1)).compile(
    ...         dialect=mssql.dialect()
    ...     )
    ... )
    {printsql}CREATE SEQUENCE my_seq START WITH 1

For integer primary key generation, SQL Server's ``IDENTITY`` construct should
generally be preferred vs. sequence.

.. tip::

    The default start value for T-SQL is ``-2**63`` instead of 1 as
    in most other SQL databases. Users should explicitly set the
    :paramref:`.Sequence.start` to 1 if that's the expected default::

        seq = Sequence("my_sequence", start=1)

.. versionadded:: 1.4 added SQL Server support for :class:`.Sequence`

.. versionchanged:: 2.0 The SQL Server dialect will no longer implicitly
   render "START WITH 1" for ``CREATE SEQUENCE``, which was the behavior
   first implemented in version 1.4.

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:

.. sourcecode:: sql

    login VARCHAR(32) COLLATE Latin1_General_CI_AS NULL

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

MSSQL has added support for LIMIT / OFFSET as of SQL Server 2012, via the
"OFFSET n ROWS" and "FETCH NEXT n ROWS" clauses.  SQLAlchemy supports these
syntaxes automatically if SQL Server 2012 or greater is detected.

.. versionchanged:: 1.4 support added for SQL Server "OFFSET n ROWS" and
   "FETCH NEXT n ROWS" syntax.

For statements that specify only LIMIT and no OFFSET, all versions of SQL
Server support the TOP keyword.   This syntax is used for all SQL Server
versions when no OFFSET clause is present.  A statement such as::

    select(some_table).limit(5)

will render similarly to:

.. sourcecode:: sql

    SELECT TOP 5 col1, col2.. FROM table

For versions of SQL Server prior to SQL Server 2012, a statement that uses
LIMIT and OFFSET, or just OFFSET alone, will be rendered using the
``ROW_NUMBER()`` window function.   A statement such as::

    select(some_table).order_by(some_table.c.col3).limit(5).offset(10)

will render similarly to:

.. sourcecode:: sql

    SELECT anon_1.col1, anon_1.col2 FROM (SELECT col1, col2,
    ROW_NUMBER() OVER (ORDER BY col3) AS
    mssql_rn FROM table WHERE t.x = :x_1) AS
    anon_1 WHERE mssql_rn > :param_1 AND mssql_rn <= :param_2 + :param_1

Note that when using LIMIT and/or OFFSET, whether using the older
or newer SQL Server syntaxes, the statement must have an ORDER BY as well,
else a :class:`.CompileError` is raised.

.. _mssql_comment_support:

DDL Comment Support
--------------------

Comment support, which includes DDL rendering for attributes such as
:paramref:`_schema.Table.comment` and :paramref:`_schema.Column.comment`, as
well as the ability to reflect these comments, is supported assuming a
supported version of SQL Server is in use. If a non-supported version such as
Azure Synapse is detected at first-connect time (based on the presence
of the ``fn_listextendedproperty`` SQL function), comment support including
rendering and table-comment reflection is disabled, as both features rely upon
SQL Server stored procedures and functions that are not available on all
backend types.

To force comment support to be on or off, bypassing autodetection, set the
parameter ``supports_comments`` within :func:`_sa.create_engine`::

    e = create_engine("mssql+pyodbc://u:p@dsn", supports_comments=False)

.. versionadded:: 2.0 Added support for table and column comments for
   the SQL Server dialect, including DDL generation and reflection.

.. _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

There are also more options for isolation level configurations, such as
"sub-engine" objects linked to a main :class:`_engine.Engine` which each apply
different isolation level settings.  See the discussion at
:ref:`dbapi_autocommit` for background.

.. seealso::

    :ref:`dbapi_autocommit`

.. _mssql_reset_on_return:

Temporary Table / Resource Reset for Connection Pooling
-------------------------------------------------------

The :class:`.QueuePool` connection pool implementation used
by the SQLAlchemy :class:`.Engine` object includes
:ref:`reset on return <pool_reset_on_return>` behavior that will invoke
the DBAPI ``.rollback()`` method when connections are returned to the pool.
While this rollback will clear out the immediate state used by the previous
transaction, it does not cover a wider range of session-level state, including
temporary tables as well as other server state such as prepared statement
handles and statement caches.   An undocumented SQL Server procedure known
as ``sp_reset_connection`` is known to be a workaround for this issue which
will reset most of the session state that builds up on a connection, including
temporary tables.

To install ``sp_reset_connection`` as the means of performing reset-on-return,
the :meth:`.PoolEvents.reset` event hook may be used, as demonstrated in the
example below. The :paramref:`_sa.create_engine.pool_reset_on_return` parameter
is set to ``None`` so that the custom scheme can replace the default behavior
completely.   The custom hook implementation calls ``.rollback()`` in any case,
as it's usually important that the DBAPI's own tracking of commit/rollback
will remain consistent with the state of the transaction::

    from sqlalchemy import create_engine
    from sqlalchemy import event

    mssql_engine = create_engine(
        "mssql+pyodbc://scott:tiger^5HHH@mssql2017:1433/test?driver=ODBC+Driver+17+for+SQL+Server",
        # disable default reset-on-return scheme
        pool_reset_on_return=None,
    )


    @event.listens_for(mssql_engine, "reset")
    def _reset_mssql(dbapi_connection, connection_record, reset_state):
        if not reset_state.terminate_only:
            dbapi_connection.execute("{call sys.sp_reset_connection}")

        # so that the DBAPI itself knows that the connection has been
        # reset
        dbapi_connection.rollback()

.. versionchanged:: 2.0.0b3  Added additional state arguments to
   the :meth:`.PoolEvents.reset` event and additionally ensured the event
   is invoked for all "reset" occurrences, so that it's appropriate
   as a place for custom "reset" handlers.   Previous schemes which
   use the :meth:`.PoolEvents.checkin` handler remain usable as well.

.. seealso::

    :ref:`pool_reset_on_return` - in the :ref:`pooling_toplevel` documentation

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

.. sourcecode:: sql

    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:

.. sourcecode:: sql

    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 <https://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.

.. _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 delimiters 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:

.. sourcecode:: pycon+sql

    >>> eng = create_engine("mssql+pymssql://mydsn", legacy_schema_aliasing=True)
    >>> print(account_table.select().compile(eng))
    {printsql}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.

.. deprecated:: 1.4

   The ``legacy_schema_aliasing`` flag is now
   deprecated and will be removed in a future release.

.. _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`.
For indexes this option can be combined with the ``mssql_columnstore`` one
to create a clustered columnstore index.

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:

.. sourcecode:: sql

  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:

.. sourcecode:: sql

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

Columnstore Index Support
-------------------------

The MSSQL dialect supports columnstore indexes via the ``mssql_columnstore``
option.  This option is available to :class:`.Index`. It be combined with
the ``mssql_clustered`` option to create a clustered columnstore index.

To generate a columnstore index::

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

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

To generate a clustered columnstore index provide no columns::

    idx = Index("my_index", mssql_clustered=True, mssql_columnstore=True)
    # required to associate the index with the table
    table.append_constraint(idx)

the above renders the index as
``CREATE CLUSTERED COLUMNSTORE INDEX my_index ON table``.

.. versionadded:: 2.0.18

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.

.. _mssql_triggers:

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}

.. _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.    Previous versions of SQLAlchemy therefore had
limitations for features such as the "ORM Versioning" feature that relies upon
accurate rowcounts in order to match version numbers with matched rows.

SQLAlchemy 2.0 now retrieves the "rowcount" manually for these particular use
cases based on counting the rows that arrived back within RETURNING; so while
the driver still has this limitation, the ORM Versioning feature is no longer
impacted by it. As of SQLAlchemy 2.0.5, ORM versioning has been fully
re-enabled for the pyodbc driver.

.. versionchanged:: 2.0.5  ORM versioning support is restored for the pyodbc
   driver.  Previously, a warning would be emitted during ORM flush that
   versioning was not supported.


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:

.. sourcecode:: sql

    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
https://msdn.microsoft.com/en-us/library/ms175095.aspx.

    )annotationsN)overload)TYPE_CHECKING)UUID   )information_schema)JSON)JSONIndexType)JSONPathType   )exc)Identity)schema)Sequence)sql)text)util)cursor)default)
reflection)ReflectionDefaults)	coercions)compiler)elements)
expression)func)quoted_name)roles)sqltypes)try_cast)is_sql_compiler)InsertmanyvaluesSentinelOpts)TryCast)BIGINT)BINARY)CHAR)DATE)DATETIME)DECIMAL)FLOAT)INTEGER)NCHAR)NUMERIC)NVARCHAR)SMALLINT)TEXT)VARCHARupdate_wrapper)Literal)DMLState)TableClause)   )   )   )   )
   )	   )   >   asbyifinisofonortoaddallandanyascendforkeynotoffsettopusebulkcasedbccdenydescdiskdropdumpelseexecexitfilefromfullgotointojoinkillleftlikeloadnullopenoverplanprocreadrulesavesomethentranuserviewwhenwithalterbeginbreakcheckclosecrossfetchgrantgroupindexinnermergeorderouterpivotprintrighttableunionwherewhilebackupbrowsecolumncommitcreater   deletedoubleerrlvlescapeexceptexistshavinginsertlinenonullifoptionpublicreturnrevertrevoker   selectuniqueupdatevaluesbetweencascadecollatecomputeconvertcurrentdeclarer   executeforeignnocheckoffsetsopenxmlpercentprimaryrestoresetusertriggertsequalunpivotvaryingwaitforcoalescecontainscontinuedatabasedistinctexternalfreetextfunctionholdlockidentitynationalreadtextrestrictrollbackrowcountshutdowntextsizetruncate	clustered	intersect	openquery	precision	procedure	raiserror	writetext
checkpoint
constraint
deallocate
fillfactor
openrowset
references
rowguidcol
statistics
updatetextdistributedidentitycolreconfigurereplicationsystem_usertablesampletransactioncurrent_datecurrent_timecurrent_usernonclusteredsession_userauthorizationcontainstablefreetexttablesecurityauditopendatasourceidentity_insertcurrent_timestampc                          e Zd ZdZ fddZ  ZS )REALzthe SQL Server REAL datatype.c                   "   | dd t jdi | d S )Nr       
setdefaultsuper__init__selfkw	__class__r   `/var/www/html/ecg_monitoring/venv/lib/python3.10/site-packages/sqlalchemy/dialects/mssql/base.pyr        zREAL.__init____name__
__module____qualname____doc__r   __classcell__r   r   r   r   r     s    r   c                      r   )DOUBLE_PRECISIONzMthe SQL Server DOUBLE PRECISION datatype.

    .. versionadded:: 2.0.11

    c                   r   )Nr   5   r   r   r   r   r   r   r     r   zDOUBLE_PRECISION.__init__r   r   r   r   r   r    s    r  c                   @     e Zd Zd ZdS )TINYINTNr   r   r  __visit_name__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                   X   t | tjr
|  S t | t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  str_regmatch
ValueErrorgroupsr  mr   r   r   r       
z)_MSDate.result_processor.<locals>.processr   r   r  coltyper  r   r1  r   result_processor     z_MSDate.result_processorN)r   r   r  r  recompiler+  r5  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   d S r  )r   r   r   )r   r   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timer*  r  r1  r   r   r    s   
	z$TIME.bind_processor.<locals>.processr   r  r   r1  r   r    r6  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'  5  r(  z:TIME.result_processor.<locals>.process.<locals>.<listcomp>)r)  r  r>  r*  r+  r,  r-  r.  r/  r1  r   r   r  ,  r2  z&TIME.result_processor.<locals>.processr   r3  r   r1  r   r5  +  r6  zTIME.result_processorr  )r   r   r  r   r  r  r=  r  r7  r8  r+  r5  r  r   r   r   r   r9    s    
r9  c                   @  r  )_BASETIMEIMPLNr  r   r   r   r   r?  ?  r
  r?  c                   @     e Zd Zdd ZdS )_DateTimeBasec                 C  r  )Nc                 S  r  r  r  r  r   r   r   r  E  r  z-_DateTimeBase.bind_processor.<locals>.processr   r  r   r   r   r  D  r  z_DateTimeBase.bind_processorN)r   r   r  r  r   r   r   r   rA  C      rA  c                   @     e Zd ZdS )_MSDateTimeNr   r   r  r   r   r   r   rD  N      rD  c                   @  r  )SMALLDATETIMENr  r   r   r   r   rG  R  r
  rG  c                      "   e Zd Zd Zd fdd	Z  ZS )	DATETIME2Nc                      t  jdi | || _d S Nr   r   r   r   r   r   r   r   r   r   r   Y     
zDATETIME2.__init__r  r   r   r  r	  r   r  r   r   r   r   rI  V      rI  c                      rH  )DATETIMEOFFSETNc                   rJ  rK  rL  rM  r   r   r   r   a  rN  zDATETIMEOFFSET.__init__r  rO  r   r   r   r   rQ  ^  rP  rQ  c                   @  r@  )_UnicodeLiteralc                   r;  )Nc                   s(   |  dd}  jjr|  dd} d|  S )N'''%z%%zN'%s')replaceidentifier_preparer_double_percentsr  r  r   r   r  h  s   z2_UnicodeLiteral.literal_processor.<locals>.processr   r  r   rY  r   literal_processorg  s   z!_UnicodeLiteral.literal_processorN)r   r   r  rZ  r   r   r   r   rR  f  rB  rR  c                   @  rC  )
_MSUnicodeNrE  r   r   r   r   r[  s  rF  r[  c                   @  rC  )_MSUnicodeTextNrE  r   r   r   r   r\  w  rF  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     s   
	zTIMESTAMP.__init__c                   s(   t  || | jr fdd}|S  S )Nc                   s*    r | } | d urt t| dd} | S )Nhex   )r#  codecsencoder  super_r   r   r    s
   z+TIMESTAMP.result_processor.<locals>.process)r   r5  r^  r3  r   rc  r   r5    s
   zTIMESTAMP.result_processorF)	r   r   r  r  r	  lengthr   r5  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   rh    s    rh  c                   @  rg  )NTEXTzMMSSQL NTEXT type, for variable-length unicode text up to 2^30
    characters.Nri  r   r   r   r   rj    s    rj  c                      s&   e Zd ZdZd Zd fdd	Z  ZS )	VARBINARYaL  The MSSQL VARBINARY type.

    This type adds additional features to the core :class:`_types.VARBINARY`
    type, including "deprecate_large_types" mode where
    either ``VARBINARY(max)`` or IMAGE is rendered, as well as the SQL
    Server ``FILESTREAM`` option.

    .. seealso::

        :ref:`mssql_large_type_deprecation`

    NFc                   s.   || _ | j r|dvrtdt j|d dS )a  
        Construct a VARBINARY type.

        :param length: optional, a length for the column for use in
          DDL statements, for those binary types that accept a length,
          such as the MySQL BLOB type.

        :param filestream=False: if True, renders the ``FILESTREAM`` keyword
          in the table definition. In this case ``length`` must be ``None``
          or ``'max'``.

          .. versionadded:: 1.4.31

        )Nmaxz4length must be None or 'max' when setting filestreamrf  N)
filestreamr-  r   r   )r   rf  rn  r   r   r   r     s   zVARBINARY.__init__)NF)r   r   r  r  r	  r   r  r   r   r   r   rk    s    rk  c                   @  r  )IMAGENr  r   r   r   r   ro    r
  ro  c                   @  rg  )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".

    Nri  r   r   r   r   rp    s    	rp  c                   @  rg  )BITzMSSQL BIT type.

    Both pyodbc and pymssql return values from BIT columns as
    Python <class 'bool'> so just subclass Boolean.

    Nri  r   r   r   r   rq    s    rq  c                   @  r  )MONEYNr  r   r   r   r   rr    r
  rr  c                   @  r  )
SMALLMONEYNr  r   r   r   r   rs    r
  rs  c                   @  s   e Zd Zdd Zdd ZdS )MSUUidc                 C  s(   | j rd S | jrdd }|S dd }|S )Nc                 S  s   | d ur| j } | S r  r_  r  r   r   r   r    s   z&MSUUid.bind_processor.<locals>.processc                 S  s    | d ur|  dd dd} | S )N- rT  rS  rV  r  r   r   r   r  '  s   native_uuidas_uuidr  r   r   r   r    s   zMSUUid.bind_processorc                 C  s0   | j r	dd }|S | jrdd }|S dd }|S )Nc                 S  s   dt | dd dS )NrS  rT  )r*  rV  r  r   r   r   r  1  s   z)MSUUid.literal_processor.<locals>.processc                 S  s   d| j  dS )NrS  ru  r  r   r   r   r  8  s   c                 S  s   d|  dd dd dS )NrS  rv  rw  rT  rx  r  r   r   r   r  >  s   ry  r  r   r   r   rZ  .  s   zMSUUid.literal_processorN)r   r   r  r  rZ  r   r   r   r   rt    s    rt  c                   @  s@   e Zd Zd Ze	ddddZe	ddd
dZddddZdS )UNIQUEIDENTIFIER.r   UNIQUEIDENTIFIER[_python_UUID]r{  Literal[True]c                 C     d S r  r   r   r{  r   r   r   r   I     zUNIQUEIDENTIFIER.__init__UNIQUEIDENTIFIER[str]Literal[False]c                 C  r  r  r   r  r   r   r   r   N  r  Tboolc                 C  s   || _ d| _dS )a  Construct a :class:`_mssql.UNIQUEIDENTIFIER` type.


        :param as_uuid=True: if True, values will be interpreted
         as Python uuid objects, converting to/from string via the
         DBAPI.

         .. versionchanged: 2.0 Added direct "uuid" support to the
            :class:`_mssql.UNIQUEIDENTIFIER` datatype; uuid interpretation
            defaults to ``True``.

        TN)r{  rz  r  r   r   r   r   S  s   
N).)r   r}  r{  r~  )r   r  r{  r  )T)r{  r  )r   r   r  r	  r   r   r   r   r   r   r|  F  s    r|  c                   @  r  )SQL_VARIANTNr  r   r   r   r   r  d  r
  r  r#  bigintsmallinttinyintvarcharnvarcharcharncharr   ntextdecimalnumericfloatr  	datetime2datetimeoffsetr  )r>  smalldatetimebinary	varbinarybitrealzdouble precisionimagexml	timestampmoney
smallmoneyuniqueidentifiersql_variantc                      s.  e Zd ZdHd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>d? Z!d@dA Z" fdBdCZ#dDdE Z$dFdG Z%  Z&S )I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  rf  rc   )r   spectype_rf  r  r   r   r   _extend  s   zMSTypeCompiler._extendc                 K     | j |fi |S r  )visit_DOUBLE_PRECISIONr   r  r   r   r   r   visit_double     zMSTypeCompiler.visit_doublec                 K  s$   t |dd }|d u rdS dd|i S )Nr   r)   zFLOAT(%(precision)s)r  r   r  r   r   r   r   r   visit_FLOAT  s   zMSTypeCompiler.visit_FLOATc                 K     dS )Nr  r   r  r   r   r   visit_TINYINT     zMSTypeCompiler.visit_TINYINTc                 K      t |dd }|d urd| S dS )Nr   zTIME(%s)r9  r  r  r   r   r   
visit_TIME     zMSTypeCompiler.visit_TIMEc                 K  r  )Nr]  r   r  r   r   r   visit_TIMESTAMP  r  zMSTypeCompiler.visit_TIMESTAMPc                 K  r  )Nrh  r   r  r   r   r   visit_ROWVERSION  r  zMSTypeCompiler.visit_ROWVERSIONc                 K  s*   |j r| j|fi |S | j|fi |S r  )timezonevisit_DATETIMEOFFSETvisit_DATETIMEr  r   r   r   visit_datetime  s   zMSTypeCompiler.visit_datetimec                 K  s"   t |dd }|d urd|j S dS )Nr   zDATETIMEOFFSET(%s)rQ  )r  r   r  r   r   r   r    s   
z#MSTypeCompiler.visit_DATETIMEOFFSETc                 K  r  )Nr   zDATETIME2(%s)rI  r  r  r   r   r   visit_DATETIME2  r  zMSTypeCompiler.visit_DATETIME2c                 K  r  )NrG  r   r  r   r   r   visit_SMALLDATETIME  r  z"MSTypeCompiler.visit_SMALLDATETIMEc                 K  r  r  )visit_NVARCHARr  r   r   r   visit_unicode  r  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_text     zMSTypeCompiler.visit_textc                 K  r  r  )r  r  r  visit_NTEXTr  r   r   r   visit_unicode_text  r  z!MSTypeCompiler.visit_unicode_textc                 K     |  d|S )Nrj  r  r  r   r   r   r       zMSTypeCompiler.visit_NTEXTc                 K  r  )Nr/   r  r  r   r   r   r    r  zMSTypeCompiler.visit_TEXTc                 K     | j d||jpddS )Nr0   rl  rm  r  rf  r  r   r   r   r       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-   rl  rm  r  r  r   r   r   r    r  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_VERSIONr  
visit_DATEr  r   r   r   
visit_date	     zMSTypeCompiler.visit_datec                 K  r  r  )
visit_timer  r   r   r   visit__BASETIMEIMPL  r  z"MSTypeCompiler.visit__BASETIMEIMPLc                 K  r  r  )r  r  r  r  r  r  r   r   r   r    r  zMSTypeCompiler.visit_timec                 K  r  r  )r  r  visit_VARBINARYvisit_IMAGEr  r   r   r   visit_large_binary  r  z!MSTypeCompiler.visit_large_binaryc                 K  r  )Nro  r   r  r   r   r   r    r  zMSTypeCompiler.visit_IMAGEc                 K  r  )Nrp  r   r  r   r   r   	visit_XML!  r  zMSTypeCompiler.visit_XMLc                 K  s.   | j d||jpdd}t|ddr|d7 }|S )Nrk  rl  rm  rn  Fz FILESTREAM)r  rf  r  )r   r  r   r   r   r   r   r  $  s   zMSTypeCompiler.visit_VARBINARYc                 K  s
   |  |S r  )	visit_BITr  r   r   r   visit_boolean*     
zMSTypeCompiler.visit_booleanc                 K  r  )Nrq  r   r  r   r   r   r  -  r  zMSTypeCompiler.visit_BITc                 K  s   | j d|ddS r  r  r  r   r   r   
visit_JSON0  s   zMSTypeCompiler.visit_JSONc                 K  r  )Nrr  r   r  r   r   r   visit_MONEY5  r  zMSTypeCompiler.visit_MONEYc                 K  r  )Nrs  r   r  r   r   r   visit_SMALLMONEY8  r  zMSTypeCompiler.visit_SMALLMONEYc                   s,   |j r| j|fi |S t j|fi |S r  )rz  visit_UNIQUEIDENTIFIERr   
visit_uuidr  r   r   r   r  ;  s   zMSTypeCompiler.visit_uuidc                 K  r  )Nr|  r   r  r   r   r   r  A  r  z%MSTypeCompiler.visit_UNIQUEIDENTIFIERc                 K  r  )Nr  r   r  r   r   r   visit_SQL_VARIANTD  r  z MSTypeCompiler.visit_SQL_VARIANTr  )'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   r   r    sH    
r  c                      sb   e Zd ZU dZdZdZded< dd Zdd Zd	d
 Z	dd Z
dd Zdd Z fddZ  ZS )MSExecutionContextFN	MSDialectr  c                 C  s*   | j r| j jr| j jj}||| j j}|S r  )compiledschema_translate_mappreparer_render_schema_translates)r   	statementrstr   r   r   _opt_encodeO  s   
zMSExecutionContext._opt_encodec              	   C  s   | j r|trt| jsJ t| jjtsJ t| jjjtsJ | jjj}|j	}|durJt|j
tsJd}| jj}|j| jd v pG|joG|j|jv | _nd}d| _| jj ob|ob| jj ob| j ob| j | _| jr~| j| j| d| j| d|  dS dS dS )z#Activate IDENTITY_INSERT if needed.NTr   FzSET IDENTITY_INSERT %s ONr   )isinsertr   r    r  r)  compile_stater4   	dml_tabler5   _autoincrement_columnr   r   dml_compile_staterM   compiled_parameters_dict_parameters_insert_col_keys_enable_identity_insertinlineeffective_returningexecutemany_select_lastrowidroot_connection_cursor_executer   r  rW  format_table)r   tbl	id_columninsert_has_identityr  r   r   r   pre_execV  sV   





#zMSExecutionContext.pre_execc              	   C  s$  | j }| js| js| jr| jj| _| jr>| jj	r"|
| jdd|  n	|
| jdd|  | j d }t|d | _tj| _n| jdurZt| jrZ| jjrZt| j| jj| j | _| jrtryt| jsfJ t| jjtsoJ t| jjjtsyJ |
| j| d| 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   NSET IDENTITY_INSERT %s OFF) r  r  isupdateisdeleter   r   	_rowcountr  r  use_scope_identityr  fetchallr#  
_lastrowid_cursor_NO_CURSOR_DMLcursor_fetch_strategyr  r    r   FullyBufferedCursorFetchStrategydescriptionr  r   r)  r  r4   r  r5   r  rW  r  )r   connrowr   r   r   	post_exec  s`   




zMSExecutionContext.post_execc                 C  s   | j S r  )r
  r1  r   r   r   get_lastrowid  s   z MSExecutionContext.get_lastrowidc                 C  sJ   | j r#z| j| d| j| jjj  W d S  t	y"   Y d S w d S )Nr  )
r  r   r   r  rW  r  r  r  r  	Exception)r   er   r   r   handle_dbapi_exception  s   
z)MSExecutionContext.handle_dbapi_exceptionc                 C  s   |  d| j| |S )NzSELECT NEXT VALUE FOR %s)_execute_scalarrW  format_sequence)r   seqr  r   r   r   fire_sequence  s   
z MSExecutionContext.fire_sequencec                   s>   t |tjr||jju rt |jtjr|jjrd S t 	|S r  )
r)  	sa_schemaColumnr   r  r   r   optionalr   get_insert_default)r   r   r   r   r   r    s   
z%MSExecutionContext.get_insert_default)r   r   r  r  r  r
  __annotations__r  r  r  r  r  r  r  r  r   r   r   r   r  H  s   
 19	r  c                      s  e Zd ZdZeejjdddddZ f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 fd!d"Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zede fd6d7	Z e fd8d9Z!edf fd;d<	Z"d=d> Z#d?d@ Z$dAdB Z%dCdD Z& fdEdFZ'dGdH Z(dIdJ Z) fdKdLZ*dMdN Z+dOdP Z,dQdR Z-dSdT Z.dUdV Z/dWdX Z0dYdZ Z1d[d\ Z2d]d^ Z3d_d` Z4dadb Z5dcdd Z6  Z7S )gMSSQLCompilerT	dayofyearweekdaymillisecondmicrosecond)doydowmillisecondsmicrosecondsc                   s   i | _ t j|i | d S r  )tablealiasesr   r   )r   argsr:  r   r   r   r     s   zMSSQLCompiler.__init__c                   s   d|d< t  j|fi |S )NTliteral_execute)r   _format_frame_clause)r   range_r   r   r   r   r,    s   z"MSSQLCompiler._format_frame_clausec                   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   r   r   )r   argr   rd  )r   fnr   r   decorate  s   z<MSSQLCompiler._with_legacy_schema_aliasing.<locals>.decorater   )r0  r1  r   r0  r   _with_legacy_schema_aliasing  s   z*MSSQLCompiler._with_legacy_schema_aliasingc                 K  r  )NCURRENT_TIMESTAMPr   r   r0  r   r   r   r   visit_now_func  r  zMSSQLCompiler.visit_now_funcc                 K  r  )Nz	GETDATE()r   r5  r   r   r   visit_current_date_func  r  z%MSSQLCompiler.visit_current_date_funcc                 K     d| j |fi | S NzLEN%sfunction_argspecr5  r   r   r   visit_length_func
  r  zMSSQLCompiler.visit_length_funcc                 K  r8  r9  r:  r5  r   r   r   visit_char_length_func  r  z$MSSQLCompiler.visit_char_length_funcc                 K  sN   |j j d j| fi |}d|d< |j j d j| fi |}d| d| dS )Nr   Tr+  r   zstring_agg(, ))clauses_compiler_dispatch)r   r0  r   expr	delimeterr   r   r   visit_aggregate_strings_func  s   z*MSSQLCompiler.visit_aggregate_strings_funcc                   s   d  fdd|D S )Nz + c                 3  s"    | ]}j |fi  V  qd S r  )r  r%  elemr   r   r   r   	<genexpr>  s     zFMSSQLCompiler.visit_concat_op_expression_clauselist.<locals>.<genexpr>rc   )r   
clauselistoperatorr   r   rG  r   %visit_concat_op_expression_clauselist  s   z3MSSQLCompiler.visit_concat_op_expression_clauselistc                 K  ,   d| j |jfi || j |jfi |f S )Nz%s + %sr  re   r   r   r  rK  r   r   r   r   visit_concat_op_binary     z$MSSQLCompiler.visit_concat_op_binaryc                 K  r  )N1r   r   rB  r   r   r   r   
visit_true!  r  zMSSQLCompiler.visit_truec                 K  r  )N0r   rS  r   r   r   visit_false$  r  zMSSQLCompiler.visit_falsec                 K  rM  )NzCONTAINS (%s, %s)rN  rO  r   r   r   visit_match_op_binary'  rQ  z#MSSQLCompiler.visit_match_op_binaryc                   s~   t  j|fi |}|jr=| |r=d|d< |d| j| |fi | 7 }|jdur=|jd r4|d7 }|jd r=|d7 }|S )	z+MS-SQL puts TOP, it's version of LIMIT hereTr+  zTOP %s Nr   zPERCENT 	with_tiesz
WITH TIES )r   get_select_precolumns_has_row_limiting_clause_use_topr  _get_limit_or_fetch_fetch_clause_fetch_clause_options)r   r   r   sr   r   r   rY  -  s   



z#MSSQLCompiler.get_select_precolumnsc                 C     |S r  r   r   r   r   r   r   r   get_from_hint_textB  r  z MSSQLCompiler.get_from_hint_textc                 C  r`  r  r   ra  r   r   r   get_crud_hint_textE  r  z MSSQLCompiler.get_crud_hint_textc                 C  s   |j d u r|jS |j S r  )r]  _limit_clauser   r   r   r   r   r\  H  s   
z!MSSQLCompiler._get_limit_or_fetchc                 C  s6   |j d u o||jp||jo|jd p|jd S )Nr   rX  )_offset_clause_simple_int_clauserd  r]  r^  re  r   r   r   r[  N  s   

zMSSQLCompiler._use_topc                 K  r  Nrw  r   )r   csr:  r   r   r   limit_clause]  r  zMSSQLCompiler.limit_clausec                 C  sB   |j js	td|jd ur|jd s|jd rtdd S d S )NzLMSSQL requires an order_by when using an OFFSET or a non-simple LIMIT clauser   rX  z^MSSQL needs TOP to use PERCENT and/or WITH TIES. Only simple fetch without offset can be used.)_order_by_clauser@  r   CompileErrorr^  re  r   r   r   _check_can_use_fetch_limit`  s   
z(MSSQLCompiler._check_can_use_fetch_limitc                 K  s>   | j jr| |s| | | j|f| |dd|S dS )zdMSSQL 2012 supports OFFSET/FETCH operators
        Use it instead subquery with row_number

        T)fetch_clauserequire_offsetrw  )r  _supports_offset_fetchr[  rm  rn  r\  r   r   r   r   r   r   _row_limit_clauses  s   
zMSSQLCompiler._row_limit_clausec                 K  s,   d| j |jfi || j |jfi |f S )NzTRY_CAST (%s AS %s))r  clause
typeclause)r   elementr   r   r   r   visit_try_cast  rQ  zMSSQLCompiler.visit_try_castc           	      K  s   |}|j rx| jjsx| |sxt|ddsx| | dd |jjD }| |}|j	}|
 }d|_|tj j|ddd }td}tjdd |jD  }|duro|||k}|durm|||| k}|S |||k}|S |S )	zLook for ``LIMIT`` and OFFSET in a select statement, and if
        so tries to wrap it in a subquery with ``row_number()`` criterion.
        MSSQL 2012 and above are excluded

        _mssql_visitNc                 S  s   g | ]}t |qS r   )sql_utilunwrap_label_referencerE  r   r   r   r'    s    z<MSSQLCompiler.translate_select_structure.<locals>.<listcomp>T)order_bymssql_rnc                 S  s   g | ]	}|j d kr|qS )r{  )rM   r  r   r   r   r'    s    )rZ  r  rp  r[  r  rm  rk  r@  r\  rf  	_generaterw  add_columnsr   r   
ROW_NUMBERrj   labelrz  aliasr   r   r  r   )	r   select_stmtr:  r   _order_by_clausesrj  offset_clauser{  limitselectr   r   r   translate_select_structure  sP   





z(MSSQLCompiler.translate_select_structureFc                   s\   ||u s|rt  j|fi |S | |}|d ur$| j|fd|i|S t  j|fi |S Nmssql_aliased)r   visit_table_schema_aliased_tabler  )r   r   r  iscrudr:  r  r   r   r   r    s   
zMSSQLCompiler.visit_tablec                   s   |j |d< t j|fi |S r  )ru  r   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
 j|fi |S t
 j|fd|i|S )Nadd_to_result_map)r   r  r  is_subqueryr  r   _corresponding_column_or_errornamerM   r  r   visit_column)r   r   r  r   t	convertedr   r   r   r    s2   
zMSSQLCompiler.visit_columnc                 C  s6   t |dd d ur|| jvr| | j|< | j| S d S )Nr   )r  r)  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  rB  )r   extractr   r  r   r   r   visit_extract  s   zMSSQLCompiler.visit_extractc                 K     d| j | S )NzSAVE TRANSACTION %sr  format_savepointr   savepoint_stmtr   r   r   r   visit_savepoint     zMSSQLCompiler.visit_savepointc                 K  r  )NzROLLBACK TRANSACTION %sr  r  r   r   r   visit_rollback_to_savepoint  r  z)MSSQLCompiler.visit_rollback_to_savepointc                   s^   t |jtjr%|jtjkr%t |jtjs%| jt|j|j|jfi |S t	 j
|fi |S )z]Move bind parameters to the right-hand side of an operator, where
        possible.

        )r)  re   r   BindParameterrK  eqr   r  BinaryExpressionr   visit_binary)r   r  r:  r   r   r   r  	  s   zMSSQLCompiler.visit_binaryc                  sx   j sjrjd}njrjd}nJ dt|  fddjdt	|dD }d	d

| S )NinserteddeletedFz+expected Insert, Update or Delete statementc              	     sD   g | ]\}}}}}j  |d |fif||||dqS )result_map_targets)fallback_label_namecolumn_is_repeatedr  
proxy_name)_label_returning_columntraverse)r%  r  r  r  r   repeatedadapterr   populate_result_mapr   stmtr   r   r'  -	  s*    	z2MSSQLCompiler.returning_clause.<locals>.<listcomp>T)colszOUTPUT r>  )	is_insert	is_updater   r  	is_deleterx  ClauseAdapter_generate_columns_plus_namesr   _select_iterablesrc   )r   r  returning_colsr  r   targetcolumnsr   r  r   returning_clause	  s   	


zMSSQLCompiler.returning_clausec                 C  r  )NWITHr   )r   	recursiver   r   r   get_cte_preambleF	  s   zMSSQLCompiler.get_cte_preamblec                   s&   t |tjr|d S t |||S r  )r)  r   Functionr  r   label_select_column)r   r   r   asfromr   r   r   r  M	  s   
z!MSSQLCompiler.label_select_columnc                 K  r  rh  r   rq  r   r   r   for_update_clauseS	  r  zMSSQLCompiler.for_update_clausec                 K  sL   |   r| |s|jd u s| jjsdS | j|jfi |}|r$d| S dS )Nrw  z
 ORDER BY )r  r[  _offsetr  rp  r  rk  )r   r   r   rz  r   r   r   order_by_clauseX	  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  	fromhintsNrA  r%  r  
from_hintsr   r   r   r   rH  {	  
    
z3MSSQLCompiler.update_from_clause.<locals>.<genexpr>rI  )r   update_stmt
from_tableextra_fromsr  r   r   r  r   update_from_clauseq	  s   

z MSSQLCompiler.update_from_clausec                 K  s&   d}|rd}|j | f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   r   delete_table_clause	  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   rH  	  r  z9MSSQLCompiler.delete_extra_from_clause.<locals>.<genexpr>rI  )r   r  r  r  r  r   r   r  r   delete_extra_from_clause	  s   
z&MSSQLCompiler.delete_extra_from_clausec                 K  r  )NzSELECT 1 WHERE 1!=1r   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)rN  rO  r   r   r   visit_is_distinct_from_binary	     

z+MSSQLCompiler.visit_is_distinct_from_binaryc                 K  r  )Nz&EXISTS (SELECT %s INTERSECT SELECT %s)rN  rO  r   r   r   !visit_is_not_distinct_from_binary	  r  z/MSSQLCompiler.visit_is_not_distinct_from_binaryc                 K  s  |j jtju rd| j|jfi || j|jfi |f S d| j|jfi || j|jfi |f }|j jtju rQd| j|jfi || j|jfi |f }nn|j jtju rd| j|jfi || j|jfi |t	|j tj
rtdn	d|j j|j jf f }n>|j jtju rd}n4|j jtju rd| j|jfi || j|jfi |f }nd	| j|jfi || j|jfi |f }|d
 | d S )NzJSON_QUERY(%s, %s)z+CASE JSON_VALUE(%s, %s) WHEN NULL THEN NULLz(ELSE CAST(JSON_VALUE(%s, %s) AS INTEGER)z#ELSE CAST(JSON_VALUE(%s, %s) AS %s)r)   zNUMERIC(%s, %s)z0WHEN 'true' THEN 1 WHEN 'false' THEN 0 ELSE NULLzELSE JSON_VALUE(%s, %s)zELSE JSON_QUERY(%s, %s)r  z END)r  _type_affinityr   r   r  re   r   IntegerNumericr)  Floatr   scaleBooleanString)r   r  rK  r   case_expressiontype_expressionr   r   r    _render_json_extract_from_binary	  sJ   
z.MSSQLCompiler._render_json_extract_from_binaryc                 K     | j ||fi |S r  r  rO  r   r   r   visit_json_getitem_op_binary	     z*MSSQLCompiler.visit_json_getitem_op_binaryc                 K  r  r  r  rO  r   r   r   !visit_json_path_getitem_op_binary	  r  z/MSSQLCompiler.visit_json_path_getitem_op_binaryc                 K  r  )NzNEXT VALUE FOR %s)r  r  )r   r  r   r   r   r   visit_sequence	  s   zMSSQLCompiler.visit_sequence)FFr  )8r   r   r  returning_precedes_valuesr   update_copyr   SQLCompilerr  r   r,  r3  r6  r7  r<  r=  rD  rL  rP  rT  rV  rW  rY  rb  rc  r\  r[  rj  rm  rr  rv  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     sv    

43	8r   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 )NTr+  z%s IN %srN  rO  r   r   r   visit_in_op_binary	  
   z&MSSQLStrictCompiler.visit_in_op_binaryc                 K  r  )NTr+  z%s NOT IN %srN  rO  r   r   r   visit_not_in_op_binary	  r  z*MSSQLStrictCompiler.visit_not_in_op_binaryc                   s.   t t|tjrdt| d S 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.
        rS  )
issubclassr  r  r  r*  r   render_literal_value)r   r  r  r   r   r   r   
  s   z(MSSQLStrictCompiler.render_literal_value)	r   r   r  r  ansi_bind_rulesr  r  r  r  r   r   r   r   r  	  s    r  c                      sv   e Zd Zd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 fddZdd Z  ZS )MSDDLCompilerc                 K  sz  | j |}|jd ur|d| |j 7 }n|d| jjj|j|d 7 }|jd urL|jr>|js>t	|j
tjs>|jdu s>|jrC|d7 }n	|jd u rL|d7 }|jd u rVtd|jd }|d }|d	 }|d usk|d ury|jrstd
tdd |jr|| j|jfi |7 }|S ||jju s|jdu rt	|j
tr|j
jr|| t||d7 }|S | |}|d ur|d| 7 }|S )Nr  )r  Tz	 NOT NULLz NULLz;mssql requires Table-bound columns in order to generate DDLmssqlidentity_startidentity_incrementzzCannot specify options 'mssql_identity_start' and/or 'mssql_identity_increment' while also using the 'Identity' construct.z|The dialect options 'mssql_identity_start' and 'mssql_identity_increment' are deprecated. Use the 'Identity' object instead.1.4start	incrementz	 DEFAULT )r  format_columncomputedr  r  type_compiler_instancer  nullableprimary_keyr)  r   r  r   autoincrementr   r   r   rl  dialect_optionsr   warn_deprecatedr  r  r   get_column_default_string)r   r   r:  colspecd_optr  r  r   r   r   r   get_column_specification
  sd   










z&MSDDLCompiler.get_column_specificationFc           
        sP  |j    jd} jr|d7 } jd d }|d ur*|r&|d7 }n|d7 } jd d }|r7|d7 }|d	j |d
 jf 7 }t j	dkr`|dd
fdd j	D  7 } jd d r fdd jd d D }|dd
fdd|D  7 } jd d }|d urttj|}jj|ddd}	|d|	 7 }|S )NzCREATE zUNIQUE r  r   
CLUSTERED NONCLUSTERED columnstorezCOLUMNSTORE zINDEX %s ON %sinclude_schemar   z (%s)r>  c                 3  s"    | ]} j j|d ddV  qdS )FTinclude_tableliteral_bindsN)sql_compilerr  )r%  rB  r1  r   r   rH  o
  s    
z3MSDDLCompiler.visit_create_index.<locals>.<genexpr>includec                   s&   g | ]}t |tr jj| n|qS r   )r)  r*  r   r  )r%  col)r   r   r   r'  x
  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 )ru  _verify_index_tabler  r   r  _prepared_index_namer  r   lenexpressionsrc   r   expectr   DDLExpressionRoler  r  )
r   r   r  r   r   r   r  
inclusionswhereclausewhere_compiledr   )r   r  r   r   visit_create_indexS
  sN   



z MSDDLCompiler.visit_create_indexc                 K  s$   d| j |jdd| j|jjf S )Nz
DROP INDEX %s ON %sFr  )r  ru  r  r  r   )r   rY   r   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   rw  CONSTRAINT %s zPRIMARY KEY r  r   r  r  r  r>  c                 3      | ]
} j |jV  qd S r  r  r  r  r  r1  r   r   rH  
      
z=MSDDLCompiler.visit_primary_key_constraint.<locals>.<genexpr>)r  r  r  format_constraintr  rc   define_constraint_deferrability)r   r   r   r   r   r   r1  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 j|fi | 7 }|jd d }|d urB|r>|d7 }n|d7 }|d	d
 fdd|D  7 }| |7 }|S )Nr   rw  r"  z	UNIQUE %sr  r   r  r  r  r>  c                 3  r#  r  r$  r  r1  r   r   rH  
  r%  z8MSDDLCompiler.visit_unique_constraint.<locals>.<genexpr>)r  r  r  r&  !define_unique_constraint_distinctr  rc   r'  )r   r   r   r   formatted_namer   r   r1  r   visit_unique_constraint
  s,   


z%MSDDLCompiler.visit_unique_constraintc                 K  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   r   visit_computed_column
  s   
z#MSDDLCompiler.visit_computed_columnc                 K  sT   | j |j}|r|n| jj}d| j|jjt	
 | j || j j|jddS )NzNexecute sp_addextendedproperty 'MS_Description', {}, 'schema', {}, 'table', {}F
use_schema)r  schema_for_objectru  r  default_schema_nameformatr  r  commentr   r-   quote_schemar  r   r   r   r   schema_namer   r   r   visit_set_table_comment
  s   
z%MSDDLCompiler.visit_set_table_commentc                 K  s@   | j |j}|r|n| jj}d| j || j j|jddS )NzKexecute sp_dropextendedproperty 'MS_Description', 'schema', {}, 'table', {}Fr0  )r  r2  ru  r  r3  r4  r6  r  r   rY   r   r   r8  r   r   r   visit_drop_table_comment
  s   
z&MSDDLCompiler.visit_drop_table_commentc                 K  sd   | j |jj}|r|n| jj}d| j|jj	t
 | j || j j|jjdd| j |jS )Nz\execute sp_addextendedproperty 'MS_Description', {}, 'schema', {}, 'table', {}, 'column', {}Fr0  )r  r2  ru  r   r  r3  r4  r  r  r5  r   r-   r6  r  r  r7  r   r   r   visit_set_column_comment
  s   
z&MSDDLCompiler.visit_set_column_commentc                 K  sP   | j |jj}|r|n| jj}d| j || j j|jjdd| j 	|jS )NzYexecute sp_dropextendedproperty 'MS_Description', 'schema', {}, 'table', {}, 'column', {}Fr0  )
r  r2  ru  r   r  r3  r4  r6  r  r  r:  r   r   r   visit_drop_column_comment
  s   
z'MSDDLCompiler.visit_drop_column_commentc                   s@   d }|j jd ur|j j}d| j| }t j|fd|i|S )Nz AS %sprefix)ru  	data_typetype_compilerr  r   visit_create_sequence)r   r   r   r>  r?  r   r   r   rA    s
   z#MSDDLCompiler.visit_create_sequencec                 K  sT   d}|j d us|jd ur(|j d u rdn|j }|jd u rdn|j}|d||f 7 }|S )Nz	 IDENTITYr   z(%s,%s)r  )r   r   r   r   r  r  r   r   r   visit_identity_column  s   z#MSDDLCompiler.visit_identity_columnre  )r   r   r  r
  r   r!  r(  r+  r/  r9  r;  r<  r=  rA  rB  r  r   r   r   r   r  
  s    
?<	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  j|dddd d S )N[]F)initial_quotefinal_quotequote_case_sensitive_collations)r   r   )r   r  r   r   r   r     s   
zMSIdentifierPreparer.__init__c                 C     | ddS )NrE  ]]rx  r   r  r   r   r   _escape_identifier   r  z'MSIdentifierPreparer._escape_identifierc                 C  rI  )NrJ  rE  rx  rK  r   r   r   _unescape_identifier#  r  z)MSIdentifierPreparer._unescape_identifierNc                 C  s\   |durt jdd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().z1.3)versionz%s.%srw  )r   r  _schema_elementsr  )r   r   forcedbnameownerresultr   r   r   r6  &  s   	
z!MSIdentifierPreparer.quote_schemar  )
r   r   r  RESERVED_WORDSreserved_wordsr   rL  rM  r6  r  r   r   r   r   rC    s    rC  c                      d fdd	}t | S )Nc              	     s,   t | |\}}t|| | ||||fi |S r  _owner_plus_db
_switch_db)r  
connectionr   r   rQ  rR  r2  r   r   wrapB  s   	z$_db_plus_owner_listing.<locals>.wrapr  r1   r0  r[  r   r2  r   _db_plus_owner_listingA  s   
r]  c                   rV  )Nc              
     s.   t | |\}}t|| | |||||f	i |S r  rW  )r  rZ  	tablenamer   r   rQ  rR  r2  r   r   r[  T  s   
z_db_plus_owner.<locals>.wrapr  r1   r\  r   r2  r   _db_plus_ownerS  s   
r_  c                 O  s   | r| d }|| kr| d|jj|   z||i |W | r4|| kr5| d|jj|  S S S | rI|| krJ| d|jj|  w w w )Nzselect db_name()zuse %s)exec_driver_sqlscalarr  rW  r  )rQ  rZ  r0  r/  r   
current_dbr   r   r   rY  f  s*   rY  c                 C  s   |sd | j fS t|S r  )r3  rO  )r  r   r   r   r   rX  w  s   
rX  c                 C  s\  t | tr| jrd | fS | tv rt|  S | drd | fS g }d}d}d}td| D ]3}|s0q+|dkr9d}d}q+|dkr@d}q+|sZ|dkrZ|rP|d	|  n|| d}d}q+||7 }q+|rf|| 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 )Nz
__[SCHEMA_rw  Fz
(\[|\]|\.)rD  TrE  .z[%s]r   r   z
.*\].*\[.*r  )NN)r)  r   r  _memoized_schema
startswithr7  splitappendr  rc   r,  lstriprstrip)r   pushsymbolbrackethas_bracketstokenrQ  rR  r   r   r   rO    sJ   
	


rO  c                      s  e Zd ZdZdZdZdZdZdZdZ	dZ
	 eZdZdZdZdZdZdZdZdZejeejeejeejjeejjeejeeje ej!e"e#e#e$e$e%e%e&e&ej'e(iZ)e*j+j,-de.j/iZ,e0Z0dZ1dZ2dZ3dZ4dZ5dZ6dZ7dZ8dZ9dZ:e;j<e;j=B e;j>B Z?dZ@dZAdZBdZCd	ZDeEZFeGZHeIZJeKZLeMjNd
difeMjOd
difeMjPdddddfeMjQdddfgZR									dG fdd	ZS fddZTdd ZU fddZVh dZWdd ZXdd ZYdd ZZ fddZ[dd  Z\d!d" Z]d#d$ Z^d%d& Z_e`d'd( Zaebjce`d)d* Zdebjceed+d, Zfebjcd-d. Zgebjceed/d0 Zhebjceed1d2 Ziebjcd3d4 Zjd5d6 Zkebjce`d7d8 Zlebjce`d9d: ZmebjcdHd;d<Znd=d> Zod?d@ Zpebjce`dAdB Zqebjce`dCdD Zrebjce`dEdF Zs  ZtS )Ir  r  TF   dbor.  r   i3  r   r   N)r   r  r   r  )r  r  c
                   sz   t |pd| _|| _|| _|| _|	| _| | _}|d ur|| _|d ur,t	dd || _
t jdi |
 || _|| _d S )Nr   z[The legacy_schema_aliasing parameter is deprecated and will be removed in a future release.r  r   )r#  query_timeoutr8  r  r  !ignore_no_transaction_on_rollback_user_defined_supports_commentssupports_commentsr   r  r.  r   r   _json_serializer_json_deserializer)r   rs  r  r8  r  rv  json_serializerjson_deserializerr.  rt  optsudsr   r   r   r   /  s$   

zMSDialect.__init__c                   s   | d t || d S )Nz$IF @@TRANCOUNT = 0 BEGIN TRANSACTION)r`  r   do_savepointr   rZ  r  r   r   r   r}  U  s   
zMSDialect.do_savepointc                 C  r  r  r   r~  r   r   r   do_release_savepointZ  s   zMSDialect.do_release_savepointc              
     sb   z	t  | W d S  | jjy0 } z| jr$tdt|r$t	d n W Y d }~d S d }~ww )Nz.*\b111214\bz|ProgrammingError 111214 'No corresponding transaction found.' has been suppressed via ignore_no_transaction_on_rollback=True)
r   do_rollbackdbapiProgrammingErrorrt  r7  r,  r*  r   warn)r   dbapi_connectionr  r   r   r   r  ^  s   
zMSDialect.do_rollback>   READ COMMITTEDREPEATABLE READREAD UNCOMMITTEDSNAPSHOTSERIALIZABLEc                 C  s
   t | jS r  )list_isolation_lookup)r   r  r   r   r   get_isolation_level_valuesv  r  z$MSDialect.get_isolation_level_valuesc                 C  s8   |  }|d|  |  |dkr|  d S d S )Nz SET TRANSACTION ISOLATION LEVEL r  )r   r   r{   r   )r   r  levelr   r   r   r   set_isolation_levely  s   zMSDialect.set_isolation_levelc              
   C  s   |  }d}zJz#|d| | }|stdd|d  }|d| W n | jjyA } z	td|||d }~ww | }|d  W |  S |  w )Nzsys.system_viewszTSELECT name FROM {} WHERE name IN ('dm_exec_sessions', 'dm_pdw_nodes_exec_sessions')zBCan't fetch isolation level on this particular SQL Server version.zsys.r   a  
                    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 {}
                    where session_id = @@SPID
                zZCan't fetch isolation level;  encountered error {} when attempting to query the "{}" view.)	r   r   r4  fetchoneNotImplementedErrorr  Errorupperr{   )r   r  r   	view_namer  errr   r   r   get_isolation_level  s>   zMSDialect.get_isolation_levelc                   s,   t  | |   | | | | d S r  )r   
initialize_setup_version_attributes_setup_supports_nvarchar_max_setup_supports_commentsr   rZ  r   r   r   r    s   
zMSDialect.initializec                 C  s   | j d ttddvrtdddd | j D   | j tkr%d| _nd	| _| jd u r3| j t	k| _| j o<| j d d
k| _
d S )Nr   r<      z[Unrecognized server version info '%s'.  Some SQL Server features may not function properly.rc  c                 s  s    | ]}t |V  qd S r  )r*  r$  r   r   r   rH    s    z6MSDialect._setup_version_attributes.<locals>.<genexpr>TFr9   )r  r  ranger   r  rc   r  supports_multivalues_insertr  MS_2012_VERSIONrp  r1  r   r   r   r    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)ra  r   r   r   
DBAPIError_supports_nvarchar_maxr  r   r   r   r    s   
z&MSDialect._setup_supports_nvarchar_maxc                 C  sJ   | j d urd S z
|td W n tjy   d| _Y d S w d| _d S )NzdSELECT 1 FROM fn_listextendedproperty(default, default, default, default, default, default, default)FT)ru  ra  r   r   r   r  rv  r  r   r   r   r    s   

z"MSDialect._setup_supports_commentsc                 C  s.   t d}||}|d urt|ddS | jS )NzSELECT schema_name()Tre  )r   r   ra  r   r8  )r   rZ  queryr3  r   r   r   _get_default_schema_name  s
   

z"MSDialect._get_default_schema_namec                 K  s    |  | | j|||fi |S r  )_ensure_has_table_connection_internal_has_table)r   rZ  r^  rQ  rR  r   r   r   r   r   	has_table  s   
zMSDialect.has_tablec           
      K  sN   t j}t|jj|jj|k}|r||jj|k}||}	|		 d uS r  )
ischema	sequencesr   r   r  sequence_namer   sequence_schemar   first)
r   rZ  sequencenamerQ  rR  r   r   r  r_  r  r   r   r   has_sequence  s   

zMSDialect.has_sequencec           	      K  sB   t j}t|jj}|r||jj|k}||}dd |D S )Nc                 S     g | ]}|d  qS r!  r   )r%  r  r   r   r   r'        z0MSDialect.get_sequence_names.<locals>.<listcomp>)	r  r  r   r   r  r  r   r  r   )	r   rZ  rQ  rR  r   r   r  r_  r  r   r   r   get_sequence_names  s   
zMSDialect.get_sequence_namesc                 K  s4   t tjjjtjjj}dd ||D }|S )Nc                 S  r  r!  r   r%  rr   r   r   r'    r  z.MSDialect.get_schema_names.<locals>.<listcomp>)r   r   r  schematar  r8  rz  r   )r   rZ  r   r_  schema_namesr   r   r   get_schema_names  s
   zMSDialect.get_schema_namesc           	      K  T   t j}t|jjt|jj|k|jj	dk
|jj}dd ||D }|S )N
BASE TABLEc                 S  r  r!  r   r  r   r   r   r'  *  r  z-MSDialect.get_table_names.<locals>.<listcomp>r  tablesr   r   r  
table_namer   and_table_schema
table_typerz  r   )	r   rZ  rQ  rR  r   r   r  r_  table_namesr   r   r   get_table_names     



zMSDialect.get_table_namesc           	      K  r  )NVIEWc                 S  r  r!  r   r  r   r   r   r'  ;  r  z,MSDialect.get_view_names.<locals>.<listcomp>r  )	r   rZ  rQ  rR  r   r   r  r_  
view_namesr   r   r   get_view_names-  r  zMSDialect.get_view_namesc              	   K  s   | drt|tddd| diS tj}t|jj	
tt|jjdk|jjdk|jj	|k}|rA|
|jj|k}||}| d uS )N#z"SELECT object_id(:table_name, 'U')r  ztempdb.dbo.[rE  r  r  )rg  r  ra  r   r  r  r   r   r  r  r   r  or_r  r  r   r  )r   rZ  r^  rR  r   r  r_  r  r   r   r   r  >  s*   





zMSDialect._internal_has_tablec                 K  s0   | j |||fi |r| S t| d| )Nrc  )r  r   NoSuchTableError)r   rZ  r^  rR  methodr   r   r   r   _default_or_error^  s   zMSDialect._default_or_errorc                 K  s  | j tkrdnd}|jddtd| dtd|t	 td|t	 j
t d	}i }	| D ]B}
|
d
 |
d dkg g i d |	|
d < }|d }|
d }|dv r_|dk|d< |dv rm|dk|d< d|d< |
d d ury|
d |d< q7|jddtdtd|t	 td|t	 j
t d	}| D ]:}
|
d |	vrq|	|
d  }|d d}|d d}|r|s|
d r|s|d |
d
  q|d |
d
  q|	 D ]
}|d |d d< q|	rt|	 S | j|||tjfi |S )Nzind.filter_definitionzNULL as filter_definitionTfuture_resultzM
select
    ind.index_id,
    ind.is_unique,
    ind.name,
    ind.type,
    a+  
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 != 0
order by
    ind.name
                tabnameschname)r  r  	is_uniquer   )r  r   column_namesinclude_columnsr  index_idr  r  >   r      mssql_clustered>         r  mssql_columnstorefilter_definitionmssql_wherea  
select
    ind_col.index_id,
    col.name,
    ind_col.is_included_column
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 = :schname
            is_included_columnr  r  mssql_include)r  r  execution_optionsr   r   r   
bindparams	bindparamr  CoerceUnicoder  r   Unicodemappingsr  ri  r   r  r  r   indexes)r   rZ  r^  rQ  rR  r   r   r  rpr  r  r   do
index_type	index_defis_colstoreis_clustered
index_infor   r   r   get_indexese  s   


zMSDialect.get_indexesc                 K  sT   | tdtd|t td|t  }|r |S t	| d| )Nzselect mod.definition from sys.sql_modules as mod join sys.views as views on mod.object_id = views.object_id join sys.schemas as sch on views.schema_id = sch.schema_id where views.name=:viewname and sch.name=:schnameviewnamer  rc  )
r   r   r   r  r  r  r  ra  r   r  )r   rZ  r  rQ  rR  r   r   view_defr   r   r   get_view_definition  s   zMSDialect.get_view_definitionc                 K  s~   | j std|r|n| j}d}|t|td|t	 td|t	 
 }|r2d|iS | j||d tjfi |S )Nz=Can't get table comments on current SQL Server version in usez
            SELECT cast(com.value as nvarchar(max))
            FROM fn_listextendedproperty('MS_Description',
                'schema', :schema, 'table', :table, NULL, NULL
            ) as com;
        r   r   r   )rv  r  r3  r   r   r   r  r  r  r  ra  r  r   table_comment)r   rZ  r  r   r   r8  COMMENT_SQLr5  r   r   r   get_table_comment  s0   
zMSDialect.get_table_commentc                 C  s   || ds	d S d S )Nz##z
[_][_][_]%rw  )rg  )r   r^  r   r   r   _temp_table_name_like_pattern  s
   z'MSDialect._temp_table_name_like_patternc              
   C  sv   z| tdd| |i W S  tjy& } ztd| |d }~w tjy: } zt	d| |d }~ww )Nz_select table_schema, table_name from tempdb.information_schema.tables where table_name like :p1p1zFound more than one temporary table named '%s' in tempdb at this time. Cannot reliably resolve that name to its internal table name.z6Unable to find a temporary table named '%s' in tempdb.)
r   r   r   r  oner   MultipleResultsFoundUnreflectableTableErrorNoResultFoundr  )r   rZ  r^  mener   r   r   _get_internal_temp_table_name  s8   z'MSDialect._get_internal_temp_table_namec           &      K  s*  | d}|r| ||\}}tj}ntj}tj}	tj}
|r7t|j	j
|k|j	j|k}|j	jd |j	j
 }n
|j	j
|k}|j	j
}| jrI|	j	j}n
t|	j	jtd}t|}t|j	j|j	j|j	j|j	j|j	j|j	j|j	j|j	j||	j	j|
j	j|
j	j|
j	jtjj	j !d"|j#|	t|	j	j|k|	j	j$|j	j%dkdj#|
t|
j	j|k|
j	j$|j	j%dkdj#tjttjj	d dktjj	j&|ktjj	j'|j	j(ktjj	j$d	kd)|*|j	j(}|j+d
d,|}g }|- D ]}||j	j }||j	j }||j	j dk}||j	j }||j	j }||j	j }||j	j }||j	j }|| }||	j	j }||
j	j }||
j	j }||
j	j }|tjj	j  } | j./|d }!i }"|!t0t1t2t3t4t5t6t7t8j9f	v rs|dkrhd }||"d< |rs||"d< |!d u rt:;d||f  t8j<}!nt=|!t8j>r||"d< t=|!t8j?s||"d< |!di |"}!||!|||d u| d}#|d ur|d ur||d|#d< |d ur|d u s|d u ri |#d< n+t@|!t8jArtB|}$tB|}%nt@|!t8jCrtB|}$tB|}%n|}$|}%|$|%d|#d< |D|# q|r|S | jE|||tFjfi |S )Nr  rc  i  r5  DATABASE_DEFAULT)onclauseclassr   MS_DescriptionTr  YESrd  rf  r  z*Did not recognize type '%s' of column '%s'r   r  )r  r  r  r   r  r5  )r,  r-  r   r   r  r   )Grg  r  r  mssql_temp_table_columnsr  computed_columnsidentity_columnsr   r  r  r  r  r  
definitioncastr-   r   	object_idr   column_namer?  is_nullablecharacter_maximum_lengthnumeric_precisionnumeric_scalecolumn_defaultcollation_nameis_persistedis_identity
seed_valueincrement_valueextended_propertiesr  r  select_from	outerjoinr  r   major_idminor_idordinal_positionr   rz  r  r   r  ischema_namesr  MSStringMSChar
MSNVarcharMSNCharMSTextMSNTextMSBinaryMSVarBinaryr   LargeBinaryr   r  NULLTYPEr  r  r  r)  
BigIntegerr#  r  ri  r  r   )&r   rZ  r^  rQ  rR  r   r   is_temp_tabler  computed_colsidentity_colsr  	full_namecomputed_definitionr  r_  r  r  r  r  r  r  charlennumericprecnumericscaler   r  r  r	  r
  r  r  r5  r4  r:  cdictr  r  r   r   r   get_columns0  s0  






!+
0

	






zMSDialect.get_columnsc                 K  s<  g }t j}t jd}	t|	jj|jj|	jj	t
t
|	jjd |	jj	 ddt|jj	|	jj	k|jj|	jjk|	jj|k|	jj|k|jj	|	jj}
|jdd|
}d }d }| D ]%}d||jjj v r||d  |d u r~||	jj	j }|d u r|d }qa|r||d	|id
S | j|||tjfi |S )NCrc  CnstIsClustKeyr  Tr  PRIMARYCOLUMN_NAMEr  )constrained_columnsr  r  )r  constraintskey_constraintsr  r   r   r  r  constraint_typeconstraint_namer   objectpropertyr  r  r  r   r  r  rz  r  r  r   r  r  ri  r  r   pk_constraint)r   rZ  r^  rQ  rR  r   r   pkeysTCr)  r_  r  r1  r  r  r   r   r   get_pk_constraint  sb   

zMSDialect.get_pk_constraintc                 K  sd  t dtd|t td|t jt t t t t t t t d}g }dd }	t	
|	}|| D ]Y}
|
\
}}}}}}}}}}|| }||d< |dkrc||d	 d
< |dkrm||d	 d< |d s||d< |d us}||kr|r|d | }||d< |d |d }}|| || qC|rt| S | j|||tjfi |S )Na>  WITH fk_info AS (
    SELECT
        ischema_ref_con.constraint_schema,
        ischema_ref_con.constraint_name,
        ischema_key_col.ordinal_position,
        ischema_key_col.table_schema,
        ischema_key_col.table_name,
        ischema_ref_con.unique_constraint_schema,
        ischema_ref_con.unique_constraint_name,
        ischema_ref_con.match_option,
        ischema_ref_con.update_rule,
        ischema_ref_con.delete_rule,
        ischema_key_col.column_name AS constrained_column
    FROM
        INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS ischema_ref_con
        INNER JOIN
        INFORMATION_SCHEMA.KEY_COLUMN_USAGE ischema_key_col ON
            ischema_key_col.table_schema = ischema_ref_con.constraint_schema
            AND ischema_key_col.constraint_name =
            ischema_ref_con.constraint_name
    WHERE ischema_key_col.table_name = :tablename
        AND ischema_key_col.table_schema = :owner
),
constraint_info AS (
    SELECT
        ischema_key_col.constraint_schema,
        ischema_key_col.constraint_name,
        ischema_key_col.ordinal_position,
        ischema_key_col.table_schema,
        ischema_key_col.table_name,
        ischema_key_col.column_name
    FROM
        INFORMATION_SCHEMA.KEY_COLUMN_USAGE ischema_key_col
),
index_info AS (
    SELECT
        sys.schemas.name AS index_schema,
        sys.indexes.name AS index_name,
        sys.index_columns.key_ordinal AS ordinal_position,
        sys.schemas.name AS table_schema,
        sys.objects.name AS table_name,
        sys.columns.name AS column_name
    FROM
        sys.indexes
        INNER JOIN
        sys.objects ON
            sys.objects.object_id = sys.indexes.object_id
        INNER JOIN
        sys.schemas ON
            sys.schemas.schema_id = sys.objects.schema_id
        INNER JOIN
        sys.index_columns ON
            sys.index_columns.object_id = sys.objects.object_id
            AND sys.index_columns.index_id = sys.indexes.index_id
        INNER JOIN
        sys.columns ON
            sys.columns.object_id = sys.indexes.object_id
            AND sys.columns.column_id = sys.index_columns.column_id
)
    SELECT
        fk_info.constraint_schema,
        fk_info.constraint_name,
        fk_info.ordinal_position,
        fk_info.constrained_column,
        constraint_info.table_schema AS referred_table_schema,
        constraint_info.table_name AS referred_table_name,
        constraint_info.column_name AS referred_column,
        fk_info.match_option,
        fk_info.update_rule,
        fk_info.delete_rule
    FROM
        fk_info INNER JOIN constraint_info ON
            constraint_info.constraint_schema =
                fk_info.unique_constraint_schema
            AND constraint_info.constraint_name =
                fk_info.unique_constraint_name
            AND constraint_info.ordinal_position = fk_info.ordinal_position
    UNION
    SELECT
        fk_info.constraint_schema,
        fk_info.constraint_name,
        fk_info.ordinal_position,
        fk_info.constrained_column,
        index_info.table_schema AS referred_table_schema,
        index_info.table_name AS referred_table_name,
        index_info.column_name AS referred_column,
        fk_info.match_option,
        fk_info.update_rule,
        fk_info.delete_rule
    FROM
        fk_info INNER JOIN index_info ON
            index_info.index_schema = fk_info.unique_constraint_schema
            AND index_info.index_name = fk_info.unique_constraint_name
            AND index_info.ordinal_position = fk_info.ordinal_position

    ORDER BY fk_info.constraint_schema, fk_info.constraint_name,
        fk_info.ordinal_position
r^  rR  )constraint_schemar1  r  r  constrained_columnreferred_table_schemareferred_table_namereferred_columnc                   S  s   d g d d g i dS )N)r  r-  referred_schemareferred_tablereferred_columnsoptionsr   r   r   r   r   fkey_rec  s   z,MSDialect.get_foreign_keys.<locals>.fkey_recr  z	NO ACTIONr?  onupdateondeleter=  rc  r<  r-  r>  )r   r  r   r  r  r  r  r   r  r   defaultdictr   rG   ri  r  r   r  r   foreign_keys)r   rZ  r^  rQ  rR  r   r   r_  fkeysr@  r  _rfknmscolrschemartblrcolfkuprule	fkdelrulerec
local_colsremote_colsr   r   r   get_foreign_keys  sz   ew


zMSDialect.get_foreign_keys)	NTrr  NNNNNFr  )ur   r   r  r  supports_statement_cachesupports_default_valuessupports_empty_insertfavor_returning_over_lastrowidreturns_native_bytesrv  supports_default_metavaluer  execution_ctx_clsr  max_identifier_lengthr8  insert_returningupdate_returningdelete_returningupdate_returning_multifromdelete_returning_multifromr   DateTimerD  Dater  r   r	   r
   Timer?  r  r[  UnicodeTextr\  rQ  rI  rG  r'   Uuidrt  colspecsr   DefaultDialectengine_config_typesr   r   asboolr  supports_sequencessequences_optionaldefault_sequence_basesupports_native_boolean#non_native_boolean_check_constraintsupports_unicode_bindspostfetch_lastrowidr  use_insertmanyvalues!use_insertmanyvalues_wo_returningr!   AUTOINCREMENTIDENTITYUSE_INSERT_FROM_SELECT"insertmanyvalues_implicit_sentinelinsertmanyvalues_max_parametersrp  r  r.  r  r   statement_compilerr  ddl_compilerr  type_compiler_clsrC  r  r  PrimaryKeyConstraintUniqueConstraintIndexr  construct_argumentsr   r}  r  r  r  r  r  r  r  r  r  r  r  r_  r  r   cacher  r]  r  r  r  r  r  r  r  r  r  r  r  r(  r6  rQ  r  r   r   r   r   r    s   		
&.




p 37r  )r  
__future__r   ra  r  rK  r7  typingr   r   uuidr   _python_UUIDrw  r   r  jsonr   r	   r
   r   r   r   r  r   r   r   r   enginer   r  r   r   engine.reflectionr   r   r   r   r   r   r   r   r   r   rx  sql._typingr    sql.compilerr!   sql.elementsr"   typesr#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r2   util.typingr3   sql.dmlr4   sql.selectabler5   MS_2017_VERSIONMS_2016_VERSIONMS_2014_VERSIONr  r  MS_2005_VERSIONMS_2000_VERSIONrT  r   r  r  r  r`  r  r9  _MSTimer?  rA  r_  rD  rG  rI  rQ  rR  r  r[  rb  r\  _Binaryr]  rh  rj  rk  r  ro  Textrp  r  rq  
TypeEnginerr  rs  rc  rt  _UUID_RETURNr|  r  
MSDateTimeMSDateMSRealMSTinyIntegerMSTimeMSSmallDateTimeMSDateTime2MSDateTimeOffsetr  r  r  r  r  r  r  r  MSImageMSBitMSMoneyMSSmallMoneyMSUniqueIdentifier	MSVariantr  GenericTypeCompilerr  DefaultExecutionContextr  r  r   r  DDLCompilerr  IdentifierPreparerrC  r]  r_  rY  rX  LRUCacherf  rO  re  r  r   r   r   r   <module>   s         S 9
*0(0	
# &     ,  ,: