a oe@sdZdZdeZddlZddlZddlZddlZddlZddlm Z m Z m Z zeejdZWndZYn0er|eedZe jrdd lmZdd lmZmZmZmZmZmZmZd d Zd dZ nZz(ddl!Z!ddl"Z"ddl#Z$dZdd ZWn(e%yddl&Z&e&'de(Yn0ddZ ddl)m*Z*e+Z,eZ-e+Z.ej/Z0ddZ1ddZ2e j3Z4e j5Z6e 7Z8d"ddZ9ddZ:Gddde;Zd kre ?ed!dS)#aadodbapi - A python DB API 2.0 (PEP 249) interface to Microsoft ADO Copyright (C) 2002 Henrik Ekelund, versions 2.1 and later by Vernon Cole * http://sourceforge.net/projects/pywin32 * https://github.com/mhammond/pywin32 * http://sourceforge.net/projects/adodbapi This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA django adaptations and refactoring by Adam Vandenberg DB-API 2.0 specification: http://www.python.org/dev/peps/pep-0249/ This module source should run correctly in CPython versions 2.7 and later, or IronPython version 2.7 and later, or, after running through 2to3.py, CPython 3.4 or later. z2.6.2.0z adodbapi vN) ado_constsapibaseprocess_connect_stringZADODBAPI_VERBOSEF) Reference) ActivatorArrayByteDateTimeDBNullDecimalTypecCst|}t|SN)r ZGetTypeFromProgIDrZCreateInstance)dispatchtyper2C:\Program Files\Certbot\pkgs\adodbapi\adodbapi.pyDispatch?s rcCs |j|Sr)ZItemobjindexrrrgetIndexedValueCsrTcCs tj|Sr)win32comZclientr)rrrrrNsz6pywin32 package (or IronPython) required for adodbapi.cCs||SrrrrrrrXs)MappingcCs4ztrttd}WntdYn0|S)NzADODB.Connectionz7Windows COM Error: Dispatch('ADODB.Connection') failed.)onWin32 pythoncomZ CoInitializerapiInterfaceError)crrrmake_COM_connecterfs  rc Osdt}t||d}z|||WSty^}z"d|j}t||WYd}~n d}~00dS)a,Connect to a database. call using: :connection_string -- An ADODB formatted connection string, see: * http://www.connectionstrings.com * http://www.asp101.com/articles/john/connstring/default.asp :timeout -- A command timeout value, in seconds (default 30 seconds) Tz Error opening connection to "%s"N) ConnectionrZprocessconnect Exceptionconnection_stringrOperationalError)argskwargscoemessagerrrr!rs   r!cCsJz6|rdd|D}ndd|D}dd|dWSYdS0dS) zeFormat a collection of ADO Command Parameters. Used by error reporting in _execute_command. c SsJg|]B}d|jtj|jtj|jt|jd|j|j |j |j fqS)zTName: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s", Precision: %s, NumericScale: %s (unknown type)) Nameadc directions Direction adTypeNamesgetr strSizeValue Precision NumericScale.0prrr s  z%format_parameters..c SsFg|]>}d|jtj|jtj|jt|jd|j|j |j fqS)zGName: %s, Dir.: %s, Type: %s, Size: %s, Precision: %s, NumericScale: %sr*) r+r,r-r.r/r0r r1r2r4r5r6rrrr9s  [ ]z[]N)join)Z ADOparametersZ show_valuedescrrrformat_parameterss   r?cCs|tjvr"t||_||nt|trvt|}|tjvr^|rNt||j}|d||_ n||_ |dkrr||_n4t|t j rtj rt |}||_ t||_n||_ |d}t|d}||_|dkrd|_n:|dkr| |_|j|jkr|j|_nd|_|||_nt|tjvrd|rH|tjvrHt||_ nt|}||_ t||_nFtj rt|trt |}||_ n"|tjkrtj|_d|_ n||_ dS)z>Configure the given ADO Parameter 'p' with the Python 'value'.Nrr)rZadoBinaryTypeslenr2Z AppendChunk isinstance StringTypesZadoStringTypesminr3decimalr onIronPythonr1Zas_tupler4r5r dateconvertertypesZadoDateTimeTypesZCOMDateZDateObjectToIsoFormatStringlongTyper,ZadEmpty adIntegerr )r8valueadotypeZsettings_knownLsZexponentZ digit_countrrr_configure_parametersV              rOc@seZdZejZejZejZejZejZej Z ej Z ej Z ej Z ej Z ejZejZeddZddZefddZddZd d Zd d Zd dZddZddZddZddZddZddZddZddZ dd Z!d!d"Z"d#d$Z#d%d&Z$d'S)(r cCstS)z;Return a reference to the DBAPI module for this Connection.)rselfrrrdbapiszConnection.dbapicCsFd|_tj|_d|_d|_t|_d|_d|_ d|_ d|_ d|_ dS)NFr) connectorr paramstylesupportsTransactionsr#weakrefWeakValueDictionarycursors dbms_name dbms_version errorhandlertransaction_level _autocommitrPrrr__init__s zConnection.__init__c Cstdkrtdt|z|d||_Wn0tyX}z|tdWYd}~n d}~00|dd|_|dt j |_ ||_ trtdt |jf||_|j|j_|j|j_|j |j_z|jWn(tjy|tjd |jYn0z t|jjd jd krd |_Wntjy(Yn0t|jjd j|_zt|jjdj|_WntjyhYn0t|j_|jrt |j_!t"|dd|_#|j#s|j$|_%nd |_#d|vr|d|_&g|_'trtdt(|dS)N zkwargs=r#z1Python string format error in connection string->timeoutmodez%s attempting: "%s"zADO error trying to Open=%szTransaction DDLrTz DBMS Namez DBMS Version autocommitFrUzadodbapi New connection at %X))verboseprintreprr#r"_raiseConnectionErrorKeyErrorr0rar,Z adModeUnknownrcr&versionrTZConnectionTimeoutZConnectionStringZModeZOpenrError DatabaseErrorrZ Propertiesr3rV pywintypes com_errorrZr[defaultCursorLocationZCursorLocationdefaultIsolationLevelZIsolationLevelboolr^ BeginTransr]rUmessagesid)rQr&Zconnection_makerr(rrrr!"sd         zConnection.connectcCs&|j}|durtj}||d||dSr)r\rstandardErrorHandlerrQZ errorclassZ errorvalueZehrrrrh[sz Connection._raiseConnectionErrorcCsX|jdurdS|js6|jr6z|jWn Yn0|jtrTtdt|dS)zfclose the underlying ADO Connection object, rolling it back first if it supports transactions.Nz adodbapi Closed connection at %X)rTr^r] RollbackTransClosererfrtrPrrr_closeAdoConnectionas  zConnection._closeAdoConnectionc Cst|jddD]}|jddqg|_z |Wn@tyz}z(|t dt dWYd}~n d}~00d|_ dS)aEClose the connection now (rather than whenever __del__ is called). The connection will be unusable from this point forward; an Error (or subclass) exception will be raised if any operation is attempted with the connection. The same applies to all cursor objects trying to use the connection. NT) dont_tell_merr) listrYvaluesclosersryr"rhsysexc_inforT)rQcrsrr(rrrr}ps  2zConnection.closec Csg|_|jsdSzH|j|_tdkr6tdt||jsV|jj t j @sV|j |_Wn2t y}z|tj|WYd}~n d}~00dS)aHCommit any pending transaction to the database. Note that if the database supports an auto-commit feature, this must be initially off. An interface method may be provided to turn it back on. Database modules that do not support transactions should implement this method with void functionality. Nrzcommit done on connection at %X)rsrVrTZ CommitTransr]rerfrtr^ Attributesr,adXactAbortRetainingrrr"rhrProgrammingErrorrQr(rrrcommits  zConnection.commitc Csg|_|jrzN|j|_tdkr2tdt||jsX|jjt j @sX|jsX|j |_Wn2t y}z| tj|WYd}~n d}~00dS)aIn case a database does provide transactions this method causes the the database to roll back to the start of any pending transaction. Closing a connection without committing the changes first will cause an implicit rollback to be performed. If the database does not support the functionality required by the method, the interface should throw an exception in case the method is used. The preferred approach is to not implement the method and thus have Python generate an AttributeError in case the method is requested. This allows the programmer to check for database capabilities using the standard hasattr() function. For some dynamically configured interfaces it may not be appropriate to require dynamically making the method available. These interfaces should then raise a NotSupportedError to indicate the non-ability to perform the roll back when the method is invoked. rz!rollback done on connection at %XN)rsr]rTrwrerfrtr^rr,rrrr"rhrrrrrr _rollbacks  zConnection._rollbackcCs|dkr>|jr:t|dt|z |Wn Yn0dS|dkrn|tjvr|tjd|t tjfn|dkrt |}t|||dS)Nrdr^rUzparamstyle="%s" not in:%svariantConversions) rVobject __setattr__rqrrZaccepted_paramstylesrhNotSupportedErrorrgcopy)rQnamerKrrrrs*   zConnection.__setattr__cCs<|dkr|jr|jStdn|dkr,|jStd|dS)NZrollbackz,this data provider does not support Rollbackrdz2no such attribute in ADO connection object as="%s")rVrAttributeErrorr^rQitemrrr __getattr__s zConnection.__getattr__cCsg|_t|}|S)z0Return a new Cursor Object using the connection.)rsCursor)rQrrrrcursorszConnection.cursorcCst|}||j|<dS)z3message from a new cursor proclaiming its existenceN)rtrY)rQrZoidrrr _i_am_hereszConnection._i_am_herecCs"z|jt|=Wn Yn0dS)z|jjD]*}t|j}|ds2|dkrtjSqtjS)a\Introspect the current ADO Errors and determine an appropriate error class. Error.SQLState is a SQL-defined error condition, per the SQL specification: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt The 23000 class of errors are integrity errors. Error 40002 is a transactional integrity error. NZ23Z40002)rTrr1r startswithrIntegrityErrorrl)rQr(staterrr_suggest_error_class s    zConnection._suggest_error_classcCs$z |Wn Yn0d|_dSr)ryrTrPrrr__del__s  zConnection.__del__cCs|SrrrPrrr __enter__"szConnection.__enter__cCs|r|n|dSr)rrrQexc_typeZexc_valZexc_tbrrr__exit__%s zConnection.__exit__cCs>|jd}g}|js8t|jdj}|||q~|S)NZ TABLE_NAME)rTZ OpenSchemaEOFrFieldsr3appendZMoveNext)rQZschemaZtablesrrrrget_table_names+s   zConnection.get_table_namesN)%__name__ __module__ __qualname__rWarningrkr DataErrorrlr$r InternalErrorrrFetchFailedErrorrepropertyrRr_rr!rhryr}rrrrrrrrrrrrrrrrrr s@  9$r c@s&eZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ ddZdBddZddZejfddZd d!Zd"d#Zd$d%ZdCd'd(Zd)d*ZdDd+d,ZdEd-d.Zd/d0ZdFd1d2Zd3d4ZdGd5d6Zd7d8Zd9d:Z d;d<Z!dHd=d>Z"d?d@Z#e$e#d&d&dAZ%d&S)IrcCsd|_d|_g|_||_|j|_g|_d|_d|_g|_i|_ d|_ d|_ d|_ |j |_ d|_||trtdtt|t|jfdS)NFrrz%s New cursor at %X on conn %X)command _ado_preparedrs connectionrU_parameter_namesZrecordset_is_remoters converters columnNamesnumberOfColumns _descriptionrowcountr\ arraysizerrerfrjrt)rQrrrrr_Rs, zCursor.__init__cCs t|jdSr)iterfetchonerPrrr__iter__iszCursor.__iter__cCs||_d|_d|_dS)Nsetup)rrr)rQ operationrrrpreparelszCursor.preparecCs|}|r|StdSr)r StopIteration)rQrrrr__next__qszCursor.__next__cCs|S)8Allow database cursors to be used with context managers.rrPrrrrwszCursor.__enter__cCs |dS)rNr}rrrrr{szCursor.__exit__cCs(|j}|durtj}||j|||dSr)r\rrurrvrrr_raiseCursorErrorszCursor._raiseCursorErrorc Csg|_i|_d|_|dus&|jtjkr6d|_d|_dS||_tj rHtj ntj |_ |j j|_z |jj}Wnty~tj}Yn0t|jD]`}t|jj |}z|j||jWn&ty|tjd|jYn0||j|j<qdS)Nrz"Data column of Unknown ADO type=%s)rrrStater, adStateClosedrrrrFRS_ARRAYZ RS_WIN_32recordset_formatrrrrrrangerrr rirrr+lower)rQ recordsetZvarConifrrrbuild_column_infos2      zCursor.build_column_infoc Cs|jdurd|_dSg}t|jD]`}t|jj|}|jjsD|jjrJd}n|j}t |j t j @}| |j|j||j|j|j|fq"||_dSr)rrrrrrrBOFZ ActualSizerqrr,ZadFldMayBeNullrr+r Z DefinedSizer4r5)rQr>rrZ display_sizeZnull_okrrr_makeDescriptionFromRSs,  zCursor._makeDescriptionFromRScCs|js||jSr)rrrPrrrget_descriptionszCursor.get_descriptioncCs |dkr|St||dS)N description)rr__getattribute__rrrrrs zCursor.__getattr__c Csr|jdur|t|tr&|j|}d|dtj|dt|dd|d|d|d|d |d f}|S) z-Format db_api description tuple for printing.NzQName= %s, Type= %s, DispSize= %s, IntSize= %s, Precision= %s, Scale= %s NullOK=%srrr*r@)rrrBintr,r/r0r1)rQdr>rrrformat_descriptions     zCursor.format_descriptionFcCsf|jdurdSg|_|jr8|jjtjkr8|jd|_|sH|j|d|_trbt dt |dS)zClose the cursor now (rather than whenever __del__ is called). The cursor will be unusable from this point forward; an Error (or subclass) exception will be raised if any operation is attempted with the cursor. Nzadodbapi Closed cursor at %X) rrsrrr,rrxrrerfrt)rQrzrrrr}s"   z Cursor.closecCsz |Wn Yn0dSrrrPrrrrs zCursor.__del__c Csd|_g|_|jdur(|tjddSzFtd|_|jj|j_|jj |j_ ||j_ |j |j_ t|j|j_Wn$|tjdt|j Yn0dS)Nz ADODB.Commandz0Error creating new ADODB.Command object for "%s")cmdrsrrrrrrTZActiveConnectionraZCommandTimeoutZ CommandType commandTextZ CommandTextrqrZPreparedrlrg)rQ command_typerrr _new_commands&     zCursor._new_commandc Csd|_d}d}tr td|jz6tjrFtt}|j |}|j }n|j \}}Wnvt y}z^d}t |dr|t |jd7}|d|jt|jjdf7}|j}|||WYd}~n d}~00z |j|_Wn||_Yn0||dS)NrzExecuting command="%s"rSr%r;zCommand: %s Parameters: %sT) return_valuererfrrrFrrrZExecuter3r"hasattrr1r%r? ParametersrrrZ RecordCountrr)rQrcountZrar(_messageklassrrr_execute_commands4     "  zCursor._execute_commandcCs|jSr)rrPrrr get_rowcount7szCursor.get_rowcountc Csg}t|jjD]}tdkr^td|jtj|jtj |j t |j d|j |j|j|jft|jtj|j }|jtjkr||_||_q||q|S)awith some providers, returned parameters and the .return_value are not available until after the last recordset has been read. In that case, you must coll nextset() until it returns None, then call this method to get your returned information.r@z]Returned=Name: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s", Precision: %s, NumericScale: %sr*)tuplerrrerfr+r,r-r.r/r0r r1r2r3r4r5rZconvert_to_pythonradParamReturnValueZ returnValuerr)rQZretLstr8ZpyObjectrrrget_returned_parameters:s.    zCursor.get_returned_parametersNcCsTg|_||_|jtjd|j|ddtdkrDtdt|j j d| | S)atCall a stored database procedure with the given name. The sequence of parameters must contain one entry for each argument that the sproc expects. The result of the call is returned as modified copy of the input sequence. Input parameters are left untouched, output and input/output parameters replaced with possibly new values. The sproc may also provide a result set as output, which is available through the standard .fetch*() methods. Extension: A "return_value" property may be set on the cursor if the sproc defines an integer return value. )rT)sprocr@z Calling Stored Proc with Params=) rrrr,ZadCmdStoredProc_buildADOparameterListrerfr?rrrr)rQZprocname parametersrrrcallproc[s  zCursor.callproccCsN|jdvrt|\}|_n.|jdks:|jdkrJt|trJt|\}|_|S)N)formatZpyformatZnamedZdynamic)rUrZchangeFormatToQmarkrrBrZchangeNamedToQmarkrQrrrrr_reformat_operationts   zCursor._reformat_operationc Cs||_|durg}d}|rz>|jjtdkrRtdt|jjdtdt|d}Wn tj yxtrttdYn00t ||jjj dkrt d|jjj d|s|gkrd }|r.|j rlt|j D]\}}t|jj|}zt||||j|Wqtyf}zLd |jt|j|jt||f}|tj|d t|jWYd}~qd}~00qn|D]} t|jj|}|jtjkr|d7}t|jj|}zt|| |j|Wnbty}zHd |jt|j|jt| f}|tj|d t|jWYd}~n d}~00|d7}qpn|j r|j D]} || } t| } |j| | tj}t|| | |z|jj|Wnbty}zHd |jt|j|jt| f}|tj|d t|jWYd}~n d}~00qz*Error Building Parameter %s: %s, %s <- %s z @RETURN_VALUEzp%ir)"rrrZRefreshrerfr?rgrrkrArrr enumeraterrOr r"r+r,Z ado_type_namer3rrr%r.rZpyTypeToADOTypeZCreateParameterZ adParamInputZAppendrJr)rQrrZparameters_knownrZpm_namer8r(rrKZ parm_nameelemrLrrrrrs                  zCursor._buildADOparameterListcCs|j|us|jdkst|dsZ|j|ur4d|_||_g|_|jdksH|sL|n ||||_|||t dkrt dt |j j d|dS) aPrepare and execute a database operation (query or command). Parameters may be provided as sequence or mapping and will be bound to variables in the operation. Variables are specified in a database-specific notation (see the module's paramstyle attribute for details). [5] A reference to the operation will be retained by the cursor. If the same operation object is passed in again, then the cursor can optimize its behavior. This is most effective for algorithms where the same operation is used, but different parameters are bound to it (many times). For maximum efficiency when reusing an operation, it is best to use the setinputsizes() method to specify the parameter types and sizes ahead of time. It is legal for a parameter to not match the predefined information; the implementation should compensate, possibly with a loss of efficiency. The parameters may also be specified as list of tuples to e.g. insert multiple rows in a single operation, but this kind of usage is depreciated: executemany() should be used instead. Return value is not defined. [5] The module will use the __getitem__ method of the parameters object to map either positions (integers) or names (strings) to parameter values. This allows for both sequences and mappings to be used as input. The term "bound" refers to the process of binding an input value to a database execution buffer. In practical terms, this means that the input value is directly used as a value in the operation. The client should not be required to "escape" the value so that it can be used -- the value should be equal to the actual database value.rrFZqmarkrzParams=TN)rrrrrUrrrrrerfr?rrrrrrrexecutes*   zCursor.executecCsXt|_d}|||D]2}||j||jdkr:d}|dkr||j7}q||_dS)zPrepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters. Return values are not defined. rrN)r{rsrrrr)rQrZseq_of_parametersZtotal_recordcountparamsrrr executemany0s   zCursor.executemanycCs|jdus|jdur&|tjddS|jjtjksD|jjsD|jj rJt S|r\|j |}n |j }|j tj krt||j}n t|d}t|||}|S)zFetch rows from the current recordset. limit -- Number of rows to fetch, or None (default) to fetch all rows. Nz/fetch() on closed connection or empty query setr)rrrrrrr,rrrr{ZGetRowsrrrArZSQLrows)rQlimitZ ado_resultslengthZ fetchObjectrrr_fetchBs&    z Cursor._fetchcCs g|_|d}|r|dSdS)aFetch the next row of a query result set, returning a single sequence, or None when no more data is available. An Error (or subclass) exception is raised if the previous call to executeXXX() did not produce any result set or no call was issued yet. rrNrsr)rQresultrrrr`s  zCursor.fetchonecCsg|_|dur|j}||S)aFetch the next set of rows of a query result, returning a list of tuples. An empty sequence is returned when no more rows are available. The number of rows to fetch per call is specified by the parameter. If it is not given, the cursor's arraysize determines the number of rows to be fetched. The method should try to fetch as many rows as indicated by the size parameter. If this is not possible due to the specified number of rows not being available, fewer rows may be returned. An Error (or subclass) exception is raised if the previous call to executeXXX() did not produce any result set or no call was issued yet. Note there are performance considerations involved with the size parameter. For optimal performance, it is usually best to use the arraysize attribute. If the size parameter is used, then it is best for it to retain the same value from one fetchmany() call to the next. N)rsrr)rQsizerrr fetchmanymszCursor.fetchmanycCsg|_|S)a}Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). Note that the cursor's arraysize attribute can affect the performance of this operation. An Error (or subclass) exception is raised if the previous call to executeXXX() did not produce any result set or no call was issued yet. rrPrrrfetchallszCursor.fetchallc Csg|_|jdus|jdur,|tjddStjrz|j}WqtyVd}Yqtj y}z|tj |j WYd}~qd}~00nNz|j}Wn6t j y}z|tj |j WYd}~n d}~00|d}|durdS||dS)aSkip to the next available recordset, discarding any remaining rows from the current recordset. If there are no more sets, the method returns None. Otherwise, it returns a true value and subsequent calls to the fetch methods will return rows from the next result set. An Error (or subclass) exception is raised if the previous call to executeXXX() did not produce any result set or no call was issued yet. Nz1nextset() on closed connection or empty query setrT)rsrrrrr$rFZ NextRecordset TypeErrorrkrr%rmrnr)rQrexcZrsTuplerrrnextsets2  ( zCursor.nextsetcCsdSrr)rQZsizesrrr setinputsizesszCursor.setinputsizescCsdSrr)rQrcolumnrrr setoutputsizeszCursor.setoutputsizecCs@z*|jdkr|j}nd|jt|jf}Wnd}Yn0|S)Nz%s,parameters=%s)rrrg)rQretrrr _last_querys  zCursor._last_queryzreturns the last query executed)F)N)F)N)N)N)N)&rrrr_rrrrrrrrrrrr}rr,Z adCmdTextrrrrrrrrrrrrrrrrr rqueryrrrrr8sB '!   0   %  r__main__z! cannot be run as a main program.)F)@__doc__ __version__rjrrEosr~rWrSrr,rrrrenvironrerfrrFZclrrZSystemrrr r r r Z SystemDecimalr rrrrmZwin32com.clientr ImportErrorwarningswarn ImportWarningcollections.abcrr1Z unicodeTyperIrCmaxsizeZmaxintrr!ZadXactReadCommittedrpZ adUseClientroZpythonDateTimeConverterrGr?rOrr rrrrrrrsn  $       &?9