o
    y¬´\&9 ã                   @   s¤  d Z ddlZddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddlm
Z dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z! ddlm"Z" ddlm#Z# ddlm$Z$ d Z%d!Z&d"Z'd#Z(d$Z)d%Z*e+g d&¢ƒZ,G d'd(„ d(ej-ƒZ-G d)d*„ d*ej.ƒZ/G d+d,„ d,ej0ƒZ1G d-d.„ d.ej2ƒZ2e2Z3G d/d0„ d0e4ƒZ5G d1d2„ d2e5ej6ƒZ7G d3d4„ d4e5ej6ƒZ8G d5d6„ d6e5ej6ƒZ9G d7d8„ d8ej:ƒZ;G d9d:„ d:e4ƒZ<G d;d<„ d<ej=ƒZ>G d=d>„ d>e>ƒZ?G d?d@„ d@ej@ƒZAG dAdB„ dBejBejCƒZBG dCdD„ dDejCƒZDG dEdF„ dFejEƒZFG dGdH„ dHej:ƒZGG dIdJ„ dJej:ƒZHG dKdL„ dLej:ƒZIG dMdN„ dNej:ƒZJG dOdP„ dPej:ƒZKe7ZLe1ZMe-ZNe/ZOe2ZPe8ZQe9ZRe;ZSe"ZTeAZUe#ZVe ZWeZXeZYeZZeBZ[eDZ\eGZ]eHZ^eIZ_eJZ`eKZai dQe“dRe“dSe!“dTe/“dUe#“dVe “dWe“dXe“dYe"“dZeA“d[e“d\e“d]e“d^e“d_e9“d`e;“dae“e2e8eeBeGe-eDeFe>eHeIeJeKdbœ¥ZbG dcdd„ ddejcƒZdG dedf„ dfejeƒZfG dgdh„ dhejgƒZhG didj„ djehƒZiG dkdl„ dlejjƒZkG dmdn„ dnejlƒZmdodp„ Zndqdr„ Zodsdt„ Zpdudv„ Zqdwdx„ ZrG dydz„ dzejsƒZtdS ){aÈO  
.. dialect:: mssql
    :name: Microsoft SQL Server


Auto Increment Behavior
-----------------------

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

    from sqlalchemy import Table, MetaData, Column, Integer

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

The above example will generate DDL as:

.. sourcecode:: sql

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

For the case where this default generation of ``IDENTITY`` is not desired,
specify ``autoincrement=False`` on all integer primary key columns::

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

.. note::

    An INSERT statement which refers to an explicit value for such
    a column is prohibited by SQL Server, however SQLAlchemy will detect this
    and modify the ``IDENTITY_INSERT`` flag accordingly at statement execution
    time.  As this is not a high performing process, care should be taken to
    set the ``autoincrement`` flag appropriately for columns that will not
    actually require IDENTITY behavior.

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

Specific control over the parameters of the ``IDENTITY`` value is supported
using the :class:`.schema.Sequence` object.  While this object normally
represents an explicit "sequence" for supporting backends, on SQL Server it is
re-purposed to specify behavior regarding the identity column, including
support of the "start" and "increment" values::

    from sqlalchemy import Table, Integer, Sequence, Column

    Table('test', metadata,
           Column('id', Integer,
                  Sequence('blah', start=100, increment=10),
                  primary_key=True),
           Column('name', String(20))
         ).create(some_engine)

would yield:

.. sourcecode:: sql

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

Note that the ``start`` and ``increment`` values for sequences are
optional and will default to 1,1.

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

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

The process for fetching this value has several variants:

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

  .. sourcecode:: sql

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

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

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

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

    an INSERT will look like:

    .. sourcecode:: sql

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

  * Other dialects such as pymssql will call upon
    ``SELECT scope_identity() AS lastrowid`` subsequent to an INSERT
    statement. If the flag ``use_scope_identity=False`` is passed to
    :func:`.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:`.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)

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

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

.. sourcecode:: sql

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

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



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

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

SQL Server supports the special string "MAX" within the
:class:`.sqltypes.VARCHAR` and :class:`.sqltypes.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:`.Table`, the
CREATE TABLE statement for this column will yield::

    login VARCHAR(32) COLLATE Latin1_General_CI_AS NULL

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

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

    select.limit

will yield::

    SELECT TOP n

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

.. _mssql_isolation_level:

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

All SQL Server dialects support setting of transaction isolation level
both via a dialect-specific parameter
:paramref:`.create_engine.isolation_level`
accepted by :func:`.create_engine`,
as well as the :paramref:`.Connection.execution_options.isolation_level`
argument as passed to
:meth:`.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:`.create_engine`::

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

To set using per-connection execution options::

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

Valid values for ``isolation_level`` include:

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

.. versionadded:: 1.1 support for isolation level setting on Microsoft
   SQL Server.

.. versionadded:: 1.2 added AUTOCOMMIT isolation level setting

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

    name VARCHAR(20) NULL

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

    name VARCHAR(20)

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

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

.. _mssql_large_type_deprecation:

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

