
    +h_                        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  G d de      Z G d deej(                        Z G d deej,                        Z G d de      Z G d de      Z G d deej4                        Z G d dee      Z G d dee
      Z G d dee      Z G d  d!e	      Z G d" d#ee      Z e Z!y)$a3  
.. dialect:: mssql+pyodbc
    :name: PyODBC
    :dbapi: pyodbc
    :connectstring: mssql+pyodbc://<username>:<password>@<dsnname>
    :url: https://pypi.org/project/pyodbc/

Connecting to PyODBC
--------------------

The URL here is to be translated to PyODBC connection strings, as
detailed in `ConnectionStrings <https://code.google.com/p/pyodbc/wiki/ConnectionStrings>`_.

DSN Connections
^^^^^^^^^^^^^^^

A DSN connection in ODBC means that a pre-existing ODBC datasource is
configured on the client machine.   The application then specifies the name
of this datasource, which encompasses details such as the specific ODBC driver
in use as well as the network address of the database.   Assuming a datasource
is configured on the client, a basic DSN-based connection looks like::

    engine = create_engine("mssql+pyodbc://scott:tiger@some_dsn")

Which above, will pass the following connection string to PyODBC::

    DSN=some_dsn;UID=scott;PWD=tiger

If the username and password are omitted, the DSN form will also add
the ``Trusted_Connection=yes`` directive to the ODBC string.

Hostname Connections
^^^^^^^^^^^^^^^^^^^^

Hostname-based connections are also supported by pyodbc.  These are often
easier to use than a DSN and have the additional advantage that the specific
database name to connect towards may be specified locally in the URL, rather
than it being fixed as part of a datasource configuration.

When using a hostname connection, the driver name must also be specified in the
query parameters of the URL.  As these names usually have spaces in them, the
name must be URL encoded which means using plus signs for spaces::

    engine = create_engine("mssql+pyodbc://scott:tiger@myhost:port/databasename?driver=ODBC+Driver+17+for+SQL+Server")

The ``driver`` keyword is significant to the pyodbc dialect and must be
specified in lowercase.

Any other names passed in the query string are passed through in the pyodbc
connect string, such as ``authentication``, ``TrustServerCertificate``, etc.
Multiple keyword arguments must be separated by an ampersand (``&``); these
will be translated to semicolons when the pyodbc connect string is generated
internally::

    e = create_engine(
        "mssql+pyodbc://scott:tiger@mssql2017:1433/test?"
        "driver=ODBC+Driver+18+for+SQL+Server&TrustServerCertificate=yes"
        "&authentication=ActiveDirectoryIntegrated"
    )

The equivalent URL can be constructed using :class:`_sa.engine.URL`::

    from sqlalchemy.engine import URL
    connection_url = URL.create(
        "mssql+pyodbc",
        username="scott",
        password="tiger",
        host="mssql2017",
        port=1433,
        database="test",
        query={
            "driver": "ODBC Driver 18 for SQL Server",
            "TrustServerCertificate": "yes",
            "authentication": "ActiveDirectoryIntegrated",
        },
    )


Pass through exact Pyodbc string
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

A PyODBC connection string can also be sent in pyodbc's format directly, as
specified in `the PyODBC documentation
<https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-databases>`_,
using the parameter ``odbc_connect``.  A :class:`_sa.engine.URL` object
can help make this easier::

    from sqlalchemy.engine import URL
    connection_string = "DRIVER={SQL Server Native Client 10.0};SERVER=dagger;DATABASE=test;UID=user;PWD=password"
    connection_url = URL.create("mssql+pyodbc", query={"odbc_connect": connection_string})

    engine = create_engine(connection_url)

.. _mssql_pyodbc_access_tokens:

Connecting to databases with access tokens
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Some database servers are set up to only accept access tokens for login. For
example, SQL Server allows the use of Azure Active Directory tokens to connect
to databases. This requires creating a credential object using the
``azure-identity`` library. More information about the authentication step can be
found in `Microsoft's documentation
<https://docs.microsoft.com/en-us/azure/developer/python/azure-sdk-authenticate?tabs=bash>`_.

After getting an engine, the credentials need to be sent to ``pyodbc.connect``
each time a connection is requested. One way to do this is to set up an event
listener on the engine that adds the credential token to the dialect's connect
call. This is discussed more generally in :ref:`engines_dynamic_tokens`. For
SQL Server in particular, this is passed as an ODBC connection attribute with
a data structure `described by Microsoft
<https://docs.microsoft.com/en-us/sql/connect/odbc/using-azure-active-directory#authenticating-with-an-access-token>`_.

The following code snippet will create an engine that connects to an Azure SQL
database using Azure credentials::

    import struct
    from sqlalchemy import create_engine, event
    from sqlalchemy.engine.url import URL
    from azure import identity

    SQL_COPT_SS_ACCESS_TOKEN = 1256  # Connection option for access tokens, as defined in msodbcsql.h
    TOKEN_URL = "https://database.windows.net/"  # The token URL for any Azure SQL database

    connection_string = "mssql+pyodbc://@my-server.database.windows.net/myDb?driver=ODBC+Driver+17+for+SQL+Server"

    engine = create_engine(connection_string)

    azure_credentials = identity.DefaultAzureCredential()

    @event.listens_for(engine, "do_connect")
    def provide_token(dialect, conn_rec, cargs, cparams):
        # remove the "Trusted_Connection" parameter that SQLAlchemy adds
        cargs[0] = cargs[0].replace(";Trusted_Connection=Yes", "")

        # create token credential
        raw_token = azure_credentials.get_token(TOKEN_URL).token.encode("utf-16-le")
        token_struct = struct.pack(f"<I{len(raw_token)}s", len(raw_token), raw_token)

        # apply it to keyword arguments
        cparams["attrs_before"] = {SQL_COPT_SS_ACCESS_TOKEN: token_struct}

.. tip::

    The ``Trusted_Connection`` token is currently added by the SQLAlchemy
    pyodbc dialect when no username or password is present.  This needs
    to be removed per Microsoft's
    `documentation for Azure access tokens
    <https://docs.microsoft.com/en-us/sql/connect/odbc/using-azure-active-directory#authenticating-with-an-access-token>`_,
    stating that a connection string when using an access token must not contain
    ``UID``, ``PWD``, ``Authentication`` or ``Trusted_Connection`` parameters.

.. _azure_synapse_ignore_no_transaction_on_rollback:

Avoiding transaction-related exceptions on Azure Synapse Analytics
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Azure Synapse Analytics has a significant difference in its transaction
handling compared to plain SQL Server; in some cases an error within a Synapse
transaction can cause it to be arbitrarily terminated on the server side, which
then causes the DBAPI ``.rollback()`` method (as well as ``.commit()``) to
fail. The issue prevents the usual DBAPI contract of allowing ``.rollback()``
to pass silently if no transaction is present as the driver does not expect
this condition. The symptom of this failure is an exception with a message
resembling 'No corresponding transaction found. (111214)' when attempting to
emit a ``.rollback()`` after an operation had a failure of some kind.

This specific case can be handled by passing ``ignore_no_transaction_on_rollback=True`` to
the SQL Server dialect via the :func:`_sa.create_engine` function as follows::

    engine = create_engine(connection_url, ignore_no_transaction_on_rollback=True)

Using the above parameter, the dialect will catch ``ProgrammingError``
exceptions raised during ``connection.rollback()`` and emit a warning
if the error message contains code ``111214``, however will not raise
an exception.

.. versionadded:: 1.4.40  Added the
   ``ignore_no_transaction_on_rollback=True`` parameter.

Enable autocommit for Azure SQL Data Warehouse (DW) connections
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Azure SQL Data Warehouse does not support transactions,
and that can cause problems with SQLAlchemy's "autobegin" (and implicit
commit/rollback) behavior. We can avoid these problems by enabling autocommit
at both the pyodbc and engine levels::

    connection_url = sa.engine.URL.create(
        "mssql+pyodbc",
        username="scott",
        password="tiger",
        host="dw.azure.example.com",
        database="mydb",
        query={
            "driver": "ODBC Driver 17 for SQL Server",
            "autocommit": "True",
        },
    )

    engine = create_engine(connection_url).execution_options(
        isolation_level="AUTOCOMMIT"
    )

