U aR@sHdZddlZddlZddlZddlZddlmZddlmZddlmZddlm Z ddlm Z d d l m Z d d l m Zd d l mZd d lmZGdddeZGdddeejZGdddeejZGdddeZGdddejZGdddeZGdddee ZGdddeeZGddde ZGd d!d!eeZeZ dS)"ar% .. dialect:: mssql+pyodbc :name: PyODBC :dbapi: pyodbc :connectstring: mssql+pyodbc://:@ :url: https://pypi.org/project/pyodbc/ Connecting to PyODBC -------------------- The URL here is to be translated to PyODBC connection strings, as detailed in `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=mydsn;UID=user;PWD=pass 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=SQL+Server+Native+Client+10.0") Other keywords interpreted by the Pyodbc dialect to be passed to ``pyodbc.connect()`` in both the DSN and hostname cases include: ``odbc_autotranslate``, ``ansi``, ``unicode_results``, ``autocommit``, ``authentication``. Note that in order for the dialect to recognize these keywords (including the ``driver`` keyword above) they must be all lowercase. Multiple additional keyword arguments must be separated by an ampersand (``&``), not a semicolon:: engine = create_engine( "mssql+pyodbc://scott:tiger@myhost:port/databasename" "?driver=ODBC+Driver+17+for+SQL+Server" "&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 `_, 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 `_. 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 `_. 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"`_, stating that a connection string when using an access token must not contain ``UID``, ``PWD``, ``Authentication`` or ``Trusted_Connection`` parameters. Pyodbc Pooling / connection close behavior ------------------------------------------ PyODBC uses internal `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 `_ - 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 `_ - 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)PyODBCConnectorcs0eZdZdZfddZddZddZZS)_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. cs,tt||jsSfdd}|S)NcsRjr>t|tjr>|}|dkr,|S|dkr>|SrJ|S|SdS)Nr)Z asdecimal isinstancedecimalDecimaladjusted_small_dec_to_string_large_dec_to_string)valuerselfZ super_processaC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\dialects\mssql\pyodbc.pyprocesss  z2_ms_numeric_pyodbc.bind_processor..process)superr bind_processor_need_decimal_fixrdialectr __class__rrr s  z!_ms_numeric_pyodbc.bind_processorcCsBd|dkrdpddt|dddd|dDfS) Nz%s0.%s%sr-0rcSsg|] }t|qSrstr).0Znintrrr (sz;_ms_numeric_pyodbc._small_dec_to_string..)absrjoinas_tuple)rrrrrr$s z'_ms_numeric_pyodbc._small_dec_to_stringcCs|d}dt|krXd|dkr&dp(dddd|Dd |t|df}nt|d|krd |dkrzdp|ddd d|Dd|ddd d|D|ddf}n8d |dkrdpdddd|Dd|df}|S)NrEz%s%s%srr"r#cSsg|] }t|qSrr%r'srrrr(0sz;_ms_numeric_pyodbc._large_dec_to_string..r$z%s%s.%scSsg|] }t|qSrr%r-rrrr(7scSsg|] }t|qSrr%r-rrrr(8sz%s%scSsg|] }t|qSrr%r-rrrr(=s)r+r&r*rlen)rr_intresultrrrr+s$  """z'_ms_numeric_pyodbc._large_dec_to_string)__name__ __module__ __qualname____doc__rrr __classcell__rrr rr s r c@s eZdZdS)_MSNumeric_pyodbcNr2r3r4rrrrr7Bsr7c@s eZdZdS)_MSFloat_pyodbcNr8rrrrr9Fsr9c@seZdZdZddZdS)_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. cs(jdkrdSjjfdd}|S)Ncs|dk r|SjjSdSN)dbapiZ BinaryNull)rZ DBAPIBinaryrrrrWsz1_ms_binary_pyodbc.bind_processor..process)r<Binaryrrr=rrQs  z _ms_binary_pyodbc.bind_processorN)r2r3r4r5rrrrrr:Jsr:c@seZdZdZdZddZdS) _ODBCDateTimez6Add bind processors to handle datetimeoffset behaviorsFcsfdd}|S)NcsR|dkr dSt|tjr|S|jr.js2js2|S|d}tdd|}|SdS)Nz%Y-%m-%d %H:%M:%S.%f %zz([\+\-]\d{2})([\d\.]+)$z\1:\2) rr string_typestzinfotimezonehas_tzstrftimeresub)rZ dto_stringrrrrgs  z-_ODBCDateTime.bind_processor..processrrrrGrrfs z_ODBCDateTime.bind_processorN)r2r3r4r5rCrrrrrr?asr?c@seZdZdZdS)_ODBCDATETIMEOFFSETTN)r2r3r4rCrrrrrHsrHc@s eZdZdS)_VARBINARY_pyodbcNr8rrrrrIsrIc@s eZdZdS)_BINARY_pyodbcNr8rrrrrJsrJcs,eZdZdZfddZfddZZS)MSExecutionContext_pyodbcFcsBtt||jr>|jjr>t|jdr>d|_|j d7_ dS)awhere 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? rTz; select scope_identity()N) rrKpre_execZ_select_lastrowidruse_scope_identityr/ parameters_embedded_scope_identity statementrGr rrrLs  z"MSExecutionContext_pyodbc.pre_execcsf|jrTz|jd}WqDWq|jjjk r@|jYqXqt|d|_nt t | dS)Nr) rOcursorZfetchallrr<ErrornextsetintZ _lastrowidrrK post_exec)rrowr rrrUsz#MSExecutionContext_pyodbc.post_exec)r2r3r4rOrLrUr6rrr rrKs rKcseZdZdZdZeZee j e j e e jeeee jeeeeee jee jeiZ dfdd ZfddZfdd Zd d Zdfd d ZfddZZS)MSDialect_pyodbcTFNc s`d|kr|d|_tt|jf||jo>|jo>t|jjd|_|joR| dk|_ ||_ dS)Ndescription_encodingrS)r) poprXrrW__init__rMr<hasattrCursorZ_dbapi_versionrfast_executemany)rrXr_paramsr rrr\s  zMSDialect_pyodbc.__init__c sz|d}Wn*tjk r<tt|j|ddYSXg}td}| |D],}z| t |WqVt k rYqVXqVt |SdS)Nz8SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)F)Z allow_charsz[.\-])Zexec_driver_sqlZscalarr Z DBAPIErrorrrW_get_server_version_inforEcompilesplitappendrT ValueErrortuple)r connectionrawversionrnr rrras"    z)MSDialect_pyodbc._get_server_version_infocs ttfdd}|S)Ncsdk r||dSr;)_setup_timestampoffset_type)connrZsuper_rr on_connectsz/MSDialect_pyodbc.on_connect..on_connect)rrWro)rror rnrroszMSDialect_pyodbc.on_connectcCsdd}d}|||dS)NcSs\td|}t|d|d|d|d|d|d|dd ttj|d |d d S) Nz<6hI2hrrrYrirrZ)hoursminutes)structunpackdatetimer rB timedelta)Z dto_valuetuprrr_handle_datetimeoffsets  zLMSDialect_pyodbc._setup_timestampoffset_type.._handle_datetimeoffsetie)Zadd_output_converter)rrgrzZodbc_SQL_SS_TIMESTAMPOFFSETrrrrl s z,MSDialect_pyodbc._setup_timestampoffset_typecs(|jr d|_tt|j||||ddS)NT)context)r_rrWdo_executemany)rrQrPrNr{r rrr|#s zMSDialect_pyodbc.do_executemanycs8t||jjr$|jd}|dkr$dStt||||S)Nr> 08S01010020100010054HYT000800308S0208007HY01008001T)rr<rRargsrrW is_disconnect)rergrQcoder rrr*s   zMSDialect_pyodbc.is_disconnect)NF)N) r2r3r4Zsupports_statement_cacheZ supports_sane_rowcount_returningrKZexecution_ctx_clsr Z update_copyrZcolspecssqltypesNumericr7Floatr9rrJDateTimer?rrHrrIZ LargeBinaryr\rarorlr|rr6rrr rrWs>  rW)!r5rwrrErubaserrrrrr#r r rr Zconnectors.pyodbcr objectr rr7rr9r:rr?rHrIrJrKrWrrrrrs4l         @2