Per
`SQL Server 2012/2014 Documentation <http://technet.microsoft.com/en-us/library/ms187993.aspx>`_,
the ``NTEXT``, ``TEXT`` and ``IMAGE`` datatypes are to be removed from SQL
Server in a future release.   SQLAlchemy normally relates these types to the
:class:`.UnicodeText`, :class:`.Text` 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:`.Text` 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:`.Text` 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:`.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:`.NVARCHAR`, :class:`.VARCHAR`, :class:`.types.VARBINARY`,
  :class:`.TEXT`, :class:`.mssql.NTEXT`, :class:`.mssql.IMAGE` will always
  remain fixed and always output exactly that type.

.. versionadded:: 1.0.0

.. _multipart_schema_names:

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

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

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

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

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

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

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

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

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

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


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

.. _legacy_schema_rendering:

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

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

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

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

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

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

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


.. _mssql_indexes:

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

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

To generate a clustered index::

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

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

To generate a clustered primary key use::

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

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

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

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

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

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

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

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

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

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


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

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

INCLUDE
^^^^^^^

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

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

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

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

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

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

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

.. seealso::

    :ref:`schema_indexes_functional`

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

Triggers
--------

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

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

Declarative form::

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


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

.. _mssql_rowcount_versioning:

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

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

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

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

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

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

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

    ALTER DATABASE MyDatabase SET ALLOW_SNAPSHOT_ISOLATION ON

    ALTER DATABASE MyDatabase SET READ_COMMITTED_SNAPSHOT ON

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

é    Né   )Úinformation_schemaé   )Úengine)Úexc)Úschema)Úsql)Útypes)Úutil)Údefault)Ú
reflection)Úcompiler)Ú
expression)Úquoted_name)ÚBIGINT)ÚBINARY)ÚCHAR)ÚDATE)ÚDATETIME)ÚDECIMAL)ÚFLOAT)ÚINTEGER)ÚNCHAR)ÚNUMERIC)ÚNVARCHAR)ÚSMALLINT)ÚTEXT)ÚVARCHAR©Úupdate_wrapper)é   )é   )é   )é
   )é	   )é   )´ÚaddÚallÚalterÚandÚanyÚasÚascÚauthorizationÚbackupÚbeginÚbetweenÚbreakÚbrowseÚbulkÚbyÚcascadeÚcaseÚcheckÚ
checkpointÚcloseÚ	clusteredÚcoalesceÚcollateÚcolumnÚcommitÚcomputeÚ
constraintÚcontainsÚcontainstableÚcontinueÚconvertÚcreateÚcrossÚcurrentÚcurrent_dateÚcurrent_timeÚcurrent_timestampÚcurrent_userÚcursorÚdatabaseÚdbccÚ
deallocateÚdeclarer   ÚdeleteÚdenyÚdescÚdiskÚdistinctÚdistributedÚdoubleÚdropÚdumpÚelseÚendÚerrlvlÚescapeÚexceptÚexecÚexecuteÚexistsÚexitÚexternalÚfetchÚfileÚ
fillfactorÚforÚforeignÚfreetextÚfreetexttableÚfromÚfullÚfunctionÚgotoÚgrantÚgroupÚhavingÚholdlockÚidentityÚidentity_insertÚidentitycolÚifÚinÚindexÚinnerÚinsertÚ	intersectÚintoÚisÚjoinÚkeyÚkillÚleftÚlikeÚlinenoÚloadÚmergeÚnationalÚnocheckÚnonclusteredÚnotÚnullÚnullifÚofÚoffÚoffsetsÚonÚopenÚopendatasourceÚ	openqueryÚ
openrowsetÚopenxmlÚoptionÚorÚorderÚouterÚoverÚpercentÚpivotÚplanÚ	precisionÚprimaryÚprintÚprocÚ	procedureÚpublicÚ	raiserrorÚreadÚreadtextÚreconfigureÚ
referencesÚreplicationÚrestoreÚrestrictÚreturnÚrevertÚrevokeÚrightÚrollbackÚrowcountÚ
rowguidcolÚruleÚsaver   ÚsecurityauditÚselectÚsession_userÚsetÚsetuserÚshutdownÚsomeÚ
statisticsÚsystem_userÚtableÚtablesampleÚtextsizeÚthenÚtoÚtopÚtranÚtransactionÚtriggerÚtruncateÚtsequalÚunionÚuniqueÚunpivotÚupdateÚ
updatetextÚuseÚuserÚvaluesÚvaryingÚviewÚwaitforÚwhenÚwhereÚwhileÚwithÚ	writetextc                       s    e Zd Zd Z‡ fdd„Z‡  ZS )ÚREALc                    s"   d|d< t t| ƒjdi |¤Ž d S )Né   r�   © )ÚsuperrØ   Ú__init__)ÚselfÚkw©Ú	__class__rÚ   úP/var/www/html/env/lib/python3.10/site-packages/sqlalchemy/dialects/mssql/base.pyrÜ   B  s   zREAL.__init__©Ú__name__Ú
__module__Ú__qualname__Ú__visit_name__rÜ   Ú__classcell__rÚ   rÚ   rß   rá   rØ   ?  s    rØ   c                   @   ó   e Zd Zd ZdS )ÚTINYINTN©rã   rä   rå   ræ   rÚ   rÚ   rÚ   rá   ré   H  ó    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á   ÚprocessT  ó   z'_MSDate.bind_processor.<locals>.processrÚ   ©rÝ   Údialectrù   rÚ   rÚ   rá   Úbind_processorS  ó   z_MSDate.bind_processorz(\d+)-(\d+)-(\d+)c                    ó   ‡ fdd„}|S )Nc                    óZ   t | tjƒr
|  ¡ S t | tjƒr+ˆ j | ¡}|std| f ƒ‚tjdd„ | ¡ D ƒŽ S | S )Nz"could not parse %r as a date valuec                 S   ó   g | ]}t |pd ƒ‘qS ©r   ©Úint©Ú.0ÚxrÚ   rÚ   rá   Ú
<listcomp>h  ó    z=_MSDate.result_processor.<locals>.process.<locals>.<listcomp>)	Ú
isinstancerò   ró   r
   Ústring_typesÚ_regÚmatchÚ
ValueErrorÚgroups©rø   Úm©rÝ   rÚ   rá   rù   _  ó   ÿz)_MSDate.result_processor.<locals>.processrÚ   ©rÝ   rü   Úcoltyperù   rÚ   r  rá   Úresult_processor^  ó   z_MSDate.result_processorN)rã   rä   rå   rý   ÚreÚcompiler  r  rÚ   rÚ   rÚ   rá   rì   R  s    
	rì   c                       sF   e Zd Zd‡ fdd„	Ze ddd¡Zdd„ Ze 	d¡Z
d	d
„ Z‡  ZS )ÚTIMENc                    s   || _ tt| ƒ ¡  d S rï   )r�   rÛ   r  rÜ   ©rÝ   r�   Úkwargsrß   rÚ   rá   rÜ   p  s   zTIME.__init__il  r   c                    s   ‡ fdd„}|S )Nc                    sD   t | tjƒrtj ˆ j|  ¡ ¡} | S t | tjƒr tj ˆ j| ¡} | S rï   )r
  rò   ÚcombineÚ_TIME__zero_dateÚtimer÷   r  rÚ   rá   rù   w  s   
ÿþz$TIME.bind_processor.<locals>.processrÚ   rû   rÚ   r  rá   rý   v  s   	zTIME.bind_processorz!(\d+):(\d+):(\d+)(?:\.(\d{0,6}))?c                    rÿ   )Nc                    r   )Nz"could not parse %r as a time valuec                 S   r  r  r  r  rÚ   rÚ   rá   r  Ž  r	  z:TIME.result_processor.<locals>.process.<locals>.<listcomp>)	r
  rò   r  r
   r  r  r  r  r  r  r  rÚ   rá   rù   …  r  z&TIME.result_processor.<locals>.processrÚ   r  rÚ   r  rá   r  „  r  zTIME.result_processorrï   )rã   rä   rå   rÜ   rò   ró   r  rý   r  r  r  r  rç   rÚ   rÚ   rß   rá   r  o  s    
r  c                   @   s   e Zd Zdd„ ZdS )Ú_DateTimeBasec                 C   rí   )Nc                 S   rî   rï   rð   r÷   rÚ   rÚ   rá   rù   š  rú   z-_DateTimeBase.bind_processor.<locals>.processrÚ   rû   rÚ   rÚ   rá   rý   ™  rþ   z_DateTimeBase.bind_processorN)rã   rä   rå   rý   rÚ   rÚ   rÚ   rá   r   ˜  s    r   c                   @   s   e Zd ZdS )Ú_MSDateTimeN)rã   rä   rå   rÚ   rÚ   rÚ   rá   r!  £  s    r!  c                   @   rè   )ÚSMALLDATETIMENrê   rÚ   rÚ   rÚ   rá   r"  §  rë   r"  c                       s"   e Zd Zd Zd‡ fdd„	Z‡  ZS )Ú	DATETIME2Nc                    s    t t| ƒjdi |¤Ž || _d S )NrÚ   )rÛ   r#  rÜ   r�   )rÝ   r�   rÞ   rß   rÚ   rá   rÜ   ®  s   
zDATETIME2.__init__rï   râ   rÚ   rÚ   rß   rá   r#  «  s    r#  c                   @   s   e Zd Zd Zddd„ZdS )ÚDATETIMEOFFSETNc                 K   s
   || _ d S rï   ©r�   r  rÚ   rÚ   rá   rÜ   ·  ó   
zDATETIMEOFFSET.__init__rï   )rã   rä   rå   ræ   rÜ   rÚ   rÚ   rÚ   rá   r$  ´  s    r$  c                       s"   e Zd ZdZd‡ fdd„	Z‡  ZS )Ú_StringTypezBase for MSSQL string types.Nc                    s   t t| ƒj|d� d S )N)Ú	collation)rÛ   r'  rÜ   )rÝ   r(  rß   rÚ   rá   rÜ   ¿  ó   z_StringType.__init__rï   )rã   rä   rå   Ú__doc__rÜ   rç   rÚ   rÚ   rß   rá   r'  »  s    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 )z¾Construct 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 t| ƒ ||¡‰ | jr‡ fdd„}|S ˆ S )Nc                    s&   ˆ | ƒ} | d urt t | d¡dƒ} | S )NÚhexé   )r  ÚcodecsÚencoder÷   ©Úsuper_rÚ   rá   rù   æ  s   z+TIMESTAMP.result_processor.<locals>.process)rÛ   r+  r  r,  r  rß   r1  rá   r  â  s
   zTIMESTAMP.result_processor©F)	rã   rä   rå   r*  ræ   ÚlengthrÜ   r  rç   rÚ   rÚ   rß   rá   r+  Ã  s    
r+  c                   @   ó   e Zd ZdZd ZdS )Ú
ROWVERSIONa(  Implement the SQL Server ROWVERSION type.

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

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

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

    .. versionadded:: 1.2

    .. seealso::

        :class:`.mssql.TIMESTAMP`

    N©rã   rä   rå   r*  ræ   rÚ   rÚ   rÚ   rá   r6  ò  s    r6  c                   @   r5  )ÚNTEXTzMMSSQL NTEXT type, for variable-length unicode text up to 2^30
    characters.Nr7  rÚ   rÚ   rÚ   rá   r8  
  s    r8  c                   @   r5  )Ú	VARBINARYaG  The MSSQL VARBINARY type.

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

    .. versionadded:: 1.0.0

    .. seealso::

        :ref:`mssql_large_type_deprecation`



    Nr7  rÚ   rÚ   rÚ   rá   r9    s    r9  c                   @   rè   )ÚIMAGENrê   rÚ   rÚ   rÚ   rá   r:  &  rë   r:  c                   @   r5  )ÚXMLa"  MSSQL XML type.

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

    .. versionadded:: 1.1.11

    Nr7  rÚ   rÚ   rÚ   rá   r;  *  s    r;  c                   @   rè   )ÚBITNrê   rÚ   rÚ   rÚ   rá   r<  9  rë   r<  c                   @   rè   )ÚMONEYNrê   rÚ   rÚ   rÚ   rá   r=  =  rë   r=  c                   @   rè   )Ú
SMALLMONEYNrê   rÚ   rÚ   rÚ   rá   r>  A  rë   r>  c                   @   rè   )ÚUNIQUEIDENTIFIERNrê   rÚ   rÚ   rÚ   rá   r?  E  rë   r?  c                   @   rè   )ÚSQL_VARIANTNrê   rÚ   rÚ   rÚ   rá   r@  I  rë   r@  r  ÚbigintÚsmallintÚtinyintÚvarcharÚnvarcharÚcharÚncharÚtextÚntextÚdecimalÚnumericÚfloatrò   Ú	datetime2Údatetimeoffsetró   )r  ÚsmalldatetimeÚbinaryÚ	varbinaryÚbitÚrealÚimageÚxmlÚ	timestampÚmoneyÚ
smallmoneyÚuniqueidentifierÚsql_variantc                   @   sþ   e Zd Zd>dd„Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd d!„ Zd"d#„ Zd$d%„ Zd&d'„ Zd(d)„ Zd*d+„ Zd,d-„ Zd.d/„ Zd0d1„ Zd2d3„ Zd4d5„ Zd6d7„ Zd8d9„ Zd:d;„ Zd<d=„ Z dS )?ÚMSTypeCompilerNc                 C   sN   t |ddƒrd|j }nd}|s|j}|r|d|  }d dd„ ||fD ƒ¡S )zYExtend a string-type declaration with standard SQL
        COLLATE annotations.

        r(  Nz
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(  r4  r~   )rÝ   ÚspecÚtype_r4  r(  rÚ   rÚ   rá   Ú_extendˆ  s   zMSTypeCompiler._extendc                 K   s$   t |dd ƒ}|d u rdS dd|i S )Nr�   r   zFLOAT(%(precision)s)©r`  ©rÝ   rb  rÞ   r�   rÚ   rÚ   rá   Úvisit_FLOAT›  s   zMSTypeCompiler.visit_FLOATc                 K   ó   dS )Nré   rÚ   ©rÝ   rb  rÞ   rÚ   rÚ   rá   Úvisit_TINYINT¢  ó   zMSTypeCompiler.visit_TINYINTc                 K   s   |j d ur
d|j  S dS )NzDATETIMEOFFSET(%s)r$  r%  rh  rÚ   rÚ   rá   Úvisit_DATETIMEOFFSET¥  s   