Avoiding sending large string parameters as TEXT/NTEXT
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

By default, for historical reasons, Microsoft's ODBC drivers for SQL Server
send long string parameters (greater than 4000 SBCS characters or 2000 Unicode
characters) as TEXT/NTEXT values. TEXT and NTEXT have been deprecated for many
years and are starting to cause compatibility issues with newer versions of
SQL_Server/Azure. For example, see `this
issue <https://github.com/mkleehammer/pyodbc/issues/835>`_.

Starting with ODBC Driver 18 for SQL Server we can override the legacy
behavior and pass long strings as varchar(max)/nvarchar(max) using the
``LongAsMax=Yes`` connection string parameter::

    connection_url = sa.engine.URL.create(
        "mssql+pyodbc",
        username="scott",
        password="tiger",
        host="mssqlserver.example.com",
        database="mydb",
        query={
            "driver": "ODBC Driver 18 for SQL Server",
            "LongAsMax": "Yes",
        },
    )


Pyodbc Pooling / connection close behavior
------------------------------------------

PyODBC uses internal `pooling
<https://github.com/mkleehammer/pyodbc/wiki/The-pyodbc-Module#pooling>`_ by
default, which means connections will be longer lived than they are within
SQLAlchemy itself.  As SQLAlchemy has its own pooling behavior, it is often
preferable to disable this behavior.  This behavior can only be disabled
globally at the PyODBC module level, **before** any connections are made::

    import pyodbc

    pyodbc.pooling = False

    # don't use the engine before pooling is set to False
    engine = create_engine("mssql+pyodbc://user:pass@dsn")

