pywin32-checkins Mailing List for Python for Windows Extensions (Page 13)
OLD project page for the Python extensions for Windows
Brought to you by:
mhammond
You can subscribe to this list here.
2003 |
Jan
|
Feb
|
Mar
|
Apr
(2) |
May
(1) |
Jun
(6) |
Jul
(50) |
Aug
(11) |
Sep
(24) |
Oct
(184) |
Nov
(118) |
Dec
(22) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2004 |
Jan
(31) |
Feb
(25) |
Mar
(34) |
Apr
(105) |
May
(49) |
Jun
(38) |
Jul
(39) |
Aug
(7) |
Sep
(98) |
Oct
(79) |
Nov
(20) |
Dec
(17) |
2005 |
Jan
(66) |
Feb
(32) |
Mar
(43) |
Apr
(30) |
May
(58) |
Jun
(30) |
Jul
(16) |
Aug
(4) |
Sep
(21) |
Oct
(42) |
Nov
(11) |
Dec
(14) |
2006 |
Jan
(42) |
Feb
(30) |
Mar
(22) |
Apr
(1) |
May
(9) |
Jun
(15) |
Jul
(20) |
Aug
(9) |
Sep
(8) |
Oct
(1) |
Nov
(9) |
Dec
(43) |
2007 |
Jan
(52) |
Feb
(45) |
Mar
(20) |
Apr
(12) |
May
(59) |
Jun
(39) |
Jul
(35) |
Aug
(31) |
Sep
(17) |
Oct
(20) |
Nov
(4) |
Dec
(4) |
2008 |
Jan
(28) |
Feb
(111) |
Mar
(4) |
Apr
(27) |
May
(40) |
Jun
(27) |
Jul
(32) |
Aug
(94) |
Sep
(87) |
Oct
(153) |
Nov
(336) |
Dec
(331) |
2009 |
Jan
(298) |
Feb
(127) |
Mar
(20) |
Apr
(8) |
May
|
Jun
(10) |
Jul
(6) |
Aug
|
Sep
(2) |
Oct
(2) |
Nov
|
Dec
(1) |
2010 |
Jan
(7) |
Feb
(1) |
Mar
|
Apr
|
May
(15) |
Jun
(4) |
Jul
(3) |
Aug
(28) |
Sep
(1) |
Oct
(19) |
Nov
(16) |
Dec
(6) |
2011 |
Jan
(2) |
Feb
(18) |
Mar
(17) |
Apr
(12) |
May
(5) |
Jun
(11) |
Jul
(7) |
Aug
(2) |
Sep
(2) |
Oct
(4) |
Nov
(4) |
Dec
|
2012 |
Jan
(6) |
Feb
(2) |
Mar
|
Apr
(8) |
May
(4) |
Jun
(3) |
Jul
(13) |
Aug
(27) |
Sep
(8) |
Oct
(9) |
Nov
(3) |
Dec
(2) |
2013 |
Jan
|
Feb
(1) |
Mar
(5) |
Apr
(10) |
May
|
Jun
(2) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(1) |
Dec
(9) |
2014 |
Jan
(2) |
Feb
(4) |
Mar
(4) |
Apr
(1) |
May
(4) |
Jun
(2) |
Jul
|
Aug
|
Sep
|
Oct
(2) |
Nov
|
Dec
(1) |
2015 |
Jan
(1) |
Feb
|
Mar
|
Apr
(6) |
May
(2) |
Jun
|
Jul
|
Aug
(1) |
Sep
|
Oct
|
Nov
|
Dec
|
2016 |
Jan
(3) |
Feb
(2) |
Mar
|
Apr
(3) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2017 |
Jan
|
Feb
|
Mar
(1) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(1) |
Oct
|
Nov
|
Dec
|
From: Mark H. <mha...@us...> - 2010-08-25 07:49:02
|
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/framework In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv28794/pythonwin/pywin/framework Modified Files: scriptutils.py Log Message: fix reload of package modules;support for 'pyw' and 'pyx' (kxroberto) Index: scriptutils.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/framework/scriptutils.py,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** scriptutils.py 6 Feb 2009 16:29:06 -0000 1.25 --- scriptutils.py 25 Aug 2010 07:48:54 -0000 1.26 *************** *** 102,108 **** # If on path, _and_ existing package of that name loaded. if IsOnPythonPath(path) and modBit in sys.modules and \ ! ( os.path.exists(os.path.join(path, '__init__.py')) or \ ! os.path.exists(os.path.join(path, '__init__.pyc')) or \ ! os.path.exists(os.path.join(path, '__init__.pyo')) \ ): modBits.reverse() --- 102,108 ---- # If on path, _and_ existing package of that name loaded. if IsOnPythonPath(path) and modBit in sys.modules and \ ! (os.path.exists(os.path.join(path, modBit, '__init__.py')) or \ ! os.path.exists(os.path.join(path, modBit, '__init__.pyc')) or \ ! os.path.exists(os.path.join(path, modBit, '__init__.pyo')) \ ): modBits.reverse() *************** *** 376,385 **** if pathName is not None: ! if os.path.splitext(pathName)[1].lower() != ".py": pathName = None if pathName is None: openFlags = win32con.OFN_OVERWRITEPROMPT|win32con.OFN_FILEMUSTEXIST ! dlg = win32ui.CreateFileDialog(1,None,None,openFlags, "Python Scripts (*.py)|*.py||") dlg.SetOFNTitle("Import Script") if dlg.DoModal()!=win32con.IDOK: --- 376,385 ---- if pathName is not None: ! if os.path.splitext(pathName)[1].lower() not in ('.py','.pyw','.pyx'): pathName = None if pathName is None: openFlags = win32con.OFN_OVERWRITEPROMPT|win32con.OFN_FILEMUSTEXIST ! dlg = win32ui.CreateFileDialog(1,None,None,openFlags, "Python Scripts (*.py;*.pyw)|*.py;*.pyw;*.pyx||") dlg.SetOFNTitle("Import Script") if dlg.DoModal()!=win32con.IDOK: *************** *** 426,429 **** --- 426,430 ---- try: exec codeObj in __main__.__dict__ + mod = sys.modules.get(modName) if bNeedReload: try: *************** *** 434,439 **** except ImportError: my_reload = reload # reload a builtin in py2k ! my_reload(sys.modules[modName]) ! win32ui.SetStatusText('Successfully ' + what + "ed module '"+modName+"'") except: _HandlePythonFailure(what) --- 435,440 ---- except ImportError: my_reload = reload # reload a builtin in py2k ! mod = my_reload(sys.modules[modName]) ! win32ui.SetStatusText('Successfully ' + what + "ed module '"+modName+"': %s" % getattr(mod,'__file__',"<unkown file>")) except: _HandlePythonFailure(what) *************** *** 515,520 **** # (eg, bScrollToTop should be false when jumping to an error line to retain the # context, but true when jumping to a method defn, where we want the full body. doc = win32ui.GetApp().OpenDocumentFile(fileName) ! if doc is None: return 0 frame = doc.GetFirstView().GetParentFrame() try: --- 516,522 ---- # (eg, bScrollToTop should be false when jumping to an error line to retain the # context, but true when jumping to a method defn, where we want the full body. + # Return the view which is editing the file, or None on error. doc = win32ui.GetApp().OpenDocumentFile(fileName) ! if doc is None: return None frame = doc.GetFirstView().GetParentFrame() try: *************** *** 539,543 **** view.LineScroll(nScroll, 0) view.SetFocus() ! return 1 def _HandlePythonFailure(what, syntaxErrorPathName = None): --- 541,545 ---- view.LineScroll(nScroll, 0) view.SetFocus() ! return view def _HandlePythonFailure(what, syntaxErrorPathName = None): |
From: Mark H. <mha...@us...> - 2010-08-25 07:49:02
|
Update of /cvsroot/pywin32/pywin32 In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv28794 Modified Files: CHANGES.txt Log Message: fix reload of package modules;support for 'pyw' and 'pyx' (kxroberto) Index: CHANGES.txt =================================================================== RCS file: /cvsroot/pywin32/pywin32/CHANGES.txt,v retrieving revision 1.55 retrieving revision 1.56 diff -C2 -d -r1.55 -r1.56 *** CHANGES.txt 25 Aug 2010 07:37:02 -0000 1.55 --- CHANGES.txt 25 Aug 2010 07:48:54 -0000 1.56 *************** *** 43,46 **** --- 43,49 ---- * Pythonwin: trim leading and trailing whitespace in calltip text (kxroberto) + * Pythonwin: fix reload of package modules and support for 'pyw' and 'pyx' + extensions (kxroberto) + Since build 213: ---------------- |
From: Mark H. <mha...@us...> - 2010-08-25 07:40:01
|
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/debugger In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv27287 Modified Files: debugger.py Log Message: allow debugger to run unicode strings (kxroberto) Index: debugger.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/debugger/debugger.py,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** debugger.py 9 May 2010 14:11:51 -0000 1.25 --- debugger.py 25 Aug 2010 07:39:53 -0000 1.26 *************** *** 630,634 **** def run(self, cmd,globals=None, locals=None, start_stepping = 1): ! if type(cmd) not in [types.StringType, types.CodeType]: raise TypeError("Only strings can be run") self.last_cmd_debugged = cmd --- 630,634 ---- def run(self, cmd,globals=None, locals=None, start_stepping = 1): ! if not isinstance(cmd, (basestring, types.CodeType)): raise TypeError("Only strings can be run") self.last_cmd_debugged = cmd |
From: Mark H. <mha...@us...> - 2010-08-25 07:37:10
|
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/idle In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv26817/Pythonwin/pywin/idle Modified Files: CallTips.py Log Message: Pythonwin: trim leading and trailing whitespace in calltip text (kxroberto); via patch 3048863 Index: CallTips.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/idle/CallTips.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** CallTips.py 5 Jan 2009 11:06:23 -0000 1.5 --- CallTips.py 25 Aug 2010 07:37:02 -0000 1.6 *************** *** 136,139 **** --- 136,140 ---- doc=ob.__doc__ try: + doc = doc.strip() pos = doc.find("\n") except AttributeError: |
From: Mark H. <mha...@us...> - 2010-08-25 07:37:10
|
Update of /cvsroot/pywin32/pywin32 In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv26817 Modified Files: CHANGES.txt Log Message: Pythonwin: trim leading and trailing whitespace in calltip text (kxroberto); via patch 3048863 Index: CHANGES.txt =================================================================== RCS file: /cvsroot/pywin32/pywin32/CHANGES.txt,v retrieving revision 1.54 retrieving revision 1.55 diff -C2 -d -r1.54 -r1.55 *** CHANGES.txt 31 Jul 2010 06:20:47 -0000 1.54 --- CHANGES.txt 25 Aug 2010 07:37:02 -0000 1.55 *************** *** 41,44 **** --- 41,46 ---- * Fix encoding problem in makepy (Massa, Harald Armin) + * Pythonwin: trim leading and trailing whitespace in calltip text (kxroberto) + Since build 213: ---------------- |
From: Mark H. <mha...@us...> - 2010-08-25 07:35:12
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv26440/win32/src Modified Files: win32apimodule.cpp Log Message: ensure GetConsoleTitle treats an empty string correctly Index: win32apimodule.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32apimodule.cpp,v retrieving revision 1.100 retrieving revision 1.101 diff -C2 -d -r1.100 -r1.101 *** win32apimodule.cpp 26 Jan 2010 17:45:27 -0000 1.100 --- win32apimodule.cpp 25 Aug 2010 07:34:59 -0000 1.101 *************** *** 942,945 **** --- 942,946 ---- if (title==NULL) return PyErr_Format(PyExc_MemoryError, "GetConsoleTitle: unable to allocate %d bytes", chars_allocated*sizeof(TCHAR)); + title[0] = 0; chars_returned=GetConsoleTitle(title, chars_allocated); if (chars_returned==0 && GetLastError() != ERROR_SUCCESS){ |
From: Mark H. <mha...@us...> - 2010-08-25 07:33:05
|
Update of /cvsroot/pywin32/pywin32 In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv26108 Modified Files: MANIFEST.in Log Message: add missing help related files to the source dist Index: MANIFEST.in =================================================================== RCS file: /cvsroot/pywin32/pywin32/MANIFEST.in,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** MANIFEST.in 2 Mar 2009 06:12:57 -0000 1.17 --- MANIFEST.in 25 Aug 2010 07:32:56 -0000 1.18 *************** *** 13,16 **** --- 13,18 ---- include win32/src/win32popenWin9x.cpp include win32/scripts/*.py + include win32/help/*.d + include win32/help/*.html include win32/test/*.py include win32/test/win32rcparser/test.rc |
From: Vernon C. <kf...@us...> - 2010-07-31 06:20:55
|
Update of /cvsroot/pywin32/pywin32 In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv27251 Modified Files: CHANGES.txt Log Message: Edit CHANGES.txt for adodbapi v2.4.0 Index: CHANGES.txt =================================================================== RCS file: /cvsroot/pywin32/pywin32/CHANGES.txt,v retrieving revision 1.53 retrieving revision 1.54 diff -C2 -d -r1.53 -r1.54 *** CHANGES.txt 3 May 2010 08:41:02 -0000 1.53 --- CHANGES.txt 31 Jul 2010 06:20:47 -0000 1.54 *************** *** 8,11 **** --- 8,28 ---- Since build 214: ---------------- + * Update adodbapi to version 2.4.0 -- in this version, + "fetchall()" and "fetchmany()" return an SQLrows object + ...which emulates a sequence of SQLrow objects. + "fetchone()" or the cursor's "next()" method return an SQLrow object. + An SQLrow object emulates a tuple of data fields. + An SQLrow object also appears to have an attribute for each column of data. + therefore... + >>> import adodbapi + >>> myConnection = adodbapi.connection('someDSN') + >>> cur = myConnection.cursor() + >>> cur.execute("select name, rank, serialNumber from soldiers") + >>> row = cur.fetchone() + >>> assert row[0] == row['name'] + >>> assert row[1] == row.rank + >>> rows = cur.fecthall() + >>> assert rows[4,'serialNumber'] == rows[4][2] + * Update adodbapi to version 2.3.0 -- this is includes major refactoring and specifically adds features for django support, including the ability for the |
From: Vernon C. <kf...@us...> - 2010-07-31 05:48:19
|
Update of /cvsroot/pywin32/pywin32/adodbapi In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv20495/adodbapi Modified Files: __init__.py adodbapi.py readme.txt Log Message: adodbapi version 2.4.0 Index: adodbapi.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/adodbapi/adodbapi.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** adodbapi.py 5 Jun 2010 21:59:48 -0000 1.13 --- adodbapi.py 31 Jul 2010 05:48:09 -0000 1.14 *************** *** 27,31 **** or, after running through 2to3.py, CPython 3.0 or later. """ ! __version__ = '2.3.0' version = 'adodbapi v' + __version__ # N.O.T.E.:... --- 27,31 ---- or, after running through 2to3.py, CPython 3.0 or later. """ ! __version__ = '2.4.0' version = 'adodbapi v' + __version__ # N.O.T.E.:... *************** *** 47,55 **** # or # from django.utils import _decimal as decimal ! if sys.platform != 'cli': ! import win32com.client ! onIronPython = False ! else: # implies running on IronPython ! onIronPython = True # --- define objects to smooth out IronPython <-> CPython differences --- 47,57 ---- # or # from django.utils import _decimal as decimal ! onIronPython = sys.platform == 'cli' ! if not onIronPython: ! try: ! import win32com.client ! except ImportError: ! import warnings ! warnings.warn("pywin32 package required but not found.",ImportWarning) # --- define objects to smooth out IronPython <-> CPython differences *************** *** 64,72 **** return obj.Item[index] else: #pywin32 ! import pythoncom ! import pywintypes ! pythoncom.__future_currency__ = True ! def Dispatch(dispatch): ! return win32com.client.Dispatch(dispatch) def getIndexedValue(obj,index): return obj(index) --- 66,77 ---- return obj.Item[index] else: #pywin32 ! try: ! import pythoncom ! import pywintypes ! pythoncom.__future_currency__ = True ! def Dispatch(dispatch): ! return win32com.client.Dispatch(dispatch) ! except: ! pass #warning already given above def getIndexedValue(obj,index): return obj(index) *************** *** 143,146 **** --- 148,153 ---- def DateObjectFromCOMDate(self,comDate): return mx.DateTime.DateTimeFromCOMDate(comDate) + def DateObjectFromCOMDate(self,comDate): + return mx.DateTime.DateTimeFromCOMDate(comDate) def Date(self,year,month,day): return mx.DateTime.Date(year,month,day) *************** *** 167,184 **** return self.COMDateFromTuple(YMDHMSmsTuple) def DateObjectFromCOMDate(self,comDate): - #ComDate is number of days since 1899-12-31 if isinstance(comDate,datetime.datetime): return comDate.replace(tzinfo=None) # make non aware elif isinstance(comDate,DateTime): ! fComDate = comDate.ToOADate() else: ! fComDate=float(comDate) ! millisecondsperday=86400000 # 24*60*60*1000 integerPart = int(fComDate) floatpart=fComDate-integerPart ! if floatpart == 0.0: ! return datetime.date.fromordinal(integerPart + self._ordinal_1899_12_31) dte=datetime.datetime.fromordinal(integerPart + self._ordinal_1899_12_31) \ ! + datetime.timedelta(milliseconds=floatpart*millisecondsperday) return dte def Date(self,year,month,day): --- 174,190 ---- return self.COMDateFromTuple(YMDHMSmsTuple) def DateObjectFromCOMDate(self,comDate): if isinstance(comDate,datetime.datetime): return comDate.replace(tzinfo=None) # make non aware elif isinstance(comDate,DateTime): ! fComDate = comDate.ToOADate() # ironPython clr Date/Time else: ! fComDate=float(comDate) #ComDate is number of days since 1899-12-31 integerPart = int(fComDate) floatpart=fComDate-integerPart ! ##if floatpart == 0.0: ! ## return datetime.date.fromordinal(integerPart + self._ordinal_1899_12_31) dte=datetime.datetime.fromordinal(integerPart + self._ordinal_1899_12_31) \ ! + datetime.timedelta(milliseconds=floatpart*86400000) ! # millisecondsperday=86400000 # 24*60*60*1000 return dte def Date(self,year,month,day): *************** *** 224,228 **** if isinstance(comDate,datetime.datetime): return comDate.timetuple() ! elif isinstance(comDate,DateTime): fcomDate = comDate.ToOADate() else: --- 230,234 ---- if isinstance(comDate,datetime.datetime): return comDate.timetuple() ! elif isinstance(comDate,DateTime): # ironPython clr date/time fcomDate = comDate.ToOADate() else: *************** *** 337,341 **** # For example: # import adodbapi, ado_consts ! # adodbapi.adodbapi.defaultIsolationLevel=adc.adXactBrowse" # # Set defaultCursorLocation on module level before creating the connection. --- 343,347 ---- # For example: # import adodbapi, ado_consts ! # adodbapi.adodbapi.defaultIsolationLevel=ado_consts.adXactBrowse" # # Set defaultCursorLocation on module level before creating the connection. *************** *** 346,350 **** # Used for COM to Python date conversions. _ordinal_1899_12_31 = datetime.date(1899,12,31).toordinal()-1 - _milliseconds_per_day = 24*60*60*1000 def format_parameters(parameters, show_value=False): --- 352,355 ---- *************** *** 394,405 **** p.Value = s p.Size = len(s) ! elif type(value) in dateconverter.types: if settings_known and p.Type in adoDateTimeTypes: p.Value=dateconverter.COMDate(value) else: #probably a string ! #Known problem with JET Provider. Date can not be specified as a COM date. ! # See for example..http://support.microsoft.com/default.aspx?scid=kb%3ben-us%3b284843 ! # One workaround is to provide the date as a string in the format 'YYYY-MM-dd' s = dateconverter.DateObjectToIsoFormatString(value) p.Value = s --- 399,410 ---- p.Value = s p.Size = len(s) ! elif type(value) in dateconverter.types: if settings_known and p.Type in adoDateTimeTypes: p.Value=dateconverter.COMDate(value) else: #probably a string ! #Known problem with JET Provider. Date can not be specified as a COM date. ! # See for example..http://support.microsoft.com/default.aspx?scid=kb%3ben-us%3b284843 ! # One workaround is to provide the date as a string in the format 'YYYY-MM-dd' s = dateconverter.DateObjectToIsoFormatString(value) p.Value = s *************** *** 559,563 **** if state.startswith('23') or state=='40002': return IntegrityError - return DatabaseError --- 564,567 ---- *************** *** 576,581 **** --- 580,683 ---- object.__setattr__(self, name, value) + # # # # # classes to emulate the result of cursor.fetchxxx() as a sequence of sequences # # # # # + class _SQLrow(object): # a single database row + # class to emulate a sequence, so that a column may be retrieved by either number or name + def __init__(self,rows,index): # "rows" is an _SQLrows object, index is which row + # note: self.__setattr__ is disabled to prevent users from trying to store in a row + object.__setattr__(self,'rows',rows) # parent 'fetch' container object + object.__setattr__(self,'index',index) # row number within parent + def __getattr__(self,name): # used for row.columnName type of value access + return self._getValue(self.rows.columnNames[name]) + def __setattr__(self,name,value): + raise NotSupportedError('Cannot assign value to SQL record column') + def _getValue(self,key): # key must be an integer + if onIronPython: # retrieve from two-dimensional array + v = self.rows.ado_results[key,self.index] + else: # pywin32 - retrieve from tuple of tuples + v = self.rows.ado_results[key][self.index] + return _convert_to_python(v,self.rows.converters[key]) + def __len__(self): + return len(self.rows.converters) + def __getitem__(self,key): # used for row[key] type of value access + if isinstance(key,int): # normal row[1] designation + try: + return self._getValue(key) + except IndexError: + raise + if isinstance(key, slice): + indices = key.indices(len(self.rows.converters)) + vl = [self._getValue(i) for i in range(*indices)] + return tuple(vl) + try: + return self._getValue(self.rows.columnNames[key]) # extension row[columnName] designation + except (KeyError,TypeError): + er, st, tr = sys.exc_info() + raise er,'No such key as "%s" in %s'%(repr(key),self.__repr__()) + def __iter__(self): + return iter(self.__next__()) + def __next__(self): + for n in range(len(self.rows.converters)): + yield self._getValue(n) + def __repr__(self): # create a human readable representation + try: #python 2.4 and later + taglist = sorted(self.rows.columnNames.items(),key=lambda x:x[1]) + except NameError: # no such function as "sorted" on 2.3 + taglist = list(self.rows.columnNames.iteritems()) + taglist.sort(lambda x, y: cmp(x[1], y[1])) #deprecated on 3.0 + s = "<SQLrow={" + for name, i in taglist: + s += name + ':' + repr(self._getValue(i)) + ', ' + return s[:-2] + '}>' + def __str__(self): # create a pretty human readable representation + return str(tuple([str(self._getValue(i)) for i in range(len(self.rows.converters))])) + # # # # + class _SQLrows(object): + # class to emulate a sequence for multiple rows using a container object + def __init__(self,ado_results,numberOfRows,cursor): + self.ado_results = ado_results # raw result of SQL get + self.numberOfRows = numberOfRows + self.converters = [] # convertion function for each column + self.columnNames = {} # names of columns {name:number,...} + for i,desc in enumerate(cursor.description): + self.columnNames[desc[0]] = i + self.converters.append(variantConversions[desc[1]]) # default convertion function + def __len__(self): + return self.numberOfRows + def __getitem__(self,item): # used for row or row,column access + if isinstance(item, slice): # will return a tuple of row objects + indices = item.indices(self.numberOfRows) + l = [_SQLrow(self,k) for k in range(*indices)] + return tuple(l) #no generator expressions in Python 2.3 + elif isinstance(item, tuple) and len(item)==2: + # d = some_rowsObject[i,j] will return a datum from a two-dimension address + i,j = item + if not isinstance(j,int): + try: + j = self.columnNames[j] # convert named column to numeric + except KeyError: + raise KeyError, 'adodbapi: no such column name as "%s"'%repr(j) + if onIronPython: # retrieve from two-dimensional array + v = self.ado_results[j,i] + else: # pywin32 - retrieve from tuple of tuples + v = self.ado_results[j][i] + return _convert_to_python(v,self.converters[j]) + else: + row = _SQLrow(self,item) # new row descriptor + return row + def __iter__(self): + return iter(self.__next__()) + def __next__(self): + for n in range(self.numberOfRows): + row = _SQLrow(self,n) + yield row + # # # # # + def _convert_to_python(variant, function): # convert DB value into Python value + if isinstance(variant,DBNull): + return None + return function(variant) # # # # # ----- the Class that defines a cursor ----- # # # # # class Cursor(object): + ## ** api required attributes: + ## description... ## This read-only attribute is a sequence of 7-item sequences. ## Each of these sequences contains information describing one result column: *************** *** 584,589 **** ## cursor has not had an operation invoked via the executeXXX() method yet. ## The type_code can be interpreted by comparing it to the Type Objects specified in the section below. ! description = None ! ## This read-only attribute specifies the number of rows that the last executeXXX() produced ## (for DQL statements like select) or affected (for DML statements like update or insert). --- 686,690 ---- ## cursor has not had an operation invoked via the executeXXX() method yet. ## The type_code can be interpreted by comparing it to the Type Objects specified in the section below. ! ## rowcount... ## This read-only attribute specifies the number of rows that the last executeXXX() produced ## (for DQL statements like select) or affected (for DML statements like update or insert). *************** *** 591,596 **** ## the rowcount of the last operation is not determinable by the interface.[7] ## NOTE: -- adodbapi returns "-1" by default for all select statements ! rowcount = -1 ! ## This read/write attribute specifies the number of rows to fetch at a time with fetchmany(). ## It defaults to 1 meaning to fetch a single row at a time. --- 692,696 ---- ## the rowcount of the last operation is not determinable by the interface.[7] ## NOTE: -- adodbapi returns "-1" by default for all select statements ! ## arraysize... ## This read/write attribute specifies the number of rows to fetch at a time with fetchmany(). ## It defaults to 1 meaning to fetch a single row at a time. *************** *** 598,610 **** ## but are free to interact with the database a single row at a time. ## It may also be used in the implementation of executemany(). ! arraysize=1 ! def __init__(self,connection): self.messages=[] self.connection = connection ! self.paramstyle = connection.paramstyle ! self.rs = None self.description = None self.errorhandler = connection.errorhandler if verbose: print 'adodbapi New cursor at %X on conn %X' % (id(self),id(self.connection)) --- 698,715 ---- ## but are free to interact with the database a single row at a time. ## It may also be used in the implementation of executemany(). ! ## ** extension attributes: ! ## paramstyle... ! ## allows the programmer to override the connection's default paramstyle ! ## errorhandler... ! ## allows the programmer to override the connection's default error handler ! def __init__(self,connection): self.messages=[] self.connection = connection ! self.paramstyle = connection.paramstyle # used for overriding the paramstyle ! self.rs = None # the ADO recordset for this cursor self.description = None self.errorhandler = connection.errorhandler + self.arraysize = 1 if verbose: print 'adodbapi New cursor at %X on conn %X' % (id(self),id(self.connection)) *************** *** 634,643 **** def format_description(self,d): ! """Format db_api description tuple.""" if isinstance(d,int): d = self.description[d] desc = "Name= %s, Type= %s, DispSize= %s, IntSize= %s, Precision= %s, Scale= %s NullOK=%s" %\ ! (d[0], adc.adTypeNames.get(d[1], str(d[1])+' (unknown type)'), ! d[2], d[3], d[4], d[5], d[6]) return desc --- 739,748 ---- def format_description(self,d): ! """Format db_api description tuple for printing.""" if isinstance(d,int): d = self.description[d] desc = "Name= %s, Type= %s, DispSize= %s, IntSize= %s, Precision= %s, Scale= %s NullOK=%s" %\ ! (d[0], adc.adTypeNames.get(d[1], str(d[1])+' (unknown type)'), ! d[2], d[3], d[4], d[5], d[6]) return desc *************** *** 753,757 **** print 'with parameters=',format_parameters(self.cmd.Parameters, True) try: ! # ----- the actual SQL is executed here --- if onIronPython: ra = Reference[int]() --- 858,862 ---- print 'with parameters=',format_parameters(self.cmd.Parameters, True) try: ! # ----- the actual SQL is executed here --- if onIronPython: ra = Reference[int]() *************** *** 795,799 **** if verbose > 2: print 'returning=', p.Name, p.Type, p.Direction, repr(p.Value) ! pyObject=_convert_to_python(p.Value,p.Type) if p.Direction == adc.adParamReturnValue: self.returnValue=pyObject --- 900,904 ---- if verbose > 2: print 'returning=', p.Name, p.Type, p.Direction, repr(p.Value) ! pyObject=_convert_to_python(p.Value,variantConversions[p.Type]) if p.Direction == adc.adParamReturnValue: self.returnValue=pyObject *************** *** 829,833 **** self.cmd.Parameters.Append(p) if verbose > 2: ! for i in range(self.cmd.Parameters.Count): P = self.cmd.Parameters[i] print 'adodbapi parameter attributes=', P.Name, P.Type, P.Direction, P.Size --- 934,938 ---- self.cmd.Parameters.Append(p) if verbose > 2: ! for i in range(self.cmd.Parameters.Count): P = self.cmd.Parameters[i] print 'adodbapi parameter attributes=', P.Name, P.Type, P.Direction, P.Size *************** *** 836,846 **** i = 0 for value in parameters: ! ##if value is None: ! ## parameter_replacements.append('NULL') ! ## continue ! ##if isinstance(value, basestring) and value == "": ! ## parameter_replacements.append("''") ! ## continue ! ##parameter_replacements.append('?') p=getIndexedValue(self.cmd.Parameters,i) if p.Direction == adc.adParamReturnValue: --- 941,951 ---- i = 0 for value in parameters: ! ##if value is None: ! ## parameter_replacements.append('NULL') ! ## continue ! ##if isinstance(value, basestring) and value == "": ! ## parameter_replacements.append("''") ! ## continue ! ##parameter_replacements.append('?') p=getIndexedValue(self.cmd.Parameters,i) if p.Direction == adc.adParamReturnValue: *************** *** 851,855 **** except (Exception), e: _message = u'Converting Parameter %s: %s, %s <- %s\n' %\ ! (p.Name, adc.ado_type_name(p.Type), p.Value, repr(value)) self._raiseCursorError(DataError, _message+'->'+repr(e.args)) i += 1 --- 956,960 ---- except (Exception), e: _message = u'Converting Parameter %s: %s, %s <- %s\n' %\ ! (p.Name, adc.ado_type_name(p.Type), p.Value, repr(value)) self._raiseCursorError(DataError, _message+'->'+repr(e.args)) i += 1 *************** *** 912,919 **** self.rowcount = total_recordcount ! def _fetch(self, rows=None): """Fetch rows from the current recordset. ! rows -- Number of rows to fetch, or None (default) to fetch all rows. """ if self.connection is None or self.rs is None: --- 1017,1024 ---- self.rowcount = total_recordcount ! def _fetch(self, limit=None): """Fetch rows from the current recordset. ! limit -- Number of rows to fetch, or None (default) to fetch all rows. """ if self.connection is None or self.rs is None: *************** *** 922,953 **** if self.rs.State == adc.adStateClosed or self.rs.BOF or self.rs.EOF: ! if rows == 1: # fetchone returns None ! return None ! else: # fetchall and fetchmany return empty lists ! return list() ! if rows: ! ado_results = self.rs.GetRows(rows) ! else: ado_results = self.rs.GetRows() ! ! d=self.description ! returnList=[] ! i=0 ! if onIronPython: ! type_codes = [descTuple[1] for descTuple in d] ! for j in range(len(ado_results)/len(d)): ! L = [] ! for i in range(len(d)): ! L.append(_convert_to_python(ado_results[i,j],type_codes[i])) ! returnList.append(tuple(L)) ! return tuple(returnList) else: #pywin32 ! for descTuple in d: ! # Desctuple =(name, type_code, display_size, internal_size, precision, scale, null_ok). ! type_code=descTuple[1] ! returnList.append([_convert_to_python(r,type_code) for r in ado_results[i]]) ! i+=1 ! return tuple(zip(*returnList)) def fetchone(self): --- 1027,1043 ---- if self.rs.State == adc.adStateClosed or self.rs.BOF or self.rs.EOF: ! return list() ! if limit: # limit number of rows retrieved ! ado_results = self.rs.GetRows(limit) ! else: # get all rows ado_results = self.rs.GetRows() ! if onIronPython: # result of GetRows is a two-dimension array ! length = len(ado_results)//len(self.description) # length of first dimension ! fetchObject = _SQLrows(ado_results,length,self) # new object to hold the results of the fetch else: #pywin32 ! length = len(ado_results[0]) #result of GetRows is tuples in a tuple ! fetchObject = _SQLrows(ado_results,length,self) # new object to hold the results of the fetch ! return fetchObject def fetchone(self): *************** *** 1085,1090 **** return makeByteBuffer(aString) - #v2.1 Cole comment out: BinaryType = Binary('a') - #SQL NULL values are represented by the Python None singleton on input and output. --- 1175,1178 ---- *************** *** 1097,1100 **** --- 1185,1192 ---- return typeMap[tp] except KeyError: + if isinstance(d,datetime.datetime): + return adc.adDBTimeStamp + if isinstance(d,datetime.time): + return adc.adDBTime if tp in dateconverter.types: return adc.adDate *************** *** 1177,1181 **** return _convertNumberWithCulture(variant, decimal.Decimal) def cvtNumeric(variant): #older name - don't break old code ! return cvtDecimal(variant) def cvtFloat(variant): --- 1269,1273 ---- return _convertNumberWithCulture(variant, decimal.Decimal) def cvtNumeric(variant): #older name - don't break old code ! return cvtDecimal(variant) def cvtFloat(variant): *************** *** 1191,1195 **** except (ValueError,TypeError,decimal.InvalidOperation): pass - def cvtInt(variant): return int(variant) --- 1283,1286 ---- *************** *** 1207,1215 **** class VariantConversionMap(dict): #builds a dictionary from {[list,of,keys]function} ! #useful for difining conversion functions for groups of similar data types. def __init__(self, aDict): for k, v in aDict.items(): self[k] = v # we must call __setitem__ - def __setitem__(self, adoType, cvtFn): "don't make adoType a string :-)" --- 1298,1305 ---- class VariantConversionMap(dict): #builds a dictionary from {[list,of,keys]function} ! #useful for defining conversion functions for groups of similar data types. def __init__(self, aDict): for k, v in aDict.items(): self[k] = v # we must call __setitem__ def __setitem__(self, adoType, cvtFn): "don't make adoType a string :-)" *************** *** 1219,1223 **** except TypeError: # single value dict.__setitem__(self, adoType, cvtFn) - def __getitem__(self, fromType): try: --- 1309,1312 ---- *************** *** 1226,1239 **** return identity ! def _convert_to_python(variant, adType): ! if verbose > 3: ! print 'Converting type_code=%s, val=%s'%(adType,repr(variant)) ! print 'conversion function=',repr(variantConversions[adType]) ! print ' output=%s'%repr(variantConversions[adType](variant)) ! if isinstance(variant,DBNull): ! return None ! return variantConversions[adType](variant) #initialize variantConversions dictionary used to convert SQL to Python variantConversions = VariantConversionMap( { adoDateTimeTypes : variantConvertDate, --- 1315,1329 ---- return identity ! ##def _convert_to_python(variant, adType): ! ## if verbose > 3: ! ## print 'Converting type_code=%s, val=%s'%(adType,repr(variant)) ! ## print 'conversion function=',repr(variantConversions[adType]) ! ## print ' output=%s'%repr(variantConversions[adType](variant)) ! ## if isinstance(variant,DBNull): ! ## return None ! ## return variantConversions[adType](variant) #initialize variantConversions dictionary used to convert SQL to Python + # this is the dictionary of default convertion functions, built by the class above. variantConversions = VariantConversionMap( { adoDateTimeTypes : variantConvertDate, Index: __init__.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/adodbapi/__init__.py,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** __init__.py 4 Jan 2008 18:49:09 -0000 1.1.1.1 --- __init__.py 31 Jul 2010 05:48:09 -0000 1.2 *************** *** 1 **** ! from adodbapi import * \ No newline at end of file --- 1,3 ---- ! import ado_consts ! from adodbapi import * ! Index: readme.txt =================================================================== RCS file: /cvsroot/pywin32/pywin32/adodbapi/readme.txt,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** readme.txt 3 May 2010 05:40:33 -0000 1.10 --- readme.txt 31 Jul 2010 05:48:09 -0000 1.11 *************** *** 16,24 **** * Supports eGenix mxDateTime, Python 2.3 datetime module and Python time module. * Supports multiple paramstyles: 'qmark' 'named' 'format' Prerequisites: * C Python 2.3 or higher and pywin32 (Mark Hammond's python for windows extensions.) ! Note: as of 2.1.1, adodbapi is included in pywin32 versions 211 and later. or Iron Python 2.6 or higher. (works in IPy2.0 for all data types except BUFFER) --- 16,28 ---- * Supports eGenix mxDateTime, Python 2.3 datetime module and Python time module. * Supports multiple paramstyles: 'qmark' 'named' 'format' + * Supports data retrieval by column name e.g.: + for row in myCurser.execute("select name,age from students"): + print "Student", row.name, "is", row.age, "years old" + * Supports user-definable system-to-Python data convertion functions (selected by ADO data type, or by column) Prerequisites: * C Python 2.3 or higher and pywin32 (Mark Hammond's python for windows extensions.) ! Note: adodbapi is included in pywin32 versions 211 and later. or Iron Python 2.6 or higher. (works in IPy2.0 for all data types except BUFFER) *************** *** 34,49 **** adodbapi.adodbapi.variantConversions[adodbapi.adNumeric] = write_your_own_convertion_function ............ Whats new in version 2.3.0 # note: breaking changes and default changes! ! This version is all about django support. There are two targets: ! A) MS SQL database connections for mainstream django. ! B) running django on IronPython Someday, far in the future, this may result in: ! C) MS SQL connections from django running on IronPython on Mono on Linux. (dreams sometimes come true.) Thanks to Adam Vandenberg for the django modifications. - The changes are: 1. the ado constants are moved into their own module: ado_consts This may break some old code, but Adam did it on his version and I like the improvement in readability. Also, you get better documentation of some results, like convertion of MS data type codes to strings: >>> ado_consts.adTypeNames[202] 'adVarWChar' --- 38,84 ---- adodbapi.adodbapi.variantConversions[adodbapi.adNumeric] = write_your_own_convertion_function ............ + Whats new in version 2.4.0 + 1. The result of fetchall() and fetchmany() will be an object which emulates a sequence of sequences. + The result of fetchone() will be an object which emulates a sequence. + [This eliminates creating a tuple of return values.] + Also the data are not fetched and converted to Python data types untill actually referred to, therefore... + 2. Data can be retrieved from the result sets using the column name (as well as the number). + >>> cs = someConnection.cursor() + >>> cs.execute('select name, rank, serialNumber from soldiers') + >>> rows = cs.fetchall() + >>> for soldier in rows: + >>> print soldier.name, soldier['rank'], soldier[2] + Fred Flintstone private 333-33-3333 + Barny Rubble sergeant 123-45-6789 + 3. User defined conversions can be applied at the column level from the 'fetch' object: + (continuing the above example)... + >>> upcaseConverter=lambda aStringField: aStringField.upper() + >>> # now use a single column converter + >>> rows.converters[0] = upcaseConverter # convert first column as upper case + >>> for soldier in rows: + >>> print soldier.name, soldier.rank + FRED FLINTSTONE private + BARNY RUBBLE sergeant + 4. Data may be retrieved by a TWO DIMENSIONAL "extended slicing": + >>> cs.execute('select name, rank, serialNumber from soldiers') + >>> rows = cs.fetchall() + >>> print rows[1,2] + 123-45-6789 + >>> print rows[0,'name'] + Fred Flintstone + Whats new in version 2.3.0 # note: breaking changes and default changes! ! This version is all about django support. There are two hoped-for targets: ! ... A) MS SQL database connections for mainstream django. ! ... B) running django on IronPython Someday, far in the future, this may result in: ! ... C) MS SQL connections from django running on IronPython on Mono on Linux. (dreams sometimes come true.) Thanks to Adam Vandenberg for the django modifications. + The changes are: 1. the ado constants are moved into their own module: ado_consts This may break some old code, but Adam did it on his version and I like the improvement in readability. Also, you get better documentation of some results, like convertion of MS data type codes to strings: + >>> import adodbapi.ado_consts as ado_consts >>> ado_consts.adTypeNames[202] 'adVarWChar' *************** *** 61,66 **** when 'named' format is used, the parameters must be in a dict, rather than a sequence. >>>c = adodbapi.connect('someConnectionString',timeout=30) ! >>>c.paramstyle = 'spam' ! <<<will result in: adodbapi.NotSupportedError: paramstyle="spam" not in:('qmark', 'named', 'format')>>> ** new extension feature ** --- 96,102 ---- when 'named' format is used, the parameters must be in a dict, rather than a sequence. >>>c = adodbapi.connect('someConnectionString',timeout=30) ! >>>c.paramstyle = 'named' ! >>>cs = c.cursor() ! >>>cs.execute('select * from sometable where firstname = :aname and age = :hisage' , {'aname':'Fred','hisage':35}) ** new extension feature ** *************** *** 149,153 **** Installation ------------ ! This version will be installed as part of the win32 package. Authors (up to version 2.0.1) --- 185,191 ---- Installation ------------ ! For CPython, this version will be installed as part of the win32 package. ! For IronPython (or to update a CPython version early), use "setup.py install" ! while using the Python version upon which you want the package installed. Authors (up to version 2.0.1) *************** *** 175,191 **** ------------- The adodbapi mailing lists have been deactivated. Submit comments to the ! pywin32 lists. ! ! ! Relase history ! -------------- ! 2.2.4 Ready for 2to3 convertion. Refactor to be more readable. Added function getIndexedValue() for IPy 2.0. ! 2.2.3 (withdrawn) ! 2.2.2 Iron Python support complete. ! 2.2.1 Bugfix for string truncation ! 2.2 Code cleanup. added feature: "adodbapi.variantConversions[adodbapi.adNumeric] = adodbapi.cvtString" ! 2.1.1 Bugfix to CoIninialize() and nextset() ! 2.1 Python 2.4 version ! 2.0 See what's new above. ! 1.0.1 Bug fix: Null values for numeric fields. Thanks to Tim Golden. ! 1.0 the first release --- 213,215 ---- ------------- The adodbapi mailing lists have been deactivated. Submit comments to the ! pywin32 or IronPython mailing lists. |
From: Vernon C. <kf...@us...> - 2010-07-31 05:48:19
|
Update of /cvsroot/pywin32/pywin32/adodbapi/tests In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv20495/adodbapi/tests Modified Files: db_print.py test_adodbapi_dbapi20.py Added Files: .cvsignore testADOdbapi.py testADOdbapiConfig.py testRun.bat Log Message: adodbapi version 2.4.0 --- NEW FILE: testADOdbapi.py --- """ Unit tests for adodbapi version 2.4.0""" """ adodbapi - A python DB API 2.0 interface to Microsoft ADO Copyright (C) 2002 Henrik Ekelund 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 Updates by Vernon Cole """ import unittest import sys try: import win32com.client win32 = True except ImportError: win32 = False import testADOdbapiConfig as config #will find (parent?) adodbapi import adodbapi try: import adodbapi.ado_consts as ado_consts except ImportError: #we are doing a shortcut import as a module -- so import ado_consts import types try: import decimal except ImportError: import win32com.decimal_23 as decimal def str2bytes(sval): if sys.version_info < (3,0) and isinstance(sval, str): sval = sval.decode("latin1") return sval.encode("latin1") class CommonDBTests(unittest.TestCase): "Self contained super-simple tests in easy syntax, should work on everything between mySQL and Oracle" def setUp(self): self.engine = 'unknown' def getEngine(self): return self.engine def getConnection(self): raise NotImplementedError #"This method must be overriden by a subclass" def getCursor(self): return self.getConnection().cursor() def testConnection(self): crsr=self.getCursor() assert crsr.__class__.__name__ == 'Cursor' def testErrorHandlerInherits(self): conn=self.getConnection() mycallable=lambda connection,cursor,errorclass,errorvalue: 1 conn.errorhandler=mycallable crsr=conn.cursor() assert crsr.errorhandler==mycallable,"Error handler on crsr should be same as on connection" def testDefaultErrorHandlerConnection(self): conn=self.getConnection() del conn.messages[:] try: conn.close() conn.commit() #Should not be able to use connection after it is closed except: assert len(conn.messages)==1 assert len(conn.messages[0])==2 assert conn.messages[0][0]==adodbapi.Error def testOwnErrorHandlerConnection(self): mycallable=lambda connection,cursor,errorclass,errorvalue: 1 #does not raise anything conn=self.getConnection() conn.errorhandler=mycallable conn.close() conn.commit() #Should not be able to use connection after it is closed assert len(conn.messages)==0 conn.errorhandler=None #This should bring back the standard error handler try: conn.close() conn.commit() #Should not be able to use connection after it is closed except: pass #The Standard errorhandler appends error to messages attribute assert len(conn.messages)>0,"Setting errorhandler to none should bring back the standard error handler" def testDefaultErrorHandlerCursor(self): crsr=self.getConnection().cursor() del crsr.messages[:] try: crsr.execute("SELECT abbtytddrf FROM dasdasd") except: assert len(crsr.messages)==1 assert len(crsr.messages[0])==2 assert crsr.messages[0][0]==adodbapi.DatabaseError def testOwnErrorHandlerCursor(self): mycallable=lambda connection,cursor,errorclass,errorvalue: 1 #does not raise anything crsr=self.getConnection().cursor() crsr.errorhandler=mycallable crsr.execute("SELECT abbtytddrf FROM dasdasd") assert len(crsr.messages)==0 crsr.errorhandler=None #This should bring back the standard error handler try: crsr.execute("SELECT abbtytddrf FROM dasdasd") except: pass #The Standard errorhandler appends error to messages attribute assert len(crsr.messages)>0,"Setting errorhandler to none should bring back the standard error handler" def testUserDefinedConversions(self): oldconverter=adodbapi.variantConversions[adodbapi.adoStringTypes] #try: duplicatingConverter=lambda aStringField: aStringField*2 assert duplicatingConverter(u'gabba') == u'gabbagabba' # change converter for ALL adoStringTypes columns adodbapi.variantConversions[adodbapi.adoStringTypes]=duplicatingConverter self.helpForceDropOnTblTemp() conn=self.getConnection() crsr=conn.cursor() tabdef = "CREATE TABLE tblTemp (fldData VARCHAR(100) NOT NULL, fld2 VARCHAR(20))" crsr.execute(tabdef) crsr.execute("INSERT INTO tblTemp(fldData,fld2) VALUES('gabba','booga')") crsr.execute("INSERT INTO tblTemp(fldData,fld2) VALUES('hey','yo')") crsr.execute("SELECT fldData,fld2 FROM tblTemp ORDER BY fldData") rows=crsr.fetchall() row = rows[0] self.assertEquals(row[0],'gabbagabba') row = rows[1] self.assertEquals(row[0],'heyhey') self.assertEquals(row[1],'yoyo') upcaseConverter=lambda aStringField: aStringField.upper() assert upcaseConverter(u'upThis') == u'UPTHIS' # now use a single column converter rows.converters[1] = upcaseConverter # convert second column self.assertEquals(row[0],'heyhey') # first will be unchanged self.assertEquals(row[1],'YO') # second will convert to upper case #finally: adodbapi.variantConversions[adodbapi.adoStringTypes]=oldconverter #Restore self.helpRollbackTblTemp() def helpTestDataType(self,sqlDataTypeString, DBAPIDataTypeString, pyData, pyDataInputAlternatives=None, compareAlmostEqual=None, allowedReturnValues=None): self.helpForceDropOnTblTemp() conn=self.getConnection() crsr=conn.cursor() tabdef= """ CREATE TABLE tblTemp ( fldId integer NOT NULL, fldData """ + sqlDataTypeString + ")\n" crsr.execute(tabdef) #Test Null values mapped to None crsr.execute("INSERT INTO tblTemp (fldId) VALUES (1)") crsr.execute("SELECT fldId,fldData FROM tblTemp") rs=crsr.fetchone() self.assertEquals(rs[1],None) #Null should be mapped to None assert rs[0]==1 #Test description related descTuple=crsr.description[1] assert descTuple[0] == 'fldData' if DBAPIDataTypeString=='STRING': assert descTuple[1] == adodbapi.STRING, 'was "%s" expected "%s"'%(descTuple[1],adodbapi.STRING.values) elif DBAPIDataTypeString == 'NUMBER': assert descTuple[1] == adodbapi.NUMBER, 'was "%s" expected "%s"'%(descTuple[1],adodbapi.NUMBER.values) elif DBAPIDataTypeString == 'BINARY': assert descTuple[1] == adodbapi.BINARY, 'was "%s" expected "%s"'%(descTuple[1],adodbapi.BINARY.values) elif DBAPIDataTypeString == 'DATETIME': assert descTuple[1] == adodbapi.DATETIME, 'was "%s" expected "%s"'%(descTuple[1],adodbapi.DATETIME.values) elif DBAPIDataTypeString == 'ROWID': assert descTuple[1] == adodbapi.ROWID, 'was "%s" expected "%s"'%(descTuple[1],adodbapi.ROWID.values) else: raise NotImplementedError #"DBAPIDataTypeString not provided" #Test data binding inputs=[pyData] if pyDataInputAlternatives: inputs.append(pyDataInputAlternatives) fldId=1 for inParam in inputs: fldId+=1 try: crsr.execute("INSERT INTO tblTemp (fldId,fldData) VALUES (?,?)", (fldId,pyData)) except: conn.printADOerrors() raise crsr.execute("SELECT fldData FROM tblTemp WHERE ?=fldID", [fldId]) rs=crsr.fetchone() if allowedReturnValues: allowedTypes = tuple([type(aRV) for aRV in allowedReturnValues]) assert isinstance(rs[0],allowedTypes), \ 'result type "%s" must be one of %s'%(type(rs[0]),allowedTypes) else: assert isinstance(rs[0] ,type(pyData)), \ 'result type "%s" must be instance of %s'%(type(rs[0]),type(pyData)) if compareAlmostEqual and DBAPIDataTypeString == 'DATETIME': iso1=adodbapi.dateconverter.DateObjectToIsoFormatString(rs[0]) iso2=adodbapi.dateconverter.DateObjectToIsoFormatString(pyData) self.assertEquals(iso1 , iso2) elif compareAlmostEqual: assert abs(rs[0]-pyData)/pyData<0.00001, \ "Values not almost equal rs[0]=%s, pyData=%f" %(rs[0],pyData) else: if allowedReturnValues: ok=0 for possibility in allowedReturnValues: if rs[0]==possibility: ok=1 assert ok else: self.assertEquals(rs[0] , pyData, \ 'Values are not equal rs[0]="%s", pyData="%s"' %(rs[0],pyData)) def testDataTypeFloat(self): self.helpTestDataType("real",'NUMBER',3.45,compareAlmostEqual=True) self.helpTestDataType("float",'NUMBER',1.79e37,compareAlmostEqual=True) def testDataTypeMoney(self): #v2.1 Cole -- use decimal for money if self.getEngine() != 'MySQL': self.helpTestDataType("smallmoney",'NUMBER',decimal.Decimal('214748.02')) self.helpTestDataType("money",'NUMBER',decimal.Decimal('-922337203685477.5808')) def testDataTypeInt(self): self.helpTestDataType("tinyint",'NUMBER',115) self.helpTestDataType("smallint",'NUMBER',-32768) self.helpTestDataType("int",'NUMBER',2147483647, pyDataInputAlternatives='2137483647') if self.getEngine() != 'ACCESS': self.helpTestDataType("bit",'NUMBER',1) #Does not work correctly with access self.helpTestDataType("bigint",'NUMBER',3000000000) def testDataTypeChar(self): for sqlDataType in ("char(6)","nchar(6)"): self.helpTestDataType(sqlDataType,'STRING',u'spam ',allowedReturnValues=[u'spam','spam',u'spam ','spam ']) def testDataTypeVarChar(self): stringKinds = ["varchar(10)","nvarchar(10)","text","ntext"] if self.getEngine() == 'MySQL': stringKinds = ["varchar(10)","text"] for sqlDataType in stringKinds: self.helpTestDataType(sqlDataType,'STRING',u'spam',['spam']) def testDataTypeDate(self): #Does not work with pytonTimeConvertor #self.helpTestDataType("smalldatetime",'DATETIME',adodbapi.Timestamp(2002,10,28,12,15,00)) #Accuracy one minute self.helpTestDataType("datetime",'DATETIME',adodbapi.Date(2002,10,28),compareAlmostEqual=True) if self.getEngine() != 'MySQL': self.helpTestDataType("smalldatetime",'DATETIME',adodbapi.Date(2002,10,28),compareAlmostEqual=True) self.helpTestDataType("datetime",'DATETIME',adodbapi.Timestamp(2002,10,28,12,15,1),compareAlmostEqual=True) def testDataTypeBinary(self): binfld = str2bytes('\x00\x01\xE2\x40') if self.getEngine() == 'MySQL': pass # self.helpTestDataType("BLOB(4)",'BINARY',adodbapi.Binary(binfld)) else: self.helpTestDataType("binary(4)",'BINARY',adodbapi.Binary(binfld)) self.helpTestDataType("varbinary(100)",'BINARY',adodbapi.Binary(binfld)) self.helpTestDataType("image",'BINARY',adodbapi.Binary(binfld)) def helpRollbackTblTemp(self): try: self.getConnection().rollback() except adodbapi.NotSupportedError: pass self.helpForceDropOnTblTemp() def helpForceDropOnTblTemp(self): conn=self.getConnection() crsr=conn.cursor() try: crsr.execute("DELETE FROM tblTemp") crsr.execute("DROP TABLE tblTemp") conn.commit() except: pass #finally: crsr.close() def helpCreateAndPopulateTableTemp(self,crsr): self.helpForceDropOnTblTemp() tabdef= """ CREATE TABLE tblTemp ( fldData INTEGER ) """ crsr.execute(tabdef) for i in range(9): # note: this poor SQL code, but a valid test crsr.execute("INSERT INTO tblTemp (fldData) VALUES (%i)" %(i,)) # better to use ("INSERT INTO tblTemp (fldData) VALUES (?)",(i,)) def testFetchAll(self): crsr=self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) crsr.execute("SELECT fldData FROM tblTemp") rs=crsr.fetchall() assert len(rs)==9 #test slice of rows i = 3 for row in rs[3:-2]: #should have rowid 3..6 assert row[0]==i i+=1 self.helpRollbackTblTemp() def testIterator(self): crsr=self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) crsr.execute("SELECT fldData FROM tblTemp") for i,row in enumerate(crsr): # using cursor rather than fetchxxx assert row[0]==i self.helpRollbackTblTemp() def testExecuteMany(self): crsr=self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) values = [ (111,) , (222,) ] crsr.executemany("INSERT INTO tblTemp (fldData) VALUES (?)",values) if crsr.rowcount==-1: print self.getEngine(),"Provider does not support rowcount (on .executemany())" else: self.assertEquals( crsr.rowcount,2) crsr.execute("SELECT fldData FROM tblTemp") rs=crsr.fetchall() assert len(rs)==11 self.helpRollbackTblTemp() def testRowCount(self): crsr=self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) crsr.execute("SELECT fldData FROM tblTemp") if crsr.rowcount == -1: #print "provider does not support rowcount on select" pass else: self.assertEquals( crsr.rowcount,9) self.helpRollbackTblTemp() def testRowCountNoRecordset(self): crsr=self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) crsr.execute("DELETE FROM tblTemp WHERE fldData >= 5") if crsr.rowcount==-1: print self.getEngine(), "Provider does not support rowcount (on DELETE)" else: self.assertEquals( crsr.rowcount,4) self.helpRollbackTblTemp() def testFetchMany(self): crsr=self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) crsr.execute("SELECT fldData FROM tblTemp") rs=crsr.fetchmany(3) assert len(rs)==3 rs=crsr.fetchmany(5) assert len(rs)==5 rs=crsr.fetchmany(5) assert len(rs)==1 #Ask for five, but there is only one left self.helpRollbackTblTemp() def testFetchManyWithArraySize(self): crsr=self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) crsr.execute("SELECT fldData FROM tblTemp") rs=crsr.fetchmany() assert len(rs)==1 #arraysize Defaults to one crsr.arraysize=4 rs=crsr.fetchmany() assert len(rs)==4 rs=crsr.fetchmany() assert len(rs)==4 rs=crsr.fetchmany() assert len(rs)==0 self.helpRollbackTblTemp() def testCurrencyDataType(self): if self.getEngine() != 'MySQL': tabdef= """ CREATE TABLE tblTemp ( fldCurr MONEY ) """ else: # database engine does not support "MONEY" tabdef= """ CREATE TABLE tblTemp ( fldCurr DECIMAL(19,4) ) """ conn=self.getConnection() crsr=conn.cursor() self.helpForceDropOnTblTemp() crsr.execute(tabdef) for multiplier in (1,decimal.Decimal('2.5'),78,9999,99999,7007): crsr.execute("DELETE FROM tblTemp") correct = decimal.Decimal('12.50') * multiplier crsr.execute("INSERT INTO tblTemp(fldCurr) VALUES (?)",[correct]) sql="SELECT fldCurr FROM tblTemp " try: crsr.execute(sql) except: conn.printADOerrors() fldcurr=crsr.fetchone()[0] self.assertEquals( fldcurr,correct) def testErrorConnect(self): self.assertRaises(adodbapi.DatabaseError,adodbapi.connect,'not a valid connect string') def testRowIterator(self): self.helpForceDropOnTblTemp() conn=self.getConnection() crsr=conn.cursor() tabdef= """ CREATE TABLE tblTemp ( fldId integer NOT NULL, fldTwo integer, fldThree integer, fldFour integer) """ crsr.execute(tabdef) inputs = [(2,3,4),(102,103,104)] fldId=1 for inParam in inputs: fldId+=1 try: crsr.execute("INSERT INTO tblTemp (fldId,fldTwo,fldThree,fldFour) VALUES (?,?,?,?)", (fldId,inParam[0],inParam[1],inParam[2])) except: conn.printADOerrors() raise crsr.execute("SELECT fldTwo,fldThree,fldFour FROM tblTemp WHERE ?=fldID",[fldId]) rec = crsr.fetchone() # check that stepping through an emulated row works for j in range(len(inParam)): assert rec[j] == inParam[j], 'returned value:"%s" != test value:"%s"'%(rec[j],inParam[j]) # check that we can get a complete tuple from a row assert tuple(rec) == inParam, 'returned value:"%s" != test value:"%s"'%(repr(rec),repr(inParam)) # test that slices of rows work slice1 = tuple(rec[:-1]) slice2 = tuple(inParam[0:2]) assert slice1 == slice2, 'returned value:"%s" != test value:"%s"'%(repr(slice1),repr(slice2)) # now test named column retrieval assert rec['fldTwo'] == inParam[0] assert rec.fldThree == inParam[1] assert rec.fldFour == inParam[2] # test array operation # note that the fields vv vv vv are out of order crsr.execute("select fldThree,fldFour,fldTwo from tblTemp") recs = crsr.fetchall() assert recs[1][0] == 103 assert recs[0][1] == 4 assert recs[1]['fldFour'] == 104 assert recs[0,0] == 3 assert recs[0,'fldTwo'] == 2 assert recs[1,2] == 102 for i in range(1): for j in range(2): assert recs[i][j] == recs[i,j] def testFormatParamstyle(self): self.helpForceDropOnTblTemp() conn=self.getConnection() conn.paramstyle = 'format' #test nonstandard use of paramstyle crsr=conn.cursor() tabdef= """ CREATE TABLE tblTemp ( fldId integer NOT NULL, fldData varchar(10)) """ crsr.execute(tabdef) inputs = [u'one',u'two',u'three'] fldId=2 for inParam in inputs: fldId+=1 try: crsr.execute("INSERT INTO tblTemp (fldId,fldData) VALUES (%s,%s)", (fldId,inParam)) except: conn.printADOerrors() raise crsr.execute("SELECT fldData FROM tblTemp WHERE %s=fldID", [fldId]) rec = crsr.fetchone() assert rec[0]==inParam, 'returned value:"%s" != test value:"%s"'%(rec[0],inParam) # now try an operation with a "%s" as part of a literal crsr.execute("insert into tblTemp (fldId,fldData) VALUES (%s,'four%sfive')",(20,)) crsr.execute("SELECT fldData FROM tblTemp WHERE fldID=20") rec = crsr.fetchone() assert rec[0]=='four%sfive' def testNamedParamstyle(self): self.helpForceDropOnTblTemp() conn=self.getConnection() crsr=conn.cursor() crsr.paramstyle = 'named' #test nonstandard use of paramstyle tabdef= """ CREATE TABLE tblTemp ( fldId integer NOT NULL, fldData varchar(10)) """ crsr.execute(tabdef) inputs = [u'four',u'five',u'six'] fldId=3 for inParam in inputs: fldId+=1 try: crsr.execute("INSERT INTO tblTemp (fldId,fldData) VALUES (:Id,:f_Val)", {"f_Val":inParam,'Id':fldId}) except: conn.printADOerrors() raise crsr.execute("SELECT fldData FROM tblTemp WHERE :Id=fldID", {'Id':fldId}) rec = crsr.fetchone() assert rec[0]==inParam, 'returned value:"%s" != test value:"%s"'%(rec[0],inParam) # now a test with a ":" as part of a literal crsr.execute("insert into tblTemp (fldId,fldData) VALUES (:xyz,'six:five')",{'xyz':30}) crsr.execute("SELECT fldData FROM tblTemp WHERE fldID=30") rec = crsr.fetchone() assert rec[0]=='six:five' class TestADOwithSQLServer(CommonDBTests): def setUp(self): self.conn=adodbapi.connect(config.connStrSQLServer) self.engine = 'MSSQL' def tearDown(self): try: self.conn.rollback() except: pass try: self.conn.close() except: pass self.conn=None def getConnection(self): return self.conn def testSQLServerDataTypes(self): self.helpTestDataType("decimal(18,2)",'NUMBER',3.45, allowedReturnValues=[u'3.45',u'3,45',decimal.Decimal('3.45')]) self.helpTestDataType("numeric(18,2)",'NUMBER',3.45, allowedReturnValues=[u'3.45',u'3,45',decimal.Decimal('3.45')]) def testUserDefinedConversionForExactNumericTypes(self): # variantConversions is a dictionary of convertion functions # held internally in adodbapi oldconverter = adodbapi.variantConversions[ado_consts.adNumeric] #keep old function to restore later # By default decimal and "numbers" are returned as decimals. # Instead, make numbers return as floats adodbapi.variantConversions[ado_consts.adNumeric] = adodbapi.cvtFloat self.helpTestDataType("decimal(18,2)",'NUMBER',3.45,compareAlmostEqual=1) self.helpTestDataType("numeric(18,2)",'NUMBER',3.45,compareAlmostEqual=1) # now return strings adodbapi.variantConversions[ado_consts.adNumeric] = adodbapi.cvtString self.helpTestDataType("numeric(18,2)",'NUMBER','3.45') # now a completly weird user defined convertion adodbapi.variantConversions[ado_consts.adNumeric] = lambda x: u'!!This function returns a funny unicode string %s!!'%x self.helpTestDataType("numeric(18,2)",'NUMBER','3.45', allowedReturnValues=[u'!!This function returns a funny unicode string 3.45!!']) # now reset the converter to its original function adodbapi.variantConversions[ado_consts.adNumeric]=oldconverter #Restore the original convertion function self.helpTestDataType("numeric(18,2)",'NUMBER',decimal.Decimal('3.45')) def testVariableReturningStoredProcedure(self): crsr=self.conn.cursor() spdef= """ CREATE PROCEDURE sp_DeleteMeOnlyForTesting @theInput varchar(50), @theOtherInput varchar(50), @theOutput varchar(100) OUTPUT AS SET @theOutput=@theInput+@theOtherInput """ try: crsr.execute("DROP PROCEDURE sp_DeleteMeOnlyForTesting") self.conn.commit() except: #Make sure it is empty pass crsr.execute(spdef) retvalues=crsr.callproc('sp_DeleteMeOnlyForTesting',('Dodsworth','Anne',' ')) assert retvalues[0]=='Dodsworth', '%s is not "Dodsworth"'%repr(retvalues[0]) assert retvalues[1]=='Anne','%s is not "Anne"'%repr(retvalues[1]) assert retvalues[2]=='DodsworthAnne','%s is not "DodsworthAnne"'%repr(retvalues[2]) self.conn.rollback() def testMultipleSetReturn(self): crsr=self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) spdef= """ CREATE PROCEDURE sp_DeleteMe_OnlyForTesting AS SELECT fldData FROM tblTemp ORDER BY fldData ASC SELECT fldData From tblTemp where fldData = -9999 SELECT fldData FROM tblTemp ORDER BY fldData DESC """ try: crsr.execute("DROP PROCEDURE sp_DeleteMe_OnlyForTesting") self.conn.commit() except: #Make sure it is empty pass crsr.execute(spdef) retvalues=crsr.callproc('sp_DeleteMe_OnlyForTesting') row=crsr.fetchone() self.assertEquals(row[0], 0) assert crsr.nextset() == True, 'Operation should succede' assert not crsr.fetchall(), 'Should be an empty second set' assert crsr.nextset() == True, 'third set should be present' rowdesc=crsr.fetchall() self.assertEquals(rowdesc[0][0],8) assert crsr.nextset() == None,'No more return sets, should return None' self.helpRollbackTblTemp() def testRollBack(self): crsr=self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) self.conn.commit() crsr.execute("INSERT INTO tblTemp (fldData) VALUES(100)") selectSql="SELECT fldData FROM tblTemp WHERE fldData=100" crsr.execute(selectSql) rs=crsr.fetchall() assert len(rs)==1 self.conn.rollback() crsr.execute(selectSql) assert crsr.fetchone()==None, 'cursor.fetchone should return None if a query retrieves no rows' self.helpRollbackTblTemp() class TestADOwithAccessDB(CommonDBTests): def setUp(self): self.conn = adodbapi.connect(config.connStrAccess) self.engine = 'ACCESS' def tearDown(self): try: self.conn.rollback() except: pass try: self.conn.close() except: pass self.conn=None def getConnection(self): return self.conn def testOkConnect(self): c=adodbapi.connect(config.connStrAccess) assert c != None c.close() class TestADOwithMySql(CommonDBTests): def setUp(self): self.conn = adodbapi.connect(config.connStrMySql) self.engine = 'MySQL' def tearDown(self): try: self.conn.rollback() except: pass try: self.conn.close() except: pass self.conn=None def getConnection(self): return self.conn def testOkConnect(self): c=adodbapi.connect(config.connStrMySql) assert c != None class TestADOwithPostgres(CommonDBTests): def setUp(self): self.conn = adodbapi.connect(config.connStrPostgres) self.engine = 'PostgreSQL' def tearDown(self): try: self.conn.rollback() except: pass try: self.conn.close() except: pass self.conn=None def getConnection(self): return self.conn def testOkConnect(self): c=adodbapi.connect(config.connStrPostgres) assert c != None class TimeConverterInterfaceTest(unittest.TestCase): def testIDate(self): assert self.tc.Date(1990,2,2) def testITime(self): assert self.tc.Time(13,2,2) def testITimestamp(self): assert self.tc.Timestamp(1990,2,2,13,2,1) def testIDateObjectFromCOMDate(self): assert self.tc.DateObjectFromCOMDate(37435.7604282) def testICOMDate(self): assert hasattr(self.tc,'COMDate') def testExactDate(self): d=self.tc.Date(1994,11,15) comDate=self.tc.COMDate(d) correct=34653.0 assert comDate == correct,comDate def testExactTimestamp(self): d=self.tc.Timestamp(1994,11,15,12,0,0) comDate=self.tc.COMDate(d) correct=34653.5 self.assertEquals( comDate ,correct) d=self.tc.Timestamp(2003,5,6,14,15,17) comDate=self.tc.COMDate(d) correct=37747.593946759262 self.assertEquals( comDate ,correct) def testIsoFormat(self): d=self.tc.Timestamp(1994,11,15,12,3,10) iso=self.tc.DateObjectToIsoFormatString(d) self.assertEquals(str(iso[:19]) , '1994-11-15 12:03:10') dt=self.tc.Date(2003,5,2) iso=self.tc.DateObjectToIsoFormatString(dt) self.assertEquals(str(iso[:10]), '2003-05-02') if config.doMxDateTimeTest: import mx.DateTime class TestMXDateTimeConverter(TimeConverterInterfaceTest): def setUp(self): self.tc=adodbapi.mxDateTimeConverter() def testCOMDate(self): t=mx.DateTime.DateTime(2002,6,28,18,15,2) cmd=self.tc.COMDate(t) assert cmd == t.COMDate() def testDateObjectFromCOMDate(self): cmd=self.tc.DateObjectFromCOMDate(37435.7604282) t=mx.DateTime.DateTime(2002,6,28,18,15,0) t2=mx.DateTime.DateTime(2002,6,28,18,15,2) assert t2>cmd>t def testDate(self): assert mx.DateTime.Date(1980,11,4)==self.tc.Date(1980,11,4) def testTime(self): assert mx.DateTime.Time(13,11,4)==self.tc.Time(13,11,4) def testTimestamp(self): t=mx.DateTime.DateTime(2002,6,28,18,15,1) obj=self.tc.Timestamp(2002,6,28,18,15,1) assert t == obj import time class TestPythonTimeConverter(TimeConverterInterfaceTest): def setUp(self): self.tc=adodbapi.pythonTimeConverter() def testCOMDate(self): mk = time.mktime((2002,6,28,18,15,1, 4,31+28+31+30+31+28,-1)) t=time.localtime(mk) # Fri, 28 Jun 2002 18:15:01 +0000 cmd=self.tc.COMDate(t) assert abs(cmd - 37435.7604282) < 1.0/24,"%f more than an hour wrong" % cmd def testDateObjectFromCOMDate(self): cmd=self.tc.DateObjectFromCOMDate(37435.7604282) t1=time.gmtime(time.mktime((2002,6,28,0,14,1, 4,31+28+31+30+31+28,-1))) #there are errors in the implementation of gmtime which we ignore t2=time.gmtime(time.mktime((2002,6,29,12,14,2, 4,31+28+31+30+31+28,-1))) assert t1<cmd<t2, '"%s" should be about 2002-6-28 12:15:01'%repr(cmd) def testDate(self): t1=time.mktime((2002,6,28,18,15,1, 4,31+28+31+30+31+30,0)) t2=time.mktime((2002,6,30,18,15,1, 4,31+28+31+30+31+28,0)) obj=self.tc.Date(2002,6,29) assert t1< time.mktime(obj)<t2,obj def testTime(self): self.assertEquals( self.tc.Time(18,15,2),time.gmtime(18*60*60+15*60+2)) def testTimestamp(self): t1=time.localtime(time.mktime((2002,6,28,18,14,1, 4,31+28+31+30+31+28,-1))) t2=time.localtime(time.mktime((2002,6,28,18,16,1, 4,31+28+31+30+31+28,-1))) obj=self.tc.Timestamp(2002,6,28,18,15,2) assert t1< obj <t2,obj if config.doDateTimeTest: import datetime class TestPythonDateTimeConverter(TimeConverterInterfaceTest): def setUp(self): self.tc=adodbapi.pythonDateTimeConverter() def testCOMDate(self): t=datetime.datetime( 2002,6,28,18,15,1) # Fri, 28 Jun 2002 18:15:01 +0000 cmd=self.tc.COMDate(t) assert abs(cmd - 37435.7604282) < 1.0/24,"more than an hour wrong" def testDateObjectFromCOMDate(self): cmd=self.tc.DateObjectFromCOMDate(37435.7604282) t1=datetime.datetime(2002,6,28,18,14,1) t2=datetime.datetime(2002,6,28,18,16,1) assert t1<cmd<t2,cmd def testDate(self): t1=datetime.date(2002,6,28) t2=datetime.date(2002,6,30) obj=self.tc.Date(2002,6,29) assert t1< obj <t2,obj def testTime(self): self.assertEquals( self.tc.Time(18,15,2).isoformat()[:8],'18:15:02') def testTimestamp(self): t1=datetime.datetime(2002,6,28,18,14,1) t2=datetime.datetime(2002,6,28,18,16,1) obj=self.tc.Timestamp(2002,6,28,18,15,2) assert t1< obj <t2,obj suites=[] if config.doMxDateTimeTest: suites.append( unittest.makeSuite(TestMXDateTimeConverter,'test')) if config.doDateTimeTest: suites.append( unittest.makeSuite(TestPythonDateTimeConverter,'test')) suites.append( unittest.makeSuite(TestPythonTimeConverter,'test')) if config.doAccessTest: suites.append( unittest.makeSuite(TestADOwithAccessDB,'test')) if config.doSqlServerTest: suites.append( unittest.makeSuite(TestADOwithSQLServer,'test')) if config.doMySqlTest: suites.append( unittest.makeSuite(TestADOwithMySql,'test')) if config.doPostgresTest: suites.append( unittest.makeSuite(TestADOwithPostgres,'test')) suite=unittest.TestSuite(suites) if __name__ == '__main__': defaultDateConverter=adodbapi.dateconverter print __doc__ print "Default Date Converter is %s" %(defaultDateConverter,) unittest.TextTestRunner().run(suite) if config.iterateOverTimeTests: for test,dateconverter in ( (1,adodbapi.pythonTimeConverter), (config.doMxDateTimeTest,adodbapi.mxDateTimeConverter), (config.doDateTimeTest,adodbapi.pythonDateTimeConverter) ): if test and not isinstance(defaultDateConverter,dateconverter): adodbapi.dateconverter=dateconverter() print "Changed dateconverter to " print adodbapi.dateconverter unittest.TextTestRunner().run(suite) --- NEW FILE: .cvsignore --- dbapi20.pyc adodbapitestconfig.pyc --- NEW FILE: testADOdbapiConfig.py --- # Configure this in order to run the testcases. "testADOdbapiConfig.py v 2.4.0" import os import sys print(sys.version) #attempt to use the copy of adodbapi in this directory's parent if sys.version[0] < '3': # only when running Py2.n cwd = os.getcwd() if 'P3k' not in cwd: # and not in the Python 3 test folder adoPath = os.path.normpath(cwd + '/../adodbapi.py') if os.path.exists(adoPath): if adoPath not in sys.path: sys.path.insert(1,os.path.dirname(adoPath)) import adodbapi # testADOdbapi.py will import this same version when we return try: print adodbapi.version # show version except: print '"adodbapi.version" not present or not working.' print __doc__ doAllTests = True doAccessTest = True or doAllTests doSqlServerTest = False or doAllTests doMySqlTest = False or doAllTests doPostgresTest = False # or doAllTests try: #If mx extensions are installed, use mxDateTime import mx.DateTime doMxDateTimeTest=True except: doMxDateTimeTest=False #Requires eGenixMXExtensions doDateTimeTest=True #Requires Python 2.3 Alpha2 iterateOverTimeTests = False or doAllTests if doAccessTest: _accessdatasource = "test.mdb" #set to None for automatic creation if not os.access(_accessdatasource,os.F_OK): _accessdatasource = None if _accessdatasource == None: # following setup code borrowed from pywin32 odbc test suite # kindly contributed by Frank Millman. import tempfile import os try: from win32com.client.gencache import EnsureDispatch from win32com.client import constants win32 = True except ImportError: #perhaps we are running IronPython win32 = False if not win32: #iron Python from System import Activator, Type _accessdatasource = os.path.join(tempfile.gettempdir(), "test_odbc.mdb") if os.path.isfile(_accessdatasource): os.unlink(_accessdatasource) # Create a brand-new database - what is the story with these? for suffix in (".36", ".35", ".30"): try: if win32: dbe = EnsureDispatch("DAO.DBEngine" + suffix) else: type= Type.GetTypeFromProgID("DAO.DBEngine" + suffix) dbe = Activator.CreateInstance(type) break except: pass else: raise RuntimeError("Can't find a DB engine") print ' ...Creating ACCESS db at',_accessdatasource if win32: workspace = dbe.Workspaces(0) newdb = workspace.CreateDatabase(_accessdatasource, constants.dbLangGeneral, constants.dbEncrypt) else: newdb = dbe.CreateDatabase(_accessdatasource,';LANGID=0x0409;CP=1252;COUNTRY=0') newdb.Close() connStrAccess = r"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _accessdatasource # for ODBC connection try... # connStrAccess = "Driver={Microsoft Access Driver (*.mdb)};db=%s;Uid=;Pwd=;" + _accessdatasource if doSqlServerTest: _computername=r".\SQLEXPRESS" #or name of computer with SQL Server _databasename="Northwind" #or something else #_username="guest" #_password="12345678" connStrSQLServer = r"Provider=SQLOLEDB.1; Integrated Security=SSPI; Initial Catalog=%s;Data Source=%s" %(_databasename, _computername) #connStrSQLServer = r"Provider=SQLOLEDB.1; User ID=%s; Password=%s; Initial Catalog=%s;Data Source=%s" %(_username,_password,_databasename, _computername) print ' ...Testing MS-SQL login...' try: s = adodbapi.connect(connStrSQLServer) #connect to server s.close() except adodbapi.DatabaseError, inst: print inst.args[0] # should be the error message doSqlServerTest = False if doMySqlTest: import socket try: _computername = socket.gethostbyname('kf7xm.ham-radio-op.net') except: _computername = '127.0.0.1' _databasename='test' _username = 'Test' _password = '12345678' _driver="MySQL ODBC 5.1 Driver" # or _driver="MySQL ODBC 3.51 Driver" connStrMySql = 'Driver={%s};Server=%s;Port=3306;Database=%s;user=%s;password=%s;Option=3;' % \ (_driver,_computername,_databasename,_username,_password) print ' ...Testing MySql login...' try: s = adodbapi.connect(connStrMySql) #connect to server s.close() except adodbapi.DatabaseError, inst: print inst.args[0] # should be the error message doMySqlTest = False if doPostgresTest: import socket try: _computername = socket.gethostbyname('kf7xm.ham-radio-op.net') except: _computername = '127.0.0.1' _databasename='test' _username = 'Test' _password = '12345678' _driver="PostgreSQL Unicode" connStrPostgres = 'Driver={%s};Server=%s;Database=%s;user=%s;password=%s;' % \ (_driver,_computername,_databasename,_username,_password) print ' ...Testing PostgreSQL login...' try: s = adodbapi.connect(connStrPostgres) #connect to server s.close() except adodbapi.DatabaseError, inst: print inst.args[0] # should be the error message doPostgresTest = False Index: db_print.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/adodbapi/tests/db_print.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** db_print.py 2 Feb 2009 03:48:41 -0000 1.3 --- db_print.py 31 Jul 2010 05:48:10 -0000 1.4 *************** *** 3,7 **** import adodbapi adodbapi.adodbapi.verbose = True # adds details to the sample printout ! # connection string templates from http://www.connectionstrings.com # Switch test providers by changing the "if True" below --- 3,10 ---- import adodbapi adodbapi.adodbapi.verbose = True # adds details to the sample printout ! import adodbapi.ado_consts as adc ! #tell the server we are not planning to update... ! adodbapi.adodbapi.defaultIsolationLevel = adc.adXactBrowse ! #----------------- Create connection string ----------------------------------- # connection string templates from http://www.connectionstrings.com # Switch test providers by changing the "if True" below *************** *** 46,57 **** % (_computername, _databasename, _username, _password) # NOTE! user's PC must have OLE support installed in IBM Client Access Express ! #----------------- ! ! #tell the server we are not planning to update... ! adodbapi.adodbapi.defaultIsolationLevel = adodbapi.adodbapi.adXactBrowse ! ! #and we want a local cursor (so that we will have an accurate rowcount) ! adodbapi.adodbapi.defaultCursorLocation = adodbapi.adodbapi.adUseClient #create the connection con = adodbapi.connect(constr) --- 49,55 ---- % (_computername, _databasename, _username, _password) # NOTE! user's PC must have OLE support installed in IBM Client Access Express ! #---------------------------------- + # ------------------------ START HERE ------------------------------------- #create the connection con = adodbapi.connect(constr) *************** *** 62,66 **** #run an SQL statement on the cursor sql = 'select * from %s' % _table_name - print 'Executing the command: "%s"' % sql c.execute(sql) --- 60,63 ---- *************** *** 70,85 **** print print 'result data description is:' ! print ' NAME TypeCd DispSize IntrnlSz Prec Scale Null?' for d in c.description: ! print ('%16s %6d %8d %8d %4d %5d %5d') % d print ! print 'result first ten records are:' #get the results ! db = c.fetchmany(10) #print them for rec in db: ! print repr(rec) c.close() --- 67,88 ---- print print 'result data description is:' ! print ' NAME Type DispSize IntrnlSz Prec Scale Null?' for d in c.description: ! print ('%16s %-12s %8d %8d %4d %5d %s') % \ ! (d[0], adc.adTypeNames[d[1]], d[2], d[3], d[4],d[5], bool(d[6])) print ! print 'str() of first five records are...' #get the results ! db = c.fetchmany(5) #print them for rec in db: ! print rec ! ! print ! print 'repr() of next row is...' ! print repr(c.next()) ! print c.close() --- NEW FILE: testRun.bat --- if "%1" == "" goto skip_1 set PYTHON=%1 goto skip_python :skip_1 if not "%PYTHON%"=="" goto skip_python set PYTHON=python :skip_python Echo on echo . echo . del *.pyc echo . REM unit test call %PYTHON% testADOdbapi.py echo . echo . REM generic test call %PYTHON% test_adodbapi_dbapi20.py echo . echo . pause Testing complete Index: test_adodbapi_dbapi20.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/adodbapi/tests/test_adodbapi_dbapi20.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** test_adodbapi_dbapi20.py 6 Feb 2009 03:35:11 -0000 1.5 --- test_adodbapi_dbapi20.py 31 Jul 2010 05:48:10 -0000 1.6 *************** *** 6,15 **** import os, sys ! #attempt to find adodbapi in this directory's parent ! cwd = os.getcwd() ! adoPath = os.path.normpath(cwd + '/../adodbapi.py') ! if os.path.exists(adoPath): ! if adoPath not in sys.path: ! sys.path.insert(1,os.path.dirname(adoPath)) import adodbapi --- 6,16 ---- import os, sys ! if sys.version[0] < '3': ! # attempt to find adodbapi in this directory's parent ! cwd = os.getcwd() ! adoPath = os.path.normpath(cwd + '/../adodbapi.py') ! if os.path.exists(adoPath): ! if adoPath not in sys.path: ! sys.path.insert(1,os.path.dirname(adoPath)) import adodbapi |
From: Roger U. <ru...@us...> - 2010-06-18 17:25:59
|
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/framework/editor In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv29079 Modified Files: document.py Log Message: Close change notification handle when FileWatchingThread exits Index: document.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/framework/editor/document.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** document.py 6 May 2010 16:30:03 -0000 1.14 --- document.py 18 Jun 2010 17:25:51 -0000 1.15 *************** *** 318,319 **** --- 318,321 ---- # close a circular reference self.doc = None + if self.watchEvent: + win32api.FindCloseChangeNotification(self.watchEvent) |
From: Roger U. <ru...@us...> - 2010-06-06 08:05:54
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv27900 Modified Files: win32file.i Log Message: Add Wow64DisableWow64FsRedirection and Wow64RevertWow64FsRedirection Index: win32file.i =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32file.i,v retrieving revision 1.108 retrieving revision 1.109 diff -C2 -d -r1.108 -r1.109 *** win32file.i 5 Jul 2009 20:56:24 -0000 1.108 --- win32file.i 6 Jun 2010 08:05:45 -0000 1.109 *************** *** 5291,5294 **** --- 5291,5323 ---- } PyCFunction pfnpy_GetFullPathName=(PyCFunction)py_GetFullPathName; + + // @pyswig int|Wow64DisableWow64FsRedirection|Disables file system redirection for 32-bit processes running on a 64-bit system + // @rdesc Returns a state value to be passed to <om win32file.Wow64RevertWow64FsRedirection> + // @comm Requires 64-bit XP or later + static PyObject *py_Wow64DisableWow64FsRedirection(PyObject *self, PyObject *args) + { + VOID *state; + CHECK_PFN(Wow64DisableWow64FsRedirection); + if (!PyArg_ParseTuple(args, ":Wow64DisableWow64FsRedirection")) + return NULL; + if (!(*pfnWow64DisableWow64FsRedirection)(&state)) + return PyWin_SetAPIError("Wow64DisableWow64FsRedirection"); + return PyWinLong_FromVoidPtr(state); + } + + // @pyswig |Wow64RevertWow64FsRedirection|Reenables file system redirection for 32-bit processes running on a 64-bit system + // @comm Requires 64-bit XP or later + static PyObject *py_Wow64RevertWow64FsRedirection(PyObject *self, PyObject *args) + { + VOID *state; + CHECK_PFN(Wow64RevertWow64FsRedirection); + // @pyparm int|OldValue||State returned from Wow64DisableWow64FsRedirection + if (!PyArg_ParseTuple(args, "O&:Wow64RevertWow64FsRedirection", PyWinLong_AsVoidPtr, &state)) + return NULL; + if (!(*pfnWow64RevertWow64FsRedirection)(state)) + return PyWin_SetAPIError("Wow64RevertWow64FsRedirection"); + Py_INCREF(Py_None); + return Py_None; + } %} *************** *** 5342,5345 **** --- 5371,5377 ---- %native (SfcIsFileProtected) py_SfcIsFileProtected; + %native (Wow64DisableWow64FsRedirection) py_Wow64DisableWow64FsRedirection; + %native (Wow64RevertWow64FsRedirection) py_Wow64RevertWow64FsRedirection; + %init %{ |
From: Vernon C. <kf...@us...> - 2010-06-05 21:59:58
|
Update of /cvsroot/pywin32/pywin32/adodbapi In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv5143 Modified Files: adodbapi.py Log Message: Spelling correction Index: adodbapi.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/adodbapi/adodbapi.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** adodbapi.py 31 May 2010 00:25:43 -0000 1.12 --- adodbapi.py 5 Jun 2010 21:59:48 -0000 1.13 *************** *** 716,720 **** display_size=None null_ok= bool(f.Attributes & adc.adFldMayBeNull) #v2.1 Cole ! desc.append((f.Name, f.Type, display_size, f.Definedsize, f.Precision, f.NumericScale, null_ok)) self.description = desc --- 716,720 ---- display_size=None null_ok= bool(f.Attributes & adc.adFldMayBeNull) #v2.1 Cole ! desc.append((f.Name, f.Type, display_size, f.DefinedSize, f.Precision, f.NumericScale, null_ok)) self.description = desc |
From: Roger U. <ru...@us...> - 2010-06-03 18:40:31
|
Update of /cvsroot/pywin32/pywin32/com/win32com/client In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv12476 Modified Files: genpy.py Log Message: Fix __str__ in py3k for objects with a default property Index: genpy.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32com/client/genpy.py,v retrieving revision 1.66 retrieving revision 1.67 diff -C2 -d -r1.66 -r1.67 *** genpy.py 27 Mar 2009 12:34:43 -0000 1.66 --- genpy.py 3 Jun 2010 18:40:23 -0000 1.67 *************** *** 491,495 **** print >> stream, "\t\t\treturn repr(self)" print >> stream, "\tdef __str__(self, *args):" ! print >> stream, "\t\treturn str(self.__unicode__(*args))" print >> stream, "\tdef __int__(self, *args):" print >> stream, "\t\treturn int(self.__call__(*args))" --- 491,498 ---- print >> stream, "\t\t\treturn repr(self)" print >> stream, "\tdef __str__(self, *args):" ! if sys.version_info > (3,0): ! print >> stream, "\t\treturn str(self.__call__(*args))" ! else: ! print >> stream, "\t\treturn str(self.__unicode__(*args))" print >> stream, "\tdef __int__(self, *args):" print >> stream, "\t\treturn int(self.__call__(*args))" |
From: Roger U. <ru...@us...> - 2010-05-31 00:25:53
|
Update of /cvsroot/pywin32/pywin32/adodbapi In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv11253 Modified Files: adodbapi.py Log Message: Update syntax of raise statements Index: adodbapi.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/adodbapi/adodbapi.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** adodbapi.py 3 May 2010 08:41:06 -0000 1.11 --- adodbapi.py 31 May 2010 00:25:43 -0000 1.12 *************** *** 644,648 **** def _namedToQmark(self,op,parms): #convert from 'named' paramstyle to ADO required '?'mark parameters if type(parms) != type({}): ! raise (ProgrammingError), "paramstyle 'named' requires dict parameters" outOp = '' outparms=[] --- 644,648 ---- def _namedToQmark(self,op,parms): #convert from 'named' paramstyle to ADO required '?'mark parameters if type(parms) != type({}): ! raise ProgrammingError("paramstyle 'named' requires dict parameters") outOp = '' outparms=[] *************** *** 1101,1105 **** if isinstance(d,decimal.Decimal): return adc.adDecimal ! raise (DataError), 'cannot convert "%s" (type=%s) to ADO'%(repr(d),tp) class DBAPITypeObject(object): --- 1101,1105 ---- if isinstance(d,decimal.Decimal): return adc.adDecimal ! raise DataError('cannot convert "%s" (type=%s) to ADO'%(repr(d),tp)) class DBAPITypeObject(object): |
From: Roger U. <ru...@us...> - 2010-05-22 00:59:48
|
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/scintilla In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv10157 Modified Files: configui.py Log Message: Fix resetting of default background for syles that don't use CLR_INVALID Index: configui.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/scintilla/configui.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** configui.py 9 Feb 2009 01:05:54 -0000 1.7 --- configui.py 22 May 2010 00:59:40 -0000 1.8 *************** *** 180,184 **** if isDef: # Being reset to the default color style = self.GetSelectedStyle() ! style.background = CLR_INVALID self.UpdateUIForStyle(style) self.scintilla.ApplyFormattingStyles(0) --- 180,184 ---- if isDef: # Being reset to the default color style = self.GetSelectedStyle() ! style.background = style.default_background self.UpdateUIForStyle(style) self.scintilla.ApplyFormattingStyles(0) *************** *** 209,214 **** self.GetDlgItem(win32ui.IDC_BUTTON3).EnableWindow(not style.IsBasedOnDefault()) ! self.butIsDefaultBackground.SetCheck(style.background == CLR_INVALID) ! self.GetDlgItem(win32ui.IDC_BUTTON4).EnableWindow(style.background != CLR_INVALID) bold = format[1] & win32con.CFE_BOLD != 0; italic = format[1] & win32con.CFE_ITALIC != 0 --- 209,214 ---- self.GetDlgItem(win32ui.IDC_BUTTON3).EnableWindow(not style.IsBasedOnDefault()) ! self.butIsDefaultBackground.SetCheck(style.background == style.default_background) ! self.GetDlgItem(win32ui.IDC_BUTTON4).EnableWindow(style.background != style.default_background) bold = format[1] & win32con.CFE_BOLD != 0; italic = format[1] & win32con.CFE_ITALIC != 0 |
From: Roger U. <ru...@us...> - 2010-05-18 18:57:40
|
Update of /cvsroot/pywin32/pywin32/com/win32comext/shell/src In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv12570 Modified Files: shell.cpp Log Message: Reverse order in which IExtractIcon and IExtractIconW are registered. When UNICODE is defined, both IID's are the same, and the registration function iterates backward, so whichever is first wins out. Index: shell.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/com/win32comext/shell/src/shell.cpp,v retrieving revision 1.75 retrieving revision 1.76 diff -C2 -d -r1.75 -r1.76 *** shell.cpp 25 Jan 2010 23:32:29 -0000 1.75 --- shell.cpp 18 May 2010 18:57:32 -0000 1.76 *************** *** 3255,3260 **** PYCOM_INTERFACE_SERVER_ONLY(ContextMenu2), PYCOM_INTERFACE_SERVER_ONLY(ContextMenu3), - PYCOM_INTERFACE_FULL(ExtractIcon), PYCOM_INTERFACE_FULL(ExtractIconW), PYCOM_INTERFACE_CLIENT_ONLY (ExtractImage), PYCOM_INTERFACE_FULL(ShellExtInit), --- 3255,3260 ---- PYCOM_INTERFACE_SERVER_ONLY(ContextMenu2), PYCOM_INTERFACE_SERVER_ONLY(ContextMenu3), PYCOM_INTERFACE_FULL(ExtractIconW), + PYCOM_INTERFACE_FULL(ExtractIcon), PYCOM_INTERFACE_CLIENT_ONLY (ExtractImage), PYCOM_INTERFACE_FULL(ShellExtInit), |
From: Roger U. <ru...@us...> - 2010-05-18 15:57:52
|
Update of /cvsroot/pywin32/pywin32/win32/Lib In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv12667 Modified Files: win32pdhutil.py Log Message: Accept multiple counters in CallBack for BrowseCounters Index: win32pdhutil.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/Lib/win32pdhutil.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** win32pdhutil.py 14 Nov 2008 00:22:25 -0000 1.13 --- win32pdhutil.py 18 May 2010 15:57:41 -0000 1.14 *************** *** 136,152 **** # NOTE: This BrowseCallback doesn't seem to work on Vista for markh. # XXX - look at why!? ! def BrowseCallBackDemo(counter): ! machine, object, instance, parentInstance, index, counterName = \ ! win32pdh.ParseCounterPath(counter) ! result = GetPerformanceAttributes(object, counterName, instance, index, ! win32pdh.PDH_FMT_DOUBLE, machine) ! print "Value of '%s' is" % counter, result ! print "Added '%s' on object '%s' (machine %s), instance %s(%d)-parent of %s" \ ! % (counterName, object, machine, instance, index, parentInstance) def browse(callback = BrowseCallBackDemo, title="Python Browser", level=win32pdh.PERF_DETAIL_WIZARD): ! win32pdh.BrowseCounters(None,0, callback, level, title) if __name__=='__main__': --- 136,157 ---- # NOTE: This BrowseCallback doesn't seem to work on Vista for markh. # XXX - look at why!? ! # Some counters on Vista require elevation, and callback would previously ! # clear exceptions without printing them. ! def BrowseCallBackDemo(counters): ! ## BrowseCounters can now return multiple counter paths ! for counter in counters: ! machine, object, instance, parentInstance, index, counterName = \ ! win32pdh.ParseCounterPath(counter) ! result = GetPerformanceAttributes(object, counterName, instance, index, ! win32pdh.PDH_FMT_DOUBLE, machine) ! print "Value of '%s' is" % counter, result ! print "Added '%s' on object '%s' (machine %s), instance %s(%d)-parent of %s" \ ! % (counterName, object, machine, instance, index, parentInstance) ! return 0 def browse(callback = BrowseCallBackDemo, title="Python Browser", level=win32pdh.PERF_DETAIL_WIZARD): ! win32pdh.BrowseCounters(None,0, callback, level, title, ReturnMultiple=True) if __name__=='__main__': |
From: Roger U. <ru...@us...> - 2010-05-18 15:54:41
|
Update of /cvsroot/pywin32/pywin32/win32/src In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv12132 Modified Files: win32pdhmodule.cpp Log Message: Various improvements to BrowseCounters: Accept keyword args Allow multiple counters to be passed to Callback function Accept extra arg to be passed to callback function Add a few extra flags Accept InitialPath to be used as initially selected counter Accept DataSource to read from pdh log file Print exceptions when Python errors occur during callback Create a class for TCHAR that frees itself to simplify cleanup More consistent use of Py_*_ALLOW_THREAD macros Index: win32pdhmodule.cpp =================================================================== RCS file: /cvsroot/pywin32/pywin32/win32/src/win32pdhmodule.cpp,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** win32pdhmodule.cpp 8 Dec 2008 13:16:38 -0000 1.19 --- win32pdhmodule.cpp 18 May 2010 15:54:33 -0000 1.20 *************** *** 16,19 **** --- 16,24 ---- #include "pdhmsg.h" + /* + According to MSDN, Pdh calls are thread safe, although there was a bug + in Win2k that might make it appear to not be. Plus, the PyW32* macros + weren't actually used most places, so would be no point in using them anywhere. + // It appears PDH it not thread safe! // Use a critical section to protect calls into it [...1360 lines suppressed...] PYWIN_MODULE_INIT_PREPARE(win32pdh, win32pdh_functions, "A module, encapsulating the Windows Performance Data Helpers API"); ! InitializeCriticalSection(&critSec); PyDict_SetItemString(dict, "error", PyWinExc_ApiError); --- 1218,1222 ---- PYWIN_MODULE_INIT_PREPARE(win32pdh, win32pdh_functions, "A module, encapsulating the Windows Performance Data Helpers API"); ! // InitializeCriticalSection(&critSec); PyDict_SetItemString(dict, "error", PyWinExc_ApiError); *************** *** 1149,1152 **** --- 1244,1249 ---- ADD_CONSTANT(PERF_DETAIL_EXPERT); ADD_CONSTANT(PERF_DETAIL_WIZARD); + ADD_CONSTANT(PDH_PATH_WBEM_RESULT); + ADD_CONSTANT(PDH_PATH_WBEM_INPUT); // ADD_CONSTANT(); PYWIN_MODULE_INIT_RETURN_SUCCESS; |
From: Roger U. <ru...@us...> - 2010-05-14 22:31:26
|
Update of /cvsroot/pywin32/pywin32 In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv10221 Modified Files: setup.py Log Message: Always build win32pdh as unicode Index: setup.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/setup.py,v retrieving revision 1.109 retrieving revision 1.110 diff -C2 -d -r1.109 -r1.110 *** setup.py 8 Jul 2009 02:13:00 -0000 1.109 --- setup.py 14 May 2010 22:31:15 -0000 1.110 *************** *** 1483,1487 **** win32/src/win32net/win32netuser.cpp """), ! ("win32pdh", "", None), ("win32pipe", "", None, None, 'win32/src/win32pipe.i win32/src/win32popen.cpp'), ("win32print", "winspool user32 gdi32", None, 0x0500), --- 1483,1487 ---- win32/src/win32net/win32netuser.cpp """), ! ("win32pdh", "", True), ("win32pipe", "", None, None, 'win32/src/win32pipe.i win32/src/win32popen.cpp'), ("win32print", "winspool user32 gdi32", None, 0x0500), |
From: Mark H. <mha...@us...> - 2010-05-12 02:44:10
|
Update of /cvsroot/pywin32/pywin32/win32/Demos/service In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv26249 Added Files: nativePipeTestService.py Log Message: add a sample of a service being hosted by python.exe --- NEW FILE: nativePipeTestService.py --- # This is an example of a service hosted by python.exe rather than # pythonservice.exe. # Note that it is very rare that using python.exe is a better option # than the default pythonservice.exe - the latter has better error handling # so that if Python itself can't be initialized or there are very early # import errors, you will get error details written to the event log. When # using python.exe instead, you are forced to wait for the interpreter startup # and imports to succeed before you are able to effectively setup your own # error handling. # So in short, please make sure you *really* want to do this, otherwise just # stick with the default. import sys import os import win32serviceutil import servicemanager from pipeTestService import TestPipeService class NativeTestPipeService(TestPipeService): _svc_name_ = "PyNativePipeTestService" _svc_display_name_ = "Python Native Pipe Test Service" _svc_description_ = "Tests Python.exe hosted services" # tell win32serviceutil we have a custom executable and custom args # so registration does the right thing. _exe_name_ = sys.executable _exe_args_ = '"' + os.path.abspath(sys.argv[0]) + '"' def main(): if len(sys.argv)==1: # service must be starting... # for the sake of debugging etc, we use win32traceutil to see # any unhandled exceptions and print statements. import win32traceutil print "service is starting..." print "(execute this script with '--help' if that isn't what you want)" servicemanager.Initialize() servicemanager.PrepareToHostSingle(NativeTestPipeService) # Now ask the service manager to fire things up for us... servicemanager.StartServiceCtrlDispatcher() print "service done!" else: win32serviceutil.HandleCommandLine(NativeTestPipeService) if __name__=='__main__': try: main() except (SystemExit, KeyboardInterrupt): raise except: print "Something went bad!" import traceback traceback.print_exc() |
From: Roger U. <ru...@us...> - 2010-05-09 14:11:59
|
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/debugger In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv30025 Modified Files: debugger.py Log Message: Pass name to HierListItem.__init__ Index: debugger.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/debugger/debugger.py,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** debugger.py 14 Jan 2009 12:11:46 -0000 1.24 --- debugger.py 9 May 2010 14:11:51 -0000 1.25 *************** *** 53,57 **** class HierFrameItem(HierListItem): def __init__(self, frame, debugger): ! HierListItem.__init__(self, frame, None) self.debugger = debugger def GetText(self): --- 53,57 ---- class HierFrameItem(HierListItem): def __init__(self, frame, debugger): ! HierListItem.__init__(self, frame, repr(frame)) self.debugger = debugger def GetText(self): |
From: Roger U. <ru...@us...> - 2010-05-06 16:30:28
|
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/scintilla In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv11304 Modified Files: document.py view.py Log Message: Bug #2986020 - Attempt to encode script contents before opening file Index: view.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/scintilla/view.py,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** view.py 31 Jan 2009 05:56:01 -0000 1.35 --- view.py 6 May 2010 16:30:20 -0000 1.36 *************** *** 387,398 **** def SaveTextFile(self, filename): doc = self.GetDocument() ! # Open in binary mode as scintilla itself ensures the ! # line endings are already appropriate, and our doc save ! # method handles encoding, BOMs, etc. ! f = open(filename, 'wb') ! try: ! doc._SaveTextToFile(self, f) ! finally: ! f.close() doc.SetModifiedFlag(0) return 1 --- 387,391 ---- def SaveTextFile(self, filename): doc = self.GetDocument() ! doc._SaveTextToFile(self, filename) doc.SetModifiedFlag(0) return 1 Index: document.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/scintilla/document.py,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** document.py 31 Jan 2009 05:28:24 -0000 1.10 --- document.py 6 May 2010 16:30:20 -0000 1.11 *************** *** 134,142 **** view.SendScintilla(scintillacon.SCI_SETEOLMODE, eol_mode) ! def _SaveTextToFile(self, view, f): s = view.GetTextRange() # already decoded from scintilla's encoding source_encoding = None if self.bom: - f.write(self.bom) source_encoding = self.source_encoding else: --- 134,141 ---- view.SendScintilla(scintillacon.SCI_SETEOLMODE, eol_mode) ! def _SaveTextToFile(self, view, filename): s = view.GetTextRange() # already decoded from scintilla's encoding source_encoding = None if self.bom: source_encoding = self.source_encoding else: *************** *** 153,160 **** source_encoding = 'latin1' ! f.write(s.encode(source_encoding)) self.SetModifiedFlag(0) - def FinalizeViewCreation(self, view): pass --- 152,168 ---- source_encoding = 'latin1' ! ## encode data before opening file so script is not lost if encoding fails ! file_contents = s.encode(source_encoding) ! # Open in binary mode as scintilla itself ensures the ! # line endings are already appropriate ! f = open(filename, 'wb') ! try: ! if self.bom: ! f.write(self.bom) ! f.write(file_contents) ! finally: ! f.close() self.SetModifiedFlag(0) def FinalizeViewCreation(self, view): pass |
From: Roger U. <ru...@us...> - 2010-05-06 16:30:11
|
Update of /cvsroot/pywin32/pywin32/Pythonwin/pywin/framework/editor In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv11084 Modified Files: document.py Log Message: Bug #2986020 - Attempt to encode script contents before opening file Index: document.py =================================================================== RCS file: /cvsroot/pywin32/pywin32/Pythonwin/pywin/framework/editor/document.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** document.py 5 Jan 2009 11:09:20 -0000 1.13 --- document.py 6 May 2010 16:30:03 -0000 1.14 *************** *** 79,82 **** --- 79,88 ---- win32ui.MessageBox("Error - could not save file\r\n\r\n%s"%details) return 0 + except UnicodeEncodeError, details: + win32ui.MessageBox("Encoding failed: \r\n%s"%details + + '\r\nPlease add desired source encoding as first line of file, eg \r\n' + + '# -*- coding: mbcs -*-', + "File save failed") + return 0 self.SetModifiedFlag(0) # No longer dirty self.bDeclinedReload = 0 # They probably want to know if it changes again! |
From: Vernon C. <kf...@us...> - 2010-05-03 08:41:43
|
Update of /cvsroot/pywin32/pywin32 In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv16339 Modified Files: CHANGES.txt Log Message: add adodbapi user-submitted patches, update change.txt Index: CHANGES.txt =================================================================== RCS file: /cvsroot/pywin32/pywin32/CHANGES.txt,v retrieving revision 1.52 retrieving revision 1.53 diff -C2 -d -r1.52 -r1.53 *** CHANGES.txt 15 Oct 2009 05:31:26 -0000 1.52 --- CHANGES.txt 3 May 2010 08:41:02 -0000 1.53 *************** *** 8,12 **** Since build 214: ---------------- ! * Fix problem causing ASP pages to fail when reloaded. --- 8,19 ---- Since build 214: ---------------- ! * Update adodbapi to version 2.3.0 -- this is includes major refactoring and ! specifically adds features for django support, including the ability for the ! programmer to change ado's SQL "paramstyle" at run time to select between ! 'qmark', 'format' and 'named' methods of passing SQL parameters. ! ** also, in response to user requests, adodbapi will now use client-side ! cursors by default. This will make rowcount and stored procedure return ! parameter values more readily available. ! * Fix problem causing ASP pages to fail when reloaded. |