z#MSTypeCompiler.visit_DATETIMEOFFSETc                 K   ó    t |dd ƒ}|d urd| S dS )Nr�   zTIME(%s)r  rd  re  rÚ   rÚ   rá   Ú
visit_TIME«  ó   zMSTypeCompiler.visit_TIMEc                 K   rg  )Nr+  rÚ   rh  rÚ   rÚ   rá   Úvisit_TIMESTAMP²  rj  zMSTypeCompiler.visit_TIMESTAMPc                 K   rg  )Nr6  rÚ   rh  rÚ   rÚ   rá   Úvisit_ROWVERSIONµ  rj  zMSTypeCompiler.visit_ROWVERSIONc                 K   rl  )Nr�   zDATETIME2(%s)r#  rd  re  rÚ   rÚ   rá   Úvisit_DATETIME2¸  rn  zMSTypeCompiler.visit_DATETIME2c                 K   rg  )Nr"  rÚ   rh  rÚ   rÚ   rá   Úvisit_SMALLDATETIME¿  rj  z"MSTypeCompiler.visit_SMALLDATETIMEc                 K   s   | j |fi |¤ŽS rï   )Úvisit_NVARCHARrh  rÚ   rÚ   rá   Úvisit_unicodeÂ  ó   zMSTypeCompiler.visit_unicodec                 K   ó,   | j jr| j|fi |¤ŽS | j|fi |¤ŽS rï   )rü   Údeprecate_large_typesÚvisit_VARCHARÚ
visit_TEXTrh  rÚ   rÚ   rá   Ú
visit_textÅ  ó   zMSTypeCompiler.visit_textc                 K   rv  rï   )rü   rw  rs  Úvisit_NTEXTrh  rÚ   rÚ   rá   Úvisit_unicode_textË  r{  z!MSTypeCompiler.visit_unicode_textc                 K   ó   |   d|¡S )Nr8  ©rc  rh  rÚ   rÚ   rá   r|  Ñ  ó   zMSTypeCompiler.visit_NTEXTc                 K   r~  )Nr   r  rh  rÚ   rÚ   rá   ry  Ô  r€  zMSTypeCompiler.visit_TEXTc                 K   ó   | j d||jpdd�S )Nr   Úmax©r4  ©rc  r4  rh  rÚ   rÚ   rá   rx  ×  r)  zMSTypeCompiler.visit_VARCHARc                 K   r~  )Nr   r  rh  rÚ   rÚ   rá   Ú
visit_CHARÚ  r€  zMSTypeCompiler.visit_CHARc                 K   r~  )Nr   r  rh  rÚ   rÚ   rá   Úvisit_NCHARÝ  r€  zMSTypeCompiler.visit_NCHARc                 K   r�  )Nr   r‚  rƒ  r„  rh  rÚ   rÚ   rá   rs  à  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_VERSIONÚvisit_DATETIMEÚ
visit_DATErh  rÚ   rÚ   rá   Ú
visit_dateã  ó   zMSTypeCompiler.visit_datec                 K   r‡  rï   )rü   rˆ  r‰  rŠ  rm  rh  rÚ   rÚ   rá   Ú
visit_timeé  r�  zMSTypeCompiler.visit_timec                 K   rv  rï   )rü   rw  Úvisit_VARBINARYÚvisit_IMAGErh  rÚ   rÚ   rá   Úvisit_large_binaryï  r{  z!MSTypeCompiler.visit_large_binaryc                 K   rg  )Nr:  rÚ   rh  rÚ   rÚ   rá   r�  õ  rj  zMSTypeCompiler.visit_IMAGEc                 K   rg  )Nr;  rÚ   rh  rÚ   rÚ   rá   Ú	visit_XMLø  rj  zMSTypeCompiler.visit_XMLc                 K   r�  )Nr9  r‚  rƒ  r„  rh  rÚ   rÚ   rá   r�  û  r)  zMSTypeCompiler.visit_VARBINARYc                 K   s
   |   |¡S rï   )Ú	visit_BITrh  rÚ   rÚ   rá   Úvisit_booleanþ  r&  zMSTypeCompiler.visit_booleanc                 K   rg  )Nr<  rÚ   rh  rÚ   rÚ   rá   r“    rj  zMSTypeCompiler.visit_BITc                 K   rg  )Nr=  rÚ   rh  rÚ   rÚ   rá   Úvisit_MONEY  rj  zMSTypeCompiler.visit_MONEYc                 K   rg  )Nr>  rÚ   rh  rÚ   rÚ   rá   Úvisit_SMALLMONEY  rj  zMSTypeCompiler.visit_SMALLMONEYc                 K   rg  )Nr?  rÚ   rh  rÚ   rÚ   rá   Úvisit_UNIQUEIDENTIFIER
  rj  z%MSTypeCompiler.visit_UNIQUEIDENTIFIERc                 K   rg  )Nr@  rÚ   rh  rÚ   rÚ   rá   Úvisit_SQL_VARIANT  rj  z MSTypeCompiler.visit_SQL_VARIANTrï   )!rã   rä   rå   rc  rf  ri  rk  rm  ro  rp  rq  rr  rt  rz  r}  r|  ry  rx  r…  r†  rs  rŒ  rŽ  r‘  r�  r’  r�  r”  r“  r•  r–  r—  r˜  rÚ   rÚ   rÚ   rá   r[  ‡  s>    
r[  c                   @   sL   e Zd ZdZdZdZdZdd„ Zdd„ Zdd„ Z	d	d
„ Z
dd„ Zdd„ ZdS )ÚMSExecutionContextFNc                 C   s   | j js| j  |¡d S |S )Nr   )rü   Úsupports_unicode_statementsÚ_encoder)rÝ   Ú	statementrÚ   rÚ   rá   Ú_opt_encode  s   zMSExecutionContext._opt_encodec              	   C   s  | j r~| jjj}|j}|du}|rM|j| jd v pJ| jjjoJ| jjjo5|j| jjjd v p5|| jjjd v pJ| jjj oJ|j| jjjv pJ|| jjjv | _	nd| _	| jj
 oc|oc| jj oc| j	 oc| j | _| j	r€| j | j|  d| jj |¡ ¡d| ¡ dS dS dS )z#Activate IDENTITY_INSERT if needed.Nr   FzSET IDENTITY_INSERT %s ONrÚ   )ÚisinsertÚcompiledrœ  r½   Ú_autoincrement_columnr   Úcompiled_parametersÚ