If this variable is left at its default value of ``True``, **the application
will continue to maintain active database connections**, even when the
SQLAlchemy engine itself fully discards a connection or if the engine is
disposed.

.. seealso::

    `pooling <https://github.com/mkleehammer/pyodbc/wiki/The-pyodbc-Module#pooling>`_ -
    in the PyODBC documentation.

Driver / Unicode Support
-------------------------

PyODBC works best with Microsoft ODBC drivers, particularly in the area
of Unicode support on both Python 2 and Python 3.

Using the FreeTDS ODBC drivers on Linux or OSX with PyODBC is **not**
recommended; there have been historically many Unicode-related issues
in this area, including before Microsoft offered ODBC drivers for Linux
and OSX.   Now that Microsoft offers drivers for all platforms, for
PyODBC support these are recommended.  FreeTDS remains relevant for
non-ODBC drivers such as pymssql where it works very well.


Rowcount Support
----------------

Pyodbc only has partial support for rowcount.  See the notes at
:ref:`mssql_rowcount_versioning` for important notes when using ORM
versioning.

.. _mssql_pyodbc_fastexecutemany:

Fast Executemany Mode
---------------------

The Pyodbc driver has added support for a "fast executemany" mode of execution
which greatly reduces round trips for a DBAPI ``executemany()`` call when using
Microsoft ODBC drivers, for **limited size batches that fit in memory**.  The
feature is enabled by setting the flag ``.fast_executemany`` on the DBAPI
cursor when an executemany call is to be used.   The SQLAlchemy pyodbc SQL
Server dialect supports setting this flag automatically when the
``.fast_executemany`` flag is passed to
:func:`_sa.create_engine` ; note that the ODBC driver must be the Microsoft
driver in order to use this flag::

    engine = create_engine(
        "mssql+pyodbc://scott:tiger@mssql2017:1433/test?driver=ODBC+Driver+13+for+SQL+Server",
        fast_executemany=True)

.. warning:: The pyodbc fast_executemany mode **buffers all rows in memory** and is
   not compatible with very large batches of data.    A future version of SQLAlchemy
   may support this flag as a per-execution option instead.

