VgGOdZddlZddlZddlZddlZddlmZddlmZddlmZddlm Z ddlm Z d d l m Z d d l m Zd d l mZd d lmZGddeZGddeejZGddeejZGddeZGddeZGddee ZGddeeZGdde ZGddeeZeZdS) a .. dialect:: mssql+pyodbc :name: PyODBC :dbapi: pyodbc :connectstring: mssql+pyodbc://:@ :url: http://pypi.python.org/pypi/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`` (e.g., ``authentication=ActiveDirectoryIntegrated``). Note that in order for the dialect to recognize these keywords (including the ``driver`` keyword above) they must be all lowercase. Pass through exact Pyodbc string ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A PyODBC connection string can also be sent in pyodbc's format directly, as specified in `ConnectionStrings `_ into the driver using the parameter ``odbc_connect``. The delimeters must be URL encoded, as illustrated below using ``urllib.parse.quote_plus``:: import urllib params = urllib.parse.quote_plus("DRIVER={SQL Server Native Client 10.0};SERVER=dagger;DATABASE=test;UID=user;PWD=password") engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params) 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 N)BINARY)DATETIMEOFFSET) MSDialect)MSExecutionContext) VARBINARY)exc)types)util)PyODBCConnectorc.eZdZdZfdZdZdZxZS)_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. cztt||jsSfd}|S)Ncjrdt|tjrJ|}|dkr|S|dkr|Sr |S|S)Nr) asdecimal isinstancedecimalDecimaladjusted_small_dec_to_string_large_dec_to_string)valuerself super_processs t/builddir/build/BUILD/cloudlinux-venv-1.0.10/venv/lib64/python3.11/site-packages/sqlalchemy/dialects/mssql/pyodbc.pyprocessz2_ms_numeric_pyodbc.bind_processor..processs~ <*UGO"D"D < >>++a<<44U;;;\\44U;;; $}U+++ )superrbind_processor_need_decimal_fix)rdialectrr __class__s` @rr!z!_ms_numeric_pyodbc.bind_processorsY0$77FFwOO ( !       rc|dkrdpdddt|dz zdd|dDS)Nr-z0.0rc,g|]}t|Sstr).0nints r z;_ms_numeric_pyodbc._small_dec_to_string..s???4SYY???r)absrjoinas_tuple)rrs rrz'_ms_numeric_pyodbc._small_dec_to_stringsu QY 3 $" $ $ 3u~~''((1, - - GG??5>>+;+;A+>??? @ @ @  rc|d}dt|vrV|dkrdpddd|Dd|t |dz z z}nt |dz |kr|dkrdpddd|Dd|dzd dd |D|dzd}nH|dkrdpddd |Dd|dz}|S) NrErr&r'c,g|]}t|Sr*r+r-ss rr/z;_ms_numeric_pyodbc._large_dec_to_string..s...AQ...rr(c,g|]}t|Sr*r+r6s rr/z;_ms_numeric_pyodbc._large_dec_to_string..222SVV222r.c,g|]}t|Sr*r+r6s rr/z;_ms_numeric_pyodbc._large_dec_to_string..r9rc,g|]}t|Sr*r+r6s rr/z;_ms_numeric_pyodbc._large_dec_to_string..r9r)r2r,r1rlen)rr_intresults rrz'_ms_numeric_pyodbc._large_dec_to_strings~~" #e**  "s(b(.....///u~~''3t99q=9::FF D A !1!111QY&3,",GG22T2221u~~7G7G!7K3KLMMMMGG22T2225>>3C3Ca3G3I3IJKKKQY&3,",GG22T2221u~~7G7G!7K3KLMMM r)__name__ __module__ __qualname____doc__r!rr __classcell__r$s@rrrs`2   rrceZdZdS)_MSNumeric_pyodbcNr@rArBr*rrrGrGDrrGceZdZdS)_MSFloat_pyodbcNrHr*rrrKrKrIrrKceZdZdZdZdS)_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@jdSjjfd}|S)Nc6| |SjjSN)dbapi BinaryNull)r DBAPIBinaryr#s rrz1_ms_binary_pyodbc.bind_processor..processs& "{5)))}//r)rQBinary)rr#rrSs ` @rr!z _ms_binary_pyodbc.bind_processors@ = 4m*  0 0 0 0 0 0rN)r@rArBrCr!r*rrrMrMs-     rrMceZdZdZdS)_ODBCDateTimeOffsetc d}|S)Nc|dSt|tjr|S|d}t jdd|}|S)Nz%Y-%m-%d %H:%M:%S.%f %zz([\+\-]\d{2})([\d\.]+)$z\1:\2)rr string_typesstrftimeresub)r dto_strings rrz3_ODBCDateTimeOffset.bind_processor..process s\}tE4#455 " #^^,EFF  V.* "!rr*)rr#rs rr!z"_ODBCDateTimeOffset.bind_processor s " " ""rN)r@rArBr!r*rrrVrV s#rrVceZdZdS)_VARBINARY_pyodbcNrHr*rrr_r_ rIrr_ceZdZdS)_BINARY_pyodbcNrHr*rrrara$rIrrac,eZdZdZfdZfdZxZS)MSExecutionContext_pyodbcFctt||jr?|jjr5t |jdrd|_|xj dz c_ dSdSdSdS)awhere appropriate, issue "select scope_identity()" in the same statement. Background on why "scope_identity()" is preferable to "@@identity": http://msdn.microsoft.com/en-us/library/ms190315.aspx Background on why we attempt to embed "scope_identity()" into the same statement as the INSERT: http://code.google.com/p/pyodbc/wiki/FAQs#How_do_I_retrieve_autogenerated/identity_values? rTz; select scope_identity()N) r rcpre_exec_select_lastrowidr#use_scope_identityr= parameters_embedded_scope_identity statement)rr$s rrez"MSExecutionContext_pyodbc.pre_exec+s '..77999  " : / :DOA&'' : -1D ) NN9 9NNNN : : : : : :rcH|jrr |jd}n4#|jjj$r|jYnwxYwUt|d|_dStt| dS)NTr) ricursorfetchallr#rQErrornextsetint _lastrowidr rc post_exec)rrowr$s rrrz#MSExecutionContext_pyodbc.post_execEs  ( ? **+..003C|)/***K'')))))* *"#a&kkDOOO +T 2 2 < < > > > > >s+-AA)r@rArBrirerrrDrEs@rrcrc(sW$:::::4?????????rrcceZdZdZeZejej e j e e j eeeeeeee jee jeiZ d fd ZfdZfdZdZd fd ZfdZxZS) MSDialect_pyodbcFNc 4d|vr|d|_tt|jdi||jo |jot|jjd|_|jo| dk|_ ||_ dS)Ndescription_encodingro)rr*) poprwr ru__init__rgrQhasattrCursor_dbapi_versionr"fast_executemany)rrwrparamsr$s rr{zMSDialect_pyodbc.__init__qs "V + +(. 3I(J(JD %.%%.88888  # 6  6 )955  "&" 0C0C0E0EI 1  !1rc |d}g}tjd}||D]5} |t |&#t $rY2wxYwt|S#tj $r-tt| |dcYSwxYw)Nz8SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)z[.\-]F) allow_chars) scalarr[compilesplitappendrp ValueErrortupler DBAPIErrorr ru_get_server_version_info)r connectionrawversionrnr$s rrz)MSDialect_pyodbc._get_server_version_infos "##JCG 8$$AWWS\\  NN3q66****!D>> !~   )400IIJ     s#B"A)) A65A69CCcfttfd}|S)NcL ||dSrP)_setup_timestampoffset_type)connrsuper_s r on_connectz/MSDialect_pyodbc.on_connect..on_connects0!t  , ,T 2 2 2 2 2r)r rur)rrrr$s` @rrzMSDialect_pyodbc.on_connectsG'..99;; 3 3 3 3 3 3 rc<d}d}|||dS)Nc tjd|}tj|d|d|d|d|d|d|dd ztjtj|d |d  S) Nz<6hI2hrrrxr irry)hoursminutes)structunpackdatetimer timezone timedelta) dto_valuetups r_handle_datetimeoffsetzLMSDialect_pyodbc._setup_timestampoffset_type.._handle_datetimeoffsets-)44C$AAAAAAA$ &SVSVDDD   rie)add_output_converter)rrrodbc_SQL_SS_TIMESTAMPOFFSETs rrz,MSDialect_pyodbc._setup_timestampoffset_typesA   '+#'' ')?     rc||jrd|_tt|||||dS)NT)context)rr rudo_executemany)rrlrjrhrr$s rrzMSDialect_pyodbc.do_executemanysQ   +&*F # %%44 Iz7 5     rct||jjr|jd}|dvrdSt t ||||S)Nr> 010000100208001080030800708S0108S0210054HY010HYT00T)rrQrnargsr ru is_disconnect)rerrlcoder$s rrzMSDialect_pyodbc.is_disconnectsh a) * * 6!9D   t%t,,:: z6   r)NFrP)r@rArB supports_sane_rowcount_returningrcexecution_ctx_clsr update_copyrcolspecssqltypesNumericrGFloatrKrrarrVrr_ LargeBinaryr{rrrrrrDrEs@rruruZs(-$1t  / NO N / (   1  "3 H";@111111$"""""0        ,               rru)rCrrr[rbaserrrrrr'r r rr connectors.pyodbcr objectrrrGrrKrMrVr_rarcrur#r*rrrs~QQf  $$$$$$!!!!!!000000========@     *H,<        ((.   ..,     )9        &   /?/?/?/?/? 2/?/?/?d{ { { { {  { { { | r