parametersÚ_has_multi_parametersÚ_enable_identity_insertÚinlineÚ	returningÚexecutemanyÚ_select_lastrowidÚroot_connectionÚ_cursor_executerL   r�  rü   Úidentifier_preparerÚformat_table)rÝ   ÚtblÚ
seq_columnÚinsert_has_sequencerÚ   rÚ   rá   Úpre_exec  s^   
ÿ

ÿÿû
ÿÿí
ÿþýûÿÿùÕ*zMSExecutionContext.pre_execc              	   C   s¶   | j }| jr+| jjr| | jdd| ¡ n	| | jdd| ¡ | j ¡ d }t|d ƒ| _| j	s4| j
s4| jr>| jjr>t | ¡| _| jrY| | j|  d| jj | jjj¡ ¡d| ¡ dS dS )z#Disable IDENTITY_INSERT if enabled.z$SELECT scope_identity() AS lastrowidrÚ   zSELECT @@identity AS lastrowidr   úSET IDENTITY_INSERT %s OFFN)r©  r¨  rü   Úuse_scope_identityrª  rL   Úfetchallr  Ú
_lastrowidrž  ÚisupdateÚisdeleterŸ  r¦  r   ÚFullyBufferedResultProxyÚ_result_proxyr¤  r�  r«  r¬  rœ  r½   )rÝ   ÚconnÚrowrÚ   rÚ   rá   Ú	post_execU  sJ   ü
ÿÿÿÿþÿÿÿ÷ÿzMSExecutionContext.post_execc                 C   s   | j S rï   )r´  r  rÚ   rÚ   rá   Úget_lastrowid{  s   z MSExecutionContext.get_lastrowidc                 C   sL   | j r$z| j |  d| jj | jjj	¡ ¡¡ W d S  t
y#   Y d S w d S )Nr±  )r¤  rL   r`   r�  rü   r«  r¬  rŸ  rœ  r½   Ú	Exception)rÝ   ÚerÚ   rÚ   rá   Úhandle_dbapi_exception~  s   ÿÿÿ
ÿÿöz)MSExecutionContext.handle_dbapi_exceptionc                 C   s   | j r| j S t | ¡S rï   )r¸  r   ÚResultProxyr  rÚ   rÚ   rá   Úget_result_proxyŒ  s   
z#MSExecutionContext.get_result_proxy)rã   rä   rå   r¤  r¨  r¸  r´  r�  r°  r»  r¼  r¿  rÁ  rÚ   rÚ   rÚ   rá   r™    s    8&r™  c                       sR  e Zd ZdZe ejjdddddœ¡Z‡ fdd„Z	‡ fd	d
„Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd „ Zd!d"„ Zd#d$„ Ze
dG‡ fd&d'„	ƒZe
‡ fd(d)„ƒZe
dH‡ fd+d,„	ƒZd-d.„ Zd/d0„ Zd1d2„ Zd3d4„ Z‡ fd5d6„Zd7d8„ Z d9d:„ Z!‡ fd;d<„Z"d=d>„ Z#d?d@„ Z$dAdB„ Z%dCdD„ Z&dEdF„ Z'‡  Z(S )IÚMSSQLCompilerTÚ	dayofyearÚweekdayÚmillisecondÚmicrosecond)ÚdoyÚdowÚmillisecondsÚmicrosecondsc                    s    i | _ tt| ƒj|i |¤Ž d S rï   )ÚtablealiasesrÛ   rÂ  rÜ   )rÝ   Úargsr  rß   rÚ   rá   rÜ      s   zMSSQLCompiler.__init__c                    s   ‡‡ fdd„}|S )Nc                    s>   | j jrˆ| g|¢R i |¤ŽS ttt| ƒˆjƒ}||i |¤ŽS rï   )rü   Úlegacy_schema_aliasingr`  rÛ   rÂ  rã   )rÝ   ÚargrÞ   r2  )rà   ÚfnrÚ   rá   Údecorate¥  s   z<MSSQLCompiler._with_legacy_schema_aliasing.<locals>.decoraterÚ   )rÏ  rÐ  rß   ©rÏ  rá   Ú_with_legacy_schema_aliasing¤  s   z*MSSQLCompiler._with_legacy_schema_aliasingc                 K   rg  )NÚCURRENT_TIMESTAMPrÚ   ©rÝ   rÏ  rÞ   rÚ   rÚ   rá   Úvisit_now_func®  rj  zMSSQLCompiler.visit_now_funcc                 K   rg  )Nz	GETDATE()rÚ   rÔ  rÚ   rÚ   rá   Úvisit_current_date_func±  rj  z%MSSQLCompiler.visit_current_date_funcc                 K   ó   d| j |fi |¤Ž S ©NzLEN%s©Úfunction_argspecrÔ  rÚ   rÚ   rá   Úvisit_length_func´  r)  zMSSQLCompiler.visit_length_funcc                 K   r×  rØ  rÙ  rÔ  rÚ   rÚ   rá   Úvisit_char_length_func·  r)  z$MSSQLCompiler.visit_char_length_funcc                 K   ó,   d| j |jfi |¤Ž| j |jfi |¤Žf S )Nz%s + %s©rù   r�   r®   ©rÝ   rP  ÚoperatorrÞ   rÚ   rÚ   rá   Úvisit_concat_op_binaryº  ó   þz$MSSQLCompiler.visit_concat_op_binaryc                 K   rg  )NÚ1rÚ   ©rÝ   ÚexprrÞ   rÚ   rÚ   rá   Ú
visit_trueÀ  rj  zMSSQLCompiler.visit_truec                 K   rg  )NÚ0rÚ   rä  rÚ   rÚ   rá   Úvisit_falseÃ  rj  zMSSQLCompiler.visit_falsec                 K   rÝ  )NzCONTAINS (%s, %s)rÞ  rß  rÚ   rÚ   rá   Úvisit_match_op_binaryÆ  râ  z#MSSQLCompiler.visit_match_op_binaryc                 K   sJ   d}|j r	|d7 }|jr|js|d|j 7 }|r|S tjj| |fi |¤ŽS )z- MS-SQL puts TOP, it's version of LIMIT here Ú z	DISTINCT zTOP %d )Ú	_distinctÚ_simple_int_limitÚ_offsetÚ_limitr   ÚSQLCompilerÚget_select_precolumns)rÝ   rµ   rÞ   ÚsrÚ   rÚ   rá   rð  Ì  s   ÿÿz#MSSQLCompiler.get_select_precolumnsc                 C   ó   |S rï   rÚ   ©rÝ   r½   rH  rÚ   rÚ   rá   Úget_from_hint_textà  rj  z MSSQLCompiler.get_from_hint_textc                 C   rò  rï   rÚ   ró  rÚ   rÚ   rá   Úget_crud_hint_textã  rj  z MSSQLCompiler.get_crud_hint_textc                 K   rg  ©Nrê  rÚ   )rÝ   rµ   rÞ   rÚ   rÚ   rá   Úlimit_clauseæ  ó   zMSSQLCompiler.limit_clausec                 K   s(  |j s|jdus|jdur|jr|jr‰t|ddƒs‰|jjs"t 	d¡‚dd„ |jjD ƒ}|j}|j}||d< | 
¡ }d|_| tj ¡ j|d� d	¡¡ d¡ ¡ }t d	¡}t d
d„ |jD ƒ¡}|dury| ||k¡ |durx| ||| k¡ n| ||k¡ | j|fi |¤ŽS tjj| |fi |¤ŽS )z�Look for ``LIMIT`` and OFFSET in a select statement, and if
        so tries to wrap it in a subquery with ``row_number()`` criterion.

        NÚ_mssql_visitzLMSSQL requires an order_by when using an OFFSET or a non-simple LIMIT clausec                 S   s   g | ]}t  |¡‘qS rÚ   )Úsql_utilÚunwrap_label_reference)r  ÚelemrÚ   rÚ   rá   r     s    ÿÿz.MSSQLCompiler.visit_select.<locals>.<listcomp>Úselect_wraps_forT©Úorder_byÚmssql_rnc                 S   s   g | ]	}|j d kr|‘qS )r   )r   r^  rÚ   rÚ   rá   r    s    )rì  Ú_limit_clauseÚ_offset_clauseÚ_simple_int_offsetrí  r`  Ú_order_by_clauseÚclausesr   ÚCompileErrorÚ	_generaterù  r=   r   ÚfuncÚ
ROW_NUMBERr™   Úlabelrÿ  Úaliasrµ   r_  Úappend_whereclauserù   r   rï  Úvisit_select)rÝ   rµ   r  Ú_order_by_clausesr÷  Úoffset_clauser   ÚlimitselectrÚ   rÚ   rá   r  ê  sZ   ÿ

ÿþ
üÿþÿýù

ÿ
ÿ€zMSSQLCompiler.visit_selectFc                    sd   ||u s|rt t| ƒj|fi |¤ŽS |  |¡}|d ur&| j|fd|i|¤ŽS t t| ƒj|fi |¤ŽS ©NÚmssql_aliased)rÛ   rÂ  Úvisit_tableÚ_schema_aliased_tablerù   )rÝ   r½   r  Úiscrudr  r  rß   rÚ   rá   r  $  s   
zMSSQLCompiler.visit_tablec                    s"   |j |d< tt| ƒj|fi |¤ŽS r  )ÚoriginalrÛ   rÂ  Úvisit_alias)rÝ   r  rÞ   rß   rÚ   rá   r  0  s   
zMSSQLCompiler.visit_aliasNc                    s˜   |j d ur| js| jr|  ¡ r>|  |j ¡}|d ur>t ||¡}|d ur2||j|j||j|jf|j	ƒ t
t| ƒj|fi |¤ŽS t
t| ƒj|fd|i|¤ŽS )NÚadd_to_result_map)r½   rµ  r¶  Úis_subqueryr  r   Ú_corresponding_column_or_errorÚnamer   rñ   rÛ   rÂ  Úvisit_column)rÝ   r=   r  rÞ   ÚtÚ	convertedrß   rÚ   rá   r  6  s6   
ÿÿþÿü
ÿÿÿ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  Q  s
   

z#MSSQLCompiler._schema_aliased_tablec                 K   s.   | j  |j|j¡}d|| j|jfi |¤Žf S )NzDATEPART(%s, %s))Úextract_mapÚgetÚfieldrù   rå  )rÝ   ÚextractrÞ   r!  rÚ   rÚ   rá   Úvisit_extractY  s   zMSSQLCompiler.visit_extractc                 C   ó   d| j  |¡ S )NzSAVE TRANSACTION %s©ÚpreparerÚformat_savepoint©rÝ   Úsavepoint_stmtrÚ   rÚ   rá   Úvisit_savepoint]  ó   ÿzMSSQLCompiler.visit_savepointc                 C   r$  )NzROLLBACK TRANSACTION %sr%  r(  rÚ   rÚ   rá   Úvisit_rollback_to_savepointb  r+  z)MSSQLCompiler.visit_rollback_to_savepointc                    sb   t |jtjƒr%|jtjkr%t |jtjƒs%| jt |j|j|j¡fi |¤ŽS t	t
| ƒj|fi |¤ŽS )z]Move bind parameters to the right-hand side of an operator, where
        possible.

        )r
  r�   r   ÚBindParameterrà  Úeqr®   rù   ÚBinaryExpressionrÛ   rÂ  Úvisit_binary)rÝ   rP  r  rß   rÚ   rá   r0  g  s   ÿÿÿÿüzMSSQLCompiler.visit_binaryc                    sX   ˆj sˆjr|j d¡}n|j d¡}t |¡‰ ‡ ‡fdd„t |¡D ƒ}dd |¡ S )NÚinsertedÚdeletedc              	      s$   g | ]}ˆ  d ˆ  |¡ddi ¡‘qS )NTF)Ú_label_select_columnÚtraverser^  ©ÚadapterrÝ   rÚ   rá   r  ‚  s    ýÿÿz2MSSQLCompiler.returning_clause.<locals>.<listcomp>zOUTPUT ú, )	rž  rµ  r½   r  rú  ÚClauseAdapterr   Ú_select_iterablesr~   )rÝ   ÚstmtÚreturning_colsÚtargetÚcolumnsrÚ   r5  rá   Úreturning_clausey  s   
üzMSSQLCompiler.returning_clausec                 C   rg  )NÚWITHrÚ   )rÝ   Ú	recursiverÚ   rÚ   rá   Úget_cte_preamble‹  s   zMSSQLCompiler.get_cte_preamblec                    s*   t |tjƒr| d ¡S tt| ƒ |||¡S rï   )r
  r   ÚFunctionr
  rÛ   rÂ  Úlabel_select_column)rÝ   rµ   r=   Úasfromrß   rÚ   rá   rC  ’  s
   

ÿz!MSSQLCompiler.label_select_columnc                 C   rg  rö  rÚ   )rÝ   rµ   rÚ   rÚ   rá   Úfor_update_clauseš  s   zMSSQLCompiler.for_update_clausec                 K   s2   | j |jfi |¤Ž}|r|  ¡ r|jrd| S dS )Nz
 ORDER BY rê  )rù   r  r  rî  )rÝ   rµ   rÞ   rÿ  rÚ   rÚ   rá   Úorder_by_clauseŸ  s   zMSSQLCompiler.order_by_clausec                    ó&   dd  ‡ ‡‡fdd„|g| D ƒ¡ S )a  Render the UPDATE..FROM clause specific to MSSQL.

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

        úFROM r7  c                 3   ó(   � | ]}|j ˆfd ˆ dœˆ¤ŽV  qdS ©T)rD  Ú	fromhintsN©Ú_compiler_dispatch©r  r  ©Ú
from_hintsrÞ   rÝ   rÚ   rá   Ú	<genexpr>²  ó
   € ÿ
ÿz3MSSQLCompiler.update_from_clause.<locals>.<genexpr>©r~   )rÝ   Úupdate_stmtÚ
from_tableÚextra_fromsrP  rÞ   rÚ   rO  rá   Úupdate_from_clause¨  s   

þz MSSQLCompiler.update_from_clausec                 C   s   d}|rd}|j | dd|d�S )z=If we have extra froms make sure we render any alias as hint.FT)rD  r  ÚashintrL  )rÝ   Údelete_stmtrU  rV  rX  rÚ   rÚ   rá   Údelete_table_clause·  s   ÿz!MSSQLCompiler.delete_table_clausec                    rG  )zjRender the DELETE .. FROM clause specific to MSSQL.

        Yes, it has the FROM keyword twice.

        rH  r7  c                 3   rI  rJ  rL  rN  rO  rÚ   rá   rQ  È  rR  z9MSSQLCompiler.delete_extra_from_clause.<locals>.<genexpr>rS  )rÝ   rY  rU  rV  rP  rÞ   rÚ   rO  rá   Údelete_extra_from_clauseÀ  s   
þz&MSSQLCompiler.delete_extra_from_clause)FFrï   ))rã   rä   rå   Úreturning_precedes_valuesr
   Úupdate_copyr   rï  r  rÜ   rÒ  rÕ  rÖ  rÛ  rÜ  rá  ræ  rè  ré  rð  rô  rõ  r÷  r  r  r  r  r  r#  r*  r,  r0  r>  rA  rC  rE  rF  rW  rZ  r[  rç   rÚ   rÚ   rß   rá   rÂ  “  sX    üþ

:		rÂ  c                       s4   e Zd ZdZdZdd„ Zdd„ Z‡ fdd„Z‡  ZS )	ÚMSSQLStrictCompilerzËA subclass of MSSQLCompiler which disables the usage of bind
    parameters where not allowed natively by MS-SQL.

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

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

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

        For other data types, call the base class implementation.
        ú')Ú
issubclassrñ   rò   ró   ÚstrrÛ   r^  Úrender_literal_value)rÝ   rø   rb  rß   rÚ   rá   rg  è  s
   
ÿz(MSSQLStrictCompiler.render_literal_value)	rã   rä   rå   r*  Úansi_bind_rulesra  rc  rg  rç   rÚ   rÚ   rß   rá   r^  Î  s    r^  c                   @   s6   e Zd Zdd„ Zddd„Zdd„ Zdd	„ Zd
d„ ZdS )ÚMSDDLCompilerc                 K   sð   | j  |¡d | jjj|j|d� }|jd ur-|jr$|js$t|j	t
jƒr)|d7 }n|d7 }|jd u r7t d¡‚t|j	t
jƒr[|j	jdkrGd}n|j	jpLd}|d||j	jpUdf 7 }|S ||jju rg|d	7 }|S |  |¡}|d urv|d
| 7 }|S )Nr]  )Útype_expressionz	 NOT NULLz NULLz;mssql requires Table-bound columns in order to generate DDLr   r   z IDENTITY(%s,%s)z IDENTITY(1,1)z	 DEFAULT )r&  Úformat_columnrü   Útype_compilerrù   rñ   ÚnullableÚprimary_keyr
  r   Ú	sa_schemaÚSequencer½   r   r  ÚstartÚ	incrementr   Úget_column_default_string)rÝ   r=   r  Úcolspecrq  r   rÚ   rÚ   rá   Úget_column_specificationþ  sJ   
ÿÿþÿ
ÿþý

ÿ
þù
üz&MSDDLCompiler.get_column_specificationFc              	      sÜ   |j ‰ ˆ ˆ ¡ ˆj‰d}ˆ jr|d7 }ˆ jd d }|d ur*|r&|d7 }n|d7 }|dˆjˆ |d�ˆ ˆ j¡d	 ‡fd
d„ˆ j	D ƒ¡f 7 }ˆ jd d rl‡ fdd„ˆ jd d D ƒ}|dd	 ‡fdd„|D ƒ¡ 7 }|S )NzCREATE úUNIQUE Úmssqlr:   ú
CLUSTERED úNONCLUSTERED zINDEX %s ON %s (%s)©Úinclude_schemar7  c                 3   s"   � | ]}ˆ j j|d dd�V  qdS )FT)Úinclude_tabler`  N)Úsql_compilerrù   )r  rå  r  rÚ   rá   rQ  ?  s   € ýÿ
ÿz3MSDDLCompiler.visit_create_index.<locals>.<genexpr>Úincludec                    s(   g | ]}t |tjƒrˆ jj| n|‘qS rÚ   )r
  r
   r  r½   r_  )r  Úcol)rx   rÚ   rá   r  I  s    