.. versionadded:: 1.3

.. seealso::

    `fast executemany <https://github.com/mkleehammer/pyodbc/wiki/Features-beyond-the-DB-API#fast_executemany>`_
    - on github

.. _mssql_pyodbc_setinputsizes:

Setinputsizes Support
-----------------------

The pyodbc ``cursor.setinputsizes()`` method can be used if necessary.  To
enable this hook, pass ``use_setinputsizes=True`` to :func:`_sa.create_engine`::

    engine = create_engine("mssql+pyodbc://...", use_setinputsizes=True)

The behavior of the hook can then be customized, as may be necessary
particularly if fast_executemany is in use, via the
:meth:`.DialectEvents.do_setinputsizes` hook. See that method for usage
examples.

.. versionchanged:: 1.4.1  The pyodbc dialects will not use setinputsizes
   unless ``use_setinputsizes=True`` is passed.

    N   )BINARY)DATETIMEOFFSET)	MSDialect)MSExecutionContext)	VARBINARY   )exc)types)util)PyODBCConnectorc                   .     e Zd ZdZ fdZd Zd Z xZS )_ms_numeric_pyodbczTurns Decimals with adjusted() < 0 or > 7 into strings.

    The routines here are needed for older pyodbc versions
    as well as current mxODBC versions.

    c                 Z     t         t           |      |j                  sS  fd}|S )Nc                     j                   rVt        | t        j                        r<| j	                         }|dk  rj                  |       S |dkD  rj                  |       S r |       S | S )Nr      )	asdecimal
isinstancedecimalDecimaladjusted_small_dec_to_string_large_dec_to_string)valuer   selfsuper_processs     S/var/www/html/venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/pyodbc.pyprocessz2_ms_numeric_pyodbc.bind_processor.<locals>.processq  sf    ~~*UGOO"D >>+a<44U;;\44U;;$U++    )superr   bind_processor_need_decimal_fix)r   dialectr   r   	__class__s   `  @r   r!   z!_ms_numeric_pyodbc.bind_processorj  s0    0$FwO((  	 r   c                     |dk  xr dxs dddt        |j                               dz
  z  dj                  |j                         d   D cg c]  }t	        |       c}      S c c}w )Nr   - z0.0r   )absr   joinas_tuplestr)r   r   nints      r   r   z'_ms_numeric_pyodbc._small_dec_to_string  sf    QY3$"$3u~~'(1,-GG5>>+;A+>?4SY?@
 	
 @s   A)c                    |j                         d   }dt        |      v r[|dk  xr dxs ddj                  |D cg c]  }t        |       c}      d|j                         t	        |      dz
  z
  z  }|S t	        |      dz
  |j                         kD  r|dk  xr dxs ddj                  |D cg c]  }t        |       c}d|j                         dz          ddj                  |D cg c]  }t        |       c}|j                         dz   d        }|S |dk  xr dxs ddj                  |D cg c]  }t        |       c}d|j                         dz          }|S c c}w c c}w c c}w c c}w )Nr   Er   r&   r'   r(   .)r+   r,   r*   r   len)r   r   _intsresults        r   r   z'_ms_numeric_pyodbc._large_dec_to_string  st   ~~"#e*"s(b(.AQ./u~~'3t9q=9:F"  D	A!11QY&3,",GGT2SV21u~~7G!7KLMGGT2SV25>>3Ca3G3IJK  QY&3,",GGT2SV21u~~7G!7KLM  / 32
 3s   E2
7E7
4E<F
)__name__
__module____qualname____doc__r!   r   r   __classcell__r$   s   @r   r   r   a  s    2
r   r   c                       e Zd Zy)_MSNumeric_pyodbcNr5   r6   r7    r   r   r<   r<         r   r<   c                       e Zd Zy)_MSFloat_pyodbcNr=   r>   r   r   rA   rA     r?   r   rA   c                       e Zd ZdZd Zy)_ms_binary_pyodbczWraps binary values in dialect-specific Binary wrapper.
    If the value is null, return a pyodbc-specific BinaryNull
    object to prevent pyODBC [and FreeTDS] from defaulting binary
    NULL types to SQLWCHAR and causing implicit conversion errors.
    c                 \    j                   y j                   j                  fd}|S )Nc                 D    |  |       S j                   j                  S N)dbapi