þÿýz4MSDDLCompiler.visit_create_index.<locals>.<listcomp>z INCLUDE (%s)c                    s   g | ]}ˆ   |j¡‘qS rÚ   )Úquoter  r^  )r&  rÚ   rá   r  Q  r	  )
ÚelementÚ_verify_index_tabler&  rÉ   Údialect_optionsÚ_prepared_index_namer¬  r½   r~   Úexpressions)rÝ   rE   r{  rH  r:   Ú
inclusionsrÚ   )rx   r&  rÝ   rá   Úvisit_create_index,  s4   


üý
üÿz MSDDLCompiler.visit_create_indexc                 C   s$   d| j |jdd�| j |jj¡f S )Nz
DROP INDEX %s ON %sFrz  )r„  r�  r&  r¬  r½   )rÝ   rX   rÚ   rÚ   rá   Úvisit_drop_indexV  s   þzMSDDLCompiler.visit_drop_indexc                    ó˜   t |ƒdkrdS d}|jd ur|dˆ j |¡ 7 }|d7 }|jd d }|d ur3|r/|d7 }n|d7 }|d	d
 ‡ fdd„|D ƒ¡ 7 }|ˆ  |¡7 }|S )Nr   rê  úCONSTRAINT %s zPRIMARY KEY rw  r:   rx  ry  r\  r7  c                 3   ó   � | ]
}ˆ j  |j¡V  qd S rï   ©r&  r€  r  r^  r  rÚ   rá   rQ  m  ó   € 
ÿz=MSDDLCompiler.visit_primary_key_constraint.<locals>.<genexpr>©Úlenr  r&  Úformat_constraintrƒ  r~   Údefine_constraint_deferrability©rÝ   r@   rH  r:   rÚ   r  rá   Úvisit_primary_key_constraint\  ó$   