BinaryNull)r   DBAPIBinaryr#   s    r   r   z1_ms_binary_pyodbc.bind_processor.<locals>.process  s&     "5)) }}///r   )rG   Binary)r   r#   r   rI   s    ` @r   r!   z _ms_binary_pyodbc.bind_processor  s+    == mm**	0 r   N)r5   r6   r7   r8   r!   r>   r   r   rC   rC     s    r   rC   c                       e Zd ZdZdZd Zy)_ODBCDateTimeBindProcessorz6Add bind processors to handle datetimeoffset behaviorsFc                       fd}|S )Nc                     | y t        | t        j                        r| S | j                  rj                  sj
                  s| S | j                  d      }t        j                  dd|      }|S )Nz%Y-%m-%d %H:%M:%S.%f %zz([\+\-]\d{2})([\d\.]+)$z\1:\2)	r   r   string_typestzinfotimezonehas_tzstrftimeresub)r   
dto_stringr   s     r   r   z:_ODBCDateTimeBindProcessor.bind_processor.<locals>.process  sh    }E4#4#45\\$--
 #^^,EF
  VV.*
 "!r   r>   )r   r#   r   s   `  r   r!   z)_ODBCDateTimeBindProcessor.bind_processor  s    	", r   N)r5   r6   r7   r8   rR   r!   r>   r   r   rL   rL     s    @Fr   rL   c                       e Zd Zy)_ODBCDateTimeNr=   r>   r   r   rX   rX     r?   r   rX   c                       e Zd ZdZy)_ODBCDATETIMEOFFSETTN)r5   r6   r7   rR   r>   r   r   rZ   rZ     s    Fr   rZ   c                       e Zd Zy)_VARBINARY_pyodbcNr=   r>   r   r   r\   r\     r?   r   r\   c                       e Zd Zy)_BINARY_pyodbcNr=   r>   r   r   r^   r^     r?   r   r^   c                   ,     e Zd ZdZ fdZ fdZ xZS )MSExecutionContext_pyodbcFc                     t         t        |           | j                  rM| j                  j
                  r6t        | j                  d         rd| _        | xj                  dz  c_	        yyyy)a  where appropriate, issue "select scope_identity()" in the same
        statement.

        Background on why "scope_identity()" is preferable to "@@identity":
        https://msdn.microsoft.com/en-us/library/ms190315.aspx

        Background on why we attempt to embed "scope_identity()" into the same
        statement as the INSERT:
        https://code.google.com/p/pyodbc/wiki/FAQs#How_do_I_retrieve_autogenerated/identity_values?

        r   Tz; select scope_identity()N)
r    r`   pre_exec_select_lastrowidr#   use_scope_identityr1   
parameters_embedded_scope_identity	statement)r   r$   s    r   rb   z"MSExecutionContext_pyodbc.pre_exec  sb     	'79
 ""//DOOA&',0D)NN99N	 ( 0 #r   c                 2   | j                   r4	 	 | j                  j                         d   }	 t        |d         | _        y t        t        | /          y # | j                  j                  j
                  $ r | j                  j                          Y nw xY w)Nr   )rf   cursorfetchallr#   rG   Errornextsetint
_lastrowidr    r`   	post_exec)r   rowr$   s     r   ro   z#MSExecutionContext_pyodbc.post_exec  s    (( * ++..03C "#a&kDO+T<> ||))// * KK'')* s   A =BB)r5   r6   r7   rf   rb   ro   r9   r:   s   @r   r`   r`     s    $:4? ?r   r`   c                       e Zd ZdZdZeZ ej                  e	j                  ej                  eej                  eeeej$                  eeeeeej,                  eej0                  ei      Z
	 d	 fd	Z fdZ fdZd Zd
 fd	Z fdZ xZS )MSDialect_pyodbcTFc                 <   d|v r|j                  d      | _        t        t        |   di | | j
                  xr. | j                  xr  t        | j                  j                  d      | _        | j                  xr | j                         dk  | _
        || _        y )Ndescription_encodingrl   )   r      r>   )poprt   r    rr   __init__rd   rG   hasattrCursor_dbapi_versionr"   fast_executemany)r   rt   r|   paramsr$   s       r   rx   zMSDialect_pyodbc.__init__;  s     "V+(.

3I(JD%.88## 6

6

))95 	
 "& "