ÿ
ÿz*MSDDLCompiler.visit_primary_key_constraintc                    r‰  )Nr   rê  rŠ  rv  rw  r:   rx  ry  r\  r7  c                 3   r‹  rï   rŒ  r^  r  rÚ   rá   rQ  „  r�  z8MSDDLCompiler.visit_unique_constraint.<locals>.<genexpr>rŽ  r’  rÚ   r  rá   Úvisit_unique_constraints  r”  z%MSDDLCompiler.visit_unique_constraintNr3  )rã   rä   rå   ru  r‡  rˆ  r“  r•  rÚ   rÚ   rÚ   rá   ri  ý  s    
.*ri  c                       s2   e Zd ZeZ‡ fdd„Zdd„ Zddd„Z‡  ZS )	ÚMSIdentifierPreparerc                    s   t t| ƒj|dddd� d S )Nú[ú]F)Úinitial_quoteÚfinal_quoteÚquote_case_sensitive_collations)rÛ   r–  rÜ   )rÝ   rü   rß   rÚ   rá   rÜ   Ž  s   

üzMSIdentifierPreparer.__init__c                 C   s   |S rï   rÚ   )rÝ   rø   rÚ   rÚ   rá   Ú_escape_identifier–  rj  z'MSIdentifierPreparer._escape_identifierNc                 C   sL   t |ƒ\}}|rd|  ||¡|  ||¡f }|S |r"|  ||¡}|S d}|S )z'Prepare a quoted table and schema name.ú%s.%srê  )Ú_schema_elementsr€  )rÝ   r   ÚforceÚdbnameÚownerÚresultrÚ   rÚ   rá   Úquote_schema™  s   

þüÿz!MSIdentifierPreparer.quote_schemarï   )	rã   rä   rå   ÚRESERVED_WORDSÚreserved_wordsrÜ   rœ  r£  rç   rÚ   rÚ   rß   rá   r–  ‹  s
    r–  c                    ó   d‡ fdd„	}t |ˆ ƒS )Nc              	      s,   t | |ƒ\}}t||ˆ | ||||fi |¤ŽS rï   ©Ú_owner_plus_dbÚ
_switch_db)rü   Ú
connectionr   rÞ   r   r¡  rÑ  rÚ   rá   Úwrapª  s   ø	÷z$_db_plus_owner_listing.<locals>.wraprï   r   ©rÏ  r«  rÚ   rÑ  rá   Ú_db_plus_owner_listing©  s   
r­  c                    r¦  )Nc              
      s.   t | |ƒ\}}t||ˆ | |||||f	i |¤ŽS rï   r§  )rü   rª  Ú	tablenamer   rÞ   r   r¡  rÑ  rÚ   rá   r«  ¼  s   ÷
öz_db_plus_owner.<locals>.wraprï   r   r¬  rÚ   rÑ  rá   Ú_db_plus_owner»  s   
r¯  c              
   O   sX   | r|  d¡}| d|  ¡ z||i |¤ŽW | r | d| ¡ S S | r+| d| ¡ w w )Nzselect db_name()zuse %s)Úscalarr`   )r   rª  rÏ  rÎ  rÞ   Ú
current_dbrÚ   rÚ   rá   r©  Î  s   
ÿÿr©  c                 C   s&   |sd | j fS d|v rt|ƒS d |fS )NÚ.)Údefault_schema_namerž  )rü   r   rÚ   rÚ   rá   r¨  Ù  s
   
r¨  c                 C   sÈ   t | tƒr| jrd | fS g }d}d}t d| ¡D ]%}|sq|dkr$d}q|dkr+d}q|s9|dkr9| |¡ d}q||7 }q|rE| |¡ t|ƒdkrX|d	 d |dd … ¡fS t|ƒrbd |d	 fS d
S )Nrê  Fz
(\[|\]|\.)r—  Tr˜  r²  r   r   )NN)r
  r   r€  r  ÚsplitÚappendr�  r~   )r   ÚpushÚsymbolÚbracketÚtokenrÚ   rÚ   rá   rž  â  s.   


rž  c                       s²  e Zd ZdZdZdZeZdZdZ	dZ
ejeejeejeiZejj dejfg¡ZeZdZdZdZdZdZeZ e!Z"e#Z$e%Z&e'j(dd	ife'j)dd	ife'j*d	d	d
œfgZ+											d0‡ fdd„	Z,‡ fdd„Z-dd„ Z.e/g d¢ƒZ0dd„ Z1dd„ Z2‡ fdd„Z3dd„ Z4dd„ Z5dd„ Z6e7dd„ ƒZ8e9j:d d!„ ƒZ;e9j:e<d"d#„ ƒƒZ=e9j:e<d$d%„ ƒƒZ>e9j:e7d&d'„ ƒƒZ?e9j:e7d(d)„ ƒƒZ@e9j:e7d*d+„ ƒƒZAe9j:e7d,d-„ ƒƒZBe9j:e7d.d/„ ƒƒZC‡  ZDS )1Ú	MSDialectrw  TFé€   ÚdborÍ  rÚ   r:   N)r:   r~  c           	         sZ   t |pdƒ| _|| _|| _t |pdƒp| j| _|| _|| _tt| ƒj	di |¤Ž || _
d S )Nr   rÚ   )r  Úquery_timeoutÚschema_namer²  Úmax_identifier_lengthrw  rÍ  rÛ   rº  rÜ   Úisolation_level)	rÝ   r½  r²  r¿  r¾  rÀ  rw  rÍ  Úoptsrß   rÚ   rá   rÜ   &  s   ÿ
zMSDialect.__init__c                    s    |  d¡ tt| ƒ ||¡ d S )Nz$IF @@TRANCOUNT = 0 BEGIN TRANSACTION)r`   rÛ   rº  Údo_savepoint©rÝ   rª  r  rß   rÚ   rá   rÂ  ?  s   
zMSDialect.do_savepointc                 C   s   d S rï   rÚ   rÃ  rÚ   rÚ   rá   Údo_release_savepointD  rø  zMSDialect.do_release_savepoint)ÚSERIALIZABLEzREAD UNCOMMITTEDzREAD COMMITTEDzREPEATABLE READÚSNAPSHOTc                 C   sj   |  dd¡}|| jvrt d|| jd | j¡f ¡‚| ¡ }| d| ¡ | ¡  |dkr3| 	¡  d S d S )NÚ_r]  zLInvalid value '%s' for isolation_level. Valid isolation levels for %s are %sr7  z"SET TRANSACTION ISOLATION LEVEL %srÆ  )
ÚreplaceÚ_isolation_lookupr   ÚArgumentErrorr  r~   rL   r`   r9   r>   )rÝ   rª  ÚlevelrL   rÚ   rÚ   rá   Úset_isolation_levelR  s   
þÿÿzMSDialect.set_isolation_levelc                 C   s¼   | j tk r	tdƒ‚d }d}|D ]A}| ¡ }z6z| d| ¡ | ¡ d }W n | jjy@ } z|}W Y d }~W | ¡  qd }~ww | 	¡ W | ¡    S | ¡  w t
 d||f ¡ tdƒ‚)Nz4Can't fetch isolation level prior to SQL Server 2005)zsys.dm_exec_sessionszsys.dm_pdw_nodes_exec_sessionsaÏ  
                  SELECT CASE transaction_isolation_level
                    WHEN 0 THEN NULL
                    WHEN 1 THEN 'READ UNCOMMITTED'
                    WHEN 2 THEN 'READ COMMITTED'
                    WHEN 3 THEN 'REPEATABLE READ'
                    WHEN 4 THEN 'SERIALIZABLE'
                    WHEN 5 THEN 'SNAPSHOT' END AS TRANSACTION_ISOLATION_LEVEL
                    FROM %s
                    where session_id = @@SPID
                  r   zQCould not fetch transaction isolation level, tried views: %s; final error was: %szACan't fetch isolation level on this particular SQL Server version)rˆ  ÚMS_2005_VERSIONÚNotImplementedErrorrL   r`   ÚfetchoneÚdbapiÚErrorr9   Úupperr
   Úwarn)rÝ   rª  Ú
last_errorÚviewsrÑ   rL   ÚvalÚerrrÚ   rÚ   rá   Úget_isolation_level`  s>   
ÿõÿ
€ùÿÿÿzMSDialect.get_isolation_levelc                    s   t t| ƒ |¡ |  ¡  d S rï   )rÛ   rº  Ú
initializeÚ_setup_version_attributes)rÝ   rª  rß   rÚ   rá   rÙ  Ž  s   zMSDialect.initializec                    s   ˆ j d ur‡ fdd„}|S d S )Nc                    s   ˆ   | ˆ j¡ d S rï   )rÌ  rÀ  )r¹  r  rÚ   rá   Úconnect•  ru  z%MSDialect.on_connect.<locals>.connect)rÀ  )rÝ   rÛ  rÚ   r  rá   Ú
on_connect’  s   
zMSDialect.on_connectc                 C   s€   | j d ttddƒƒvrt dd dd„ | j D ƒ¡ ¡ | j tkr)d| jvr)d	| _| j t	kr1d	| _
| jd u r>| j tk| _d S d S )
Nr   r%   é   z[Unrecognized server version info '%s'.  Some SQL Server features may not function properly.r²  c                 s   s   � | ]}t |ƒV  qd S rï   )rf  r  rÚ   rÚ   rá   rQ  ¡  s   € z6MSDialect._setup_version_attributes.<locals>.<genexpr>Úimplicit_returningT)rˆ  ÚlistÚranger
   rÓ  r~   rÍ  Ú__dict__rÞ  r‰  Úsupports_multivalues_insertrw  ÚMS_2012_VERSIONr  rÚ   rÚ   rá   rÚ  œ  s   þÿ



ÿÿz#MSDialect._setup_version_attributesc                 C   s<   | j tk r| jS t d¡}| |¡}|d urt |¡S | jS )NzSELECT schema_name())rˆ  rÍ  r¾  r   rH  r°  r
   Ú	text_type)rÝ   rª  Úqueryr³  rÚ   rÚ   rá   Ú_get_default_schema_name¯  s   



z"MSDialect._get_default_schema_namec           
      C   sN   t j}|jj|k}|rt ||jj|k¡}t |g|¡}| |¡}	|	 	¡ d uS rï   )
Úischemar=  r_  Ú
table_namer   Úand_Útable_schemarµ   r`   Úfirst)
rÝ   rª  r®  r   r¡  r   r=  Úwhereclauserñ  r_  rÚ   rÚ   rá   Ú	has_tableº  s   ÿ
zMSDialect.has_tablec                 K   s6   t jtjjjgtjjjgd�}dd„ | |¡D ƒ}|S )Nrþ  c                 S   ó   g | ]}|d  ‘qS r  rÚ   ©r  ÚrrÚ   rÚ   rá   r  Î  ó    z.MSDialect.get_schema_names.<locals>.<listcomp>)r   rµ   rç  Úschematar_  r¾  r`   )rÝ   rª  rÞ   rñ  Úschema_namesrÚ   rÚ   rá   Úget_schema_namesÈ  s   

þzMSDialect.get_schema_namesc           	      K   óR   t j}tj|jjgt |jj|k|jjdk¡|jjgd�}dd„ | 	|¡D ƒ}|S )Nz
BASE TABLErþ  c                 S   rî  r  rÚ   rï  rÚ   rÚ   rá   r  Ý  rñ  z-MSDialect.get_table_names.<locals>.<listcomp>©
rç  Útablesr   rµ   r_  rè  ré  rê  Ú
table_typer`   )	rÝ   rª  r   r¡  r   rÞ   r÷  rñ  Útable_namesrÚ   rÚ   rá   Úget_table_namesÑ  s   

þúzMSDialect.get_table_namesc           	      K   rõ  )NÚVIEWrþ  c                 S   rî  r  rÚ   rï  rÚ   rÚ   rá   r  ë  rñ  z,MSDialect.get_view_names.<locals>.<listcomp>rö  )	rÝ   rª  r   r¡  r   rÞ   r÷  rñ  Ú
view_namesrÚ   rÚ   rá   Úget_view_namesà  s   ÿûzMSDialect.get_view_namesc           
      K   s  | j tk rg S | t d¡ t d|tjdd�¡t d|tjdd�¡¡j	t 