0C0C0E I
 1

 !1r   c                 d   	 |j                  d      j                         }g }t        j                  d      }|j	                  |      D ]  }	 |j                  t        |              t        |      S # t        $ r Y 6w xY w# t        j                  $ r t        t        | 7  |d      cY S w xY w)Nz8SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)z[.\-]F)allow_chars)exec_driver_sqlscalarrT   compilesplitappendrm   
ValueErrortupler
   
DBAPIErrorr    rr   _get_server_version_info)r   
connectionrawversionrnr$   s         r   r   z)MSDialect_pyodbc._get_server_version_infoM  s    	" ,,Jfh  G

8$AWWS\ NN3q6*
 >! "  ~~ 	 )4I J  		s#   B A55	B B(B/.B/c                 <     t         t                   fd}|S )Nc                 <     |        j                  |        y rF   )_setup_timestampoffset_type)connr   super_s    r   
on_connectz/MSDialect_pyodbc.on_connect.<locals>.on_connecth  s    !t,,T2r   )r    rr   r   )r   r   r   r$   s   ` @r   r   zMSDialect_pyodbc.on_connecte  s     '9;	3 r   c                 2    d }d}|j                  ||       y )Nc                     t        j                  d|       }t        j                  |d   |d   |d   |d   |d   |d   |d   d	z  t        j                  t        j
                  |d
   |d                     S )Nz<6hI2hr   r   ru   r	            i  r   rv   )hoursminutes)structunpackdatetimer   rQ   	timedelta)	dto_valuetups     r   _handle_datetimeoffsetzLMSDialect_pyodbc._setup_timestampoffset_type.<locals>._handle_datetimeoffsetr  s~    --)4C$$AAAAAAA$&&SVSVD r   ie)add_output_converter)r   r   r   odbc_SQL_SS_TIMESTAMPOFFSETs       r   r   z,MSDialect_pyodbc._setup_timestampoffset_typep  s#    	 '+#''')?	
r   c                 Z    | j                   rd|_         t        t        |   ||||       y )NT)context)r|   r    rr   do_executemany)r   ri   rg   re   r   r$   s        r   r   zMSDialect_pyodbc.do_executemany  s2      &*F#4Iz7 	5 	
r   c                     t        || j                  j                        r|j                  d   }|dv ryt        t
        |   |||      S )Nr   >
   010000100208001080030800708S0108S0210054HY010HYT00T)r   rG   rk   argsr    rr   is_disconnect)r   er   ri   coder$   s        r   r   zMSDialect_pyodbc.is_disconnect  sR    a))*66!9D   %t:z6
 	
r   )NFrF   ) r5   r6   r7   supports_statement_cache supports_sane_rowcount_returningr`   execution_ctx_clsr   update_copyr   colspecssqltypesNumericr<   FloatrA   r   r^   DateTimerX   r   rZ   r   r\   LargeBinaryrx   r   r   r   r   r   r9   r:   s   @r   rr   rr   !  s    # (-$1t/NNON}/ ( 1  "3	
H& ;@1$"0	
,

 
r   rr   )"r8   r   r   rT   r   baser   r   r   r   r   r'   r
   r   r   r   connectors.pyodbcr   objectr   r   r<   r   rA   rC   rL   r   rX   rZ   r\   r^   r`   rr   r#   r>   r   r   <module>r      s   GT
   	      $   !  0= =@	*H,<,< 		((.. 	 . >	.0A0A 	4n 	)9 		& 	/? 2 /?d~
	 ~
B r   