¡ d�¡}i }|D ]}	|	d |	d d	kg d
œ||	d < q/| t d¡ t d|tjdd�¡t d|tjdd�¡¡j	t 
¡ d�¡}|D ]}	|	d |v r}||	d  d  |	d ¡ qht| ¡ ƒS )Na  select ind.index_id, ind.is_unique, ind.name from sys.indexes as ind join sys.tables as tab on ind.object_id=tab.object_id join sys.schemas as sch on sch.schema_id=tab.schema_id where tab.name = :tabname and sch.name=:schname and ind.is_primary_key=0 and ind.type != 0ÚtabnameT©Úconvert_unicodeÚschname©r  r  Ú	is_uniquer   )r  rÉ   Úcolumn_namesÚindex_idaR  select ind_col.index_id, ind_col.object_id, col.name from sys.columns as col join sys.tables as tab on tab.object_id=col.object_id join sys.index_columns as ind_col on (ind_col.column_id=col.column_id and ind_col.object_id=tab.object_id) join sys.schemas as sch on sch.schema_id=tab.schema_id where tab.name=:tabname and sch.name=:schnamer  )rˆ  rÍ  r`   r   rH  Ú
bindparamsÚ	bindparamÚsqltypesÚStringr=  ÚUnicoderµ  rß  rÏ   )
rÝ   rª  r®  r   r¡  r   rÞ   ÚrpÚindexesrº  rÚ   rÚ   rá   Úget_indexesî  sV   
ÿ	ÿÿüïÿ
ýÿÿÿüíÿ€zMSDialect.get_indexesc           	      K   sP   |  t d¡ t d|tjdd�¡t d|tjdd�¡¡¡}|r&| ¡ }|S d S )NzÊselect definition from sys.sql_modules as mod, sys.views as views, sys.schemas as sch where mod.object_id=views.object_id and views.schema_id=sch.schema_id and views.name=:viewname and sch.name=:schnameÚviewnameTrÿ  r  )r`   r   rH  r  r  r  r	  r°  )	rÝ   rª  r  r   r¡  r   rÞ   r  Úview_defrÚ   rÚ   rá   Úget_view_definition-	  s"   ÿÿÿü÷þzMSDialect.get_view_definitionc              
   K   s²  t j}|rt |jj|k|jj|k¡}n|jj|k}tj|g||jjgd�}	| 	|	¡}
g }	 |
 
¡ }|d u r7n“||jj ||jj ||jj dk||jj ||jj ||jj ||jj ||jj f\}}}}}}}}| j |d ¡}i }|tttttttttjf	v r’|dkrˆd }||d< |r’||d< |d u r£t  d||f ¡ tj!}nt"|tj#ƒrµ|t$urµ||d< ||d	< |di |¤Ž}||||d
dœ}| %|¡ q.i }|D ]}|||d < qÎ| 	d||f ¡}d }	 | 
¡ }|d u rìn)|d |d }}| &d¡�r||v �r|}d|| d< t'd| d�|| d< nqã| (¡  |d u�rW| j)t*k�rWd||f }| 	d||f ¡}| +¡ }|d u�rW|d d u�rW|| d  ,t-|d ƒt-|d ƒdœ¡ |S )Nrþ  TÚYESéÿÿÿÿr4  r(  z*Did not recognize type '%s' of column '%s'Úscaler�   F)r  rñ   rm  r   Úautoincrementr  z2sp_columns @table_name = '%s', @table_owner = '%s'r   é   rs   r  z%s_identityr  Úsequencer�  z)select ident_seed('%s'), ident_incr('%s')r   r   )rq  rr  rÚ   ).rç  r=  r   ré  r_  rè  rê  rµ   Úordinal_positionr`   rÏ  Úcolumn_nameÚ	data_typeÚis_nullableÚcharacter_maximum_lengthÚnumeric_precisionÚnumeric_scaleÚcolumn_defaultÚcollation_nameÚischema_namesr   ÚMSStringÚMSCharÚ
MSNVarcharÚMSNCharÚMSTextÚMSNTextÚMSBinaryÚMSVarBinaryr  ÚLargeBinaryr
   rÓ  ÚNULLTYPEre  ÚNumericÚMSRealrµ  ÚendswithÚdictr9   rˆ  rÍ  rë  rË   r  )rÝ   rª  r®  r   r¡  r   rÞ   r=  rì  rñ  r_  Úcolsrº  r  rb  rm  ÚcharlenÚnumericprecÚnumericscaler   r(  r  r  ÚcdictÚcolmapr  rL   ÚicÚcol_nameÚ	type_nameÚtable_fullnamerÚ   rÚ   rá   Úget_columnsI	  sÚ   

þÿ







ø÷÷ÿÿ
ÿû
¿CÿÿÿõÿÿÿzMSDialect.get_columnsc              
   K   sÀ   g }t j}t j d¡}	t |	jj|jj|	jj	gt 
|jj	|	jj	k|jj|	jjk|	jj|k|	jj|k¡¡}
| |
¡}d }|D ]}d||jjj v rZ| |d ¡ |d u rZ||	jj	j }q=||dœS )NÚCÚPRIMARYr   )Úconstrained_columnsr  )rç  ÚconstraintsÚkey_constraintsr  r   rµ   r_  r  Úconstraint_typeÚconstraint_nameré  rê  rè  r`   r  rµ  )rÝ   rª  r®  r   r¡  r   rÞ   ÚpkeysÚTCr:  rñ  r_  r@  rº  rÚ   rÚ   rá   Úget_pk_constraintÃ	  s*   

üþ
	€
zMSDialect.get_pk_constraintc                 K   s�  t j}t j d¡}t j d¡}	tj|jj|	jj|	jj	|	jj|jj
|jj|jj|jjgt |jj	|k|jj|k|jj|jjk|jj
|jj
k|	jj
|jjk|	jj|jjk|jj|	jjk¡|jj
|	jjgd�}
g }d g g }}}dd„ }t |¡}| |
¡ ¡ D ]C}|\}}}}}}}}|| }||d< |d s®||d< |d us¢||kr®|rª|d | }||d	< |d
 |d }}| |¡ | |¡ q~t| ¡ ƒS )Nr:  ÚRrþ  c                   S   s   d g d d g dœS )N)r  r<  Úreferred_schemaÚreferred_tableÚreferred_columnsrÚ   rÚ   rÚ   rÚ   rá   Úfkey_rec
  s   ûz,MSDialect.get_foreign_keys.<locals>.fkey_recr  rF  r²  rE  r<  rG  )rç  Úref_constraintsr>  r  r   rµ   r_  r  rê  rè  r@  Úmatch_optionÚupdate_ruleÚdelete_ruleré  Úconstraint_schemaÚunique_constraint_nameÚunique_constraint_schemar  r
   Údefaultdictr`   r³  rµ  rß  rÏ   )rÝ   rª  r®  r   r¡  r   rÞ   ÚRRr:  rD  rñ  ÚfkeysÚfknmÚscolsÚrcolsrH  rð  ÚscolÚrschemaÚrtblÚrcolÚrfknmÚfkmatchÚfkupruleÚ	fkdelruleÚrecÚ
local_colsÚremote_colsrÚ   rÚ   rá   Úget_foreign_keysß	  sX   ø


ù	ì
	þ
zMSDialect.get_foreign_keys)NTNr¼  NNF)Erã   rä   rå   r  Úsupports_default_valuesÚsupports_empty_insertr™  Úexecution_ctx_clsr²  r¿  r¾  r  ÚDateTimer!  ÚDaterì   ÚTimer  Úcolspecsr   ÚDefaultDialectÚengine_config_typesrÈ   r
   Úasboolr   Úsupports_native_booleanÚ#non_native_boolean_check_constraintÚsupports_unicode_bindsÚpostfetch_lastrowidrˆ  rÂ  Ústatement_compilerri  Úddl_compilerr[  rl  r–  r&  ro  ÚPrimaryKeyConstraintÚUniqueConstraintÚIndexÚconstruct_argumentsrÜ   rÂ  rÄ  r·   rÉ  rÌ  rØ  rÙ  rÜ  rÚ  ræ  r¯  rí  r   Úcacherô  r­  rú  rý  r  r  r9  rC  ra  rç   rÚ   rÚ   rß   rá   rº  ÿ  s’    ý
ÿýøÿ
.


=xrº  )ur*  r/  rò   rà  r  rê  r   rç  r   r   r   ro  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   ÚMS_2016_VERSIONÚMS_2014_VERSIONrã  r‰  rÍ  ÚMS_2000_VERSIONr·   r¤  rØ   ÚIntegerré   rf  rì   r  Ú_MSTimeÚobjectr   re  r!  r"  r#  Ú
TypeEnginer$  r'  Ú_Binaryr+  r6  ÚUnicodeTextr8  r9  r)  r:  ÚTextr;  r<  r=  r>  r?  r@  Ú
MSDateTimeÚMSDater,  ÚMSTinyIntegerÚMSTimeÚMSSmallDateTimeÚMSDateTime2ÚMSDateTimeOffsetr%  r&  r!  r#  r"  r$  r'  r(  ÚMSImageÚMSBitÚMSMoneyÚMSSmallMoneyÚMSUniqueIdentifierÚ	MSVariantr   ÚGenericTypeCompilerr[  ÚDefaultExecutionContextr™  rï  rÂ  r^  ÚDDLCompilerri  ÚIdentifierPreparerr–  r­  r¯  r©  r¨  rž  ri  rº  rÚ   rÚ   rÚ   rá   Ú<module>   s:      Xÿ ;	
&	/ÿþýüûúùø	÷
öõôóòñðïâ"    =/ 	