Skip to content

Commit

Permalink
Convert adodbapi source files to python 3 syntax.
Browse files Browse the repository at this point in the history
Done via 2to3 with fixers:
  -f basestring -f exec -f except -f dict -f import -f imports -f next
  -f nonzero -f raise -f raw_input -f long -f standarderror -f types
  -f unicode -f urllib -f xrange -f future
  • Loading branch information
mhammond committed Jul 5, 2020
1 parent 9a11ef0 commit 7a65a7a
Show file tree
Hide file tree
Showing 13 changed files with 77 additions and 77 deletions.
6 changes: 3 additions & 3 deletions adodbapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
import time

if sys.version_info < (3,0): # in Python 2, define all symbols, just like the bad old way
from apibase import *
from .apibase import *
VariantConversionMap = MultiMap # old name. Should use apibase.MultiMap
from ado_consts import *
from .ado_consts import *
_makeByteBuffer = buffer
else:
# but if the user is running Python 3, then keep the dictionary clean
Expand All @@ -19,7 +19,7 @@
from .apibase import NUMBER, STRING, BINARY, DATETIME, ROWID
_makeByteBuffer = bytes

from adodbapi import connect, Connection, __version__, dateconverter, Cursor
from .adodbapi import connect, Connection, __version__, dateconverter, Cursor

def Binary(aString):
"""This function constructs an object capable of holding a binary (long) string value. """
Expand Down
20 changes: 10 additions & 10 deletions adodbapi/adodbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
or IronPython version 2.7 and later,
or, after running through 2to3.py, CPython 3.4 or later.
"""
from __future__ import print_function


__version__ = '2.6.2.0'
version = 'adodbapi v' + __version__
Expand Down Expand Up @@ -80,13 +80,13 @@ def getIndexedValue(obj,index):
Mapping = dict # this will handle the most common case

# --- define objects to smooth out Python3000 <-> Python 2.x differences
unicodeType = unicode #this line will be altered by 2to3.py to '= str'
longType = long #this line will be altered by 2to3.py to '= int'
unicodeType = str #this line will be altered by 2to3.py to '= str'
longType = int #this line will be altered by 2to3.py to '= int'
if sys.version_info >= (3,0): #python 3.x
StringTypes = str
maxint = sys.maxsize
else: #python 2.x
StringTypes = (str,unicode) # will be messed up by 2to3 but never used
StringTypes = (str,str) # will be messed up by 2to3 but never used
maxint = sys.maxint

# ----------------- The .connect method -----------------
Expand Down Expand Up @@ -322,7 +322,7 @@ def close(self):
an Error (or subclass) exception will be raised if any operation is attempted with the connection.
The same applies to all cursor objects trying to use the connection.
"""
for crsr in self.cursors.values()[:]: # copy the list, then close each one
for crsr in list(self.cursors.values())[:]: # copy the list, then close each one
crsr.close(dont_tell_me=True) # close without back-link clearing
self.messages = []
try:
Expand Down Expand Up @@ -542,7 +542,7 @@ def prepare(self, operation):
self._description = None
self._ado_prepared = 'setup'

def next(self):
def __next__(self):
r = self.fetchone()
if r:
return r
Expand Down Expand Up @@ -784,7 +784,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
try:
_configure_parameter(p, parameters[pm_name], p.Type, parameters_known)
except (Exception) as e:
_message = u'Error Converting Parameter %s: %s, %s <- %s\n' % \
_message = 'Error Converting Parameter %s: %s, %s <- %s\n' % \
(p.Name, adc.ado_type_name(p.Type), p.Value, repr(parameters[pm_name]))
self._raiseCursorError(api.DataError, _message+'->'+repr(e.args))
else: # regular sequence of parameters
Expand All @@ -796,7 +796,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
try:
_configure_parameter(p, value, p.Type, parameters_known)
except Exception as e:
_message = u'Error Converting Parameter %s: %s, %s <- %s\n' % \
_message = 'Error Converting Parameter %s: %s, %s <- %s\n' % \
(p.Name, adc.ado_type_name(p.Type), p.Value, repr(value))
self._raiseCursorError(api.DataError, _message+'->'+repr(e.args))
i += 1
Expand All @@ -810,7 +810,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
try:
self.cmd.Parameters.Append(p)
except Exception as e:
_message = u'Error Building Parameter %s: %s, %s <- %s\n' % \
_message = 'Error Building Parameter %s: %s, %s <- %s\n' % \
(p.Name, adc.ado_type_name(p.Type), p.Value, repr(elem))
self._raiseCursorError(api.DataError, _message+'->'+repr(e.args))
else : # expecting the usual sequence of parameters
Expand All @@ -826,7 +826,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
try:
self.cmd.Parameters.Append(p)
except Exception as e:
_message = u'Error Building Parameter %s: %s, %s <- %s\n' % \
_message = 'Error Building Parameter %s: %s, %s <- %s\n' % \
(p.Name, adc.ado_type_name(p.Type), p.Value, repr(elem))
self._raiseCursorError(api.DataError, _message+'->'+repr(e.args))
i += 1
Expand Down
28 changes: 14 additions & 14 deletions adodbapi/apibase.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import decimal
import numbers
# noinspection PyUnresolvedReferences
import ado_consts as adc
from . import ado_consts as adc

verbose = False # debugging flag

Expand All @@ -25,19 +25,19 @@
NullTypes = type(None)

# --- define objects to smooth out Python3 <-> Python 2.x differences
unicodeType = unicode #this line will be altered by 2to3.py to '= str'
longType = long #this line will be altered by 2to3.py to '= int'
unicodeType = str #this line will be altered by 2to3.py to '= str'
longType = int #this line will be altered by 2to3.py to '= int'
if sys.version[0] >= '3': #python 3.x
StringTypes = str
makeByteBuffer = bytes
memoryViewType = memoryview
_BaseException = Exception
else: #python 2.x
# noinspection PyUnresolvedReferences
from exceptions import StandardError as _BaseException
from exceptions import Exception as _BaseException
memoryViewType = type(buffer(''))
makeByteBuffer = buffer
StringTypes = (str,unicode) # will be messed up by 2to3 but never used
StringTypes = (str,str) # will be messed up by 2to3 but never used

try: #jdhardy -- handle bytes under IronPython & Py3
bytes
Expand Down Expand Up @@ -345,7 +345,7 @@ def __ne__(self, other):
typeMap = { memoryViewType : adc.adVarBinary,
float : adc.adDouble,
type(None) : adc.adEmpty,
unicode : adc.adBSTR, # this line will be altered by 2to3 to 'str:'
str : adc.adBSTR, # this line will be altered by 2to3 to 'str:'
bool :adc.adBoolean, #v2.1 Cole
decimal.Decimal : adc.adDecimal }
if longType != int: #not Python 3
Expand Down Expand Up @@ -412,21 +412,21 @@ def cvtInt(variant):
return int(variant)

def cvtLong(variant): # only important in old versions where long and int differ
return long(variant)
return int(variant)

def cvtBuffer(variant):
return bytes(variant)

def cvtUnicode(variant):
return unicode(variant) # will be altered by 2to3 to 'str(variant)'
return str(variant) # will be altered by 2to3 to 'str(variant)'

def identity(x): return x

def cvtUnusual(variant):
if verbose > 1:
sys.stderr.write('Conversion called for Unusual data=%s\n' % repr(variant))
if isinstance(variant, DateTime): # COMdate or System.Date
from adodbapi import dateconverter # this will only be called when adodbapi is in use, and very rarely
from .adodbapi import dateconverter # this will only be called when adodbapi is in use, and very rarely
return dateconverter.DateObjectFromCOMDate(variant)
return variant # cannot find conversion function -- just give the data to the user

Expand All @@ -439,7 +439,7 @@ class MultiMap(dict): #builds a dictionary from {(sequence,of,keys) : function}
"""A dictionary of ado.type : function -- but you can set multiple items by passing a sequence of keys"""
#useful for defining conversion functions for groups of similar data types.
def __init__(self, aDict):
for k, v in aDict.items():
for k, v in list(aDict.items()):
self[k] = v # we must call __setitem__
def __setitem__(self, adoType, cvtFn):
"set a single item, or a whole sequence of items"
Expand All @@ -466,7 +466,7 @@ def __setitem__(self, adoType, cvtFn):

# # # # # classes to emulate the result of cursor.fetchxxx() as a sequence of sequences # # # # #
# "an ENUM of how my low level records are laid out"
RS_WIN_32, RS_ARRAY, RS_REMOTE = range(1,4)
RS_WIN_32, RS_ARRAY, RS_REMOTE = list(range(1,4))

class SQLrow(object): # a single database row
# class to emulate a sequence, so that a column may be retrieved by either number or name
Expand Down Expand Up @@ -506,14 +506,14 @@ def __getitem__(self,key): # used for row[key] type of value access
return self._getValue(self.rows.columnNames[key.lower()]) # 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__()),tr
raise er('No such key as "%s" in %s'%(repr(key),self.__repr__())).with_traceback(tr)
def __iter__(self):
return iter(self.__next__())
def __next__(self):
for n in range(self.rows.numberOfColumns):
yield self._getValue(n)
def __repr__(self): # create a human readable representation
taglist = sorted(self.rows.columnNames.items(), key=lambda x: x[1])
taglist = sorted(list(self.rows.columnNames.items()), key=lambda x: x[1])
s = "<SQLrow={"
for name, i in taglist:
s += name + ':' + repr(self._getValue(i)) + ', '
Expand Down Expand Up @@ -560,7 +560,7 @@ def __getitem__(self, item): # used for row or row,column access
try:
j = self.columnNames[j.lower()] # convert named column to numeric
except KeyError:
raise KeyError, 'adodbapi: no such column name as "%s"'%repr(j)
raise KeyError('adodbapi: no such column name as "%s"'%repr(j))
if self.recordset_format == RS_ARRAY: # retrieve from two-dimensional array
v = self.ado_results[j,i]
elif self.recordset_format == RS_REMOTE:
Expand Down
2 changes: 1 addition & 1 deletion adodbapi/examples/db_print.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
""" db_print.py -- a simple demo for ADO database reads."""
from __future__ import with_statement #needed for Python 2.5
#needed for Python 2.5

import sys
import adodbapi.ado_consts as adc
Expand Down
2 changes: 1 addition & 1 deletion adodbapi/examples/xls_write.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import with_statement # needed only if running Python 2.5
# needed only if running Python 2.5
import adodbapi
import datetime
try:
Expand Down
8 changes: 4 additions & 4 deletions adodbapi/process_connect_string.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
""" a clumsy attempt at a macro language to let the programmer execute code on the server (ex: determine 64bit)"""
import is64bit as is64bit
from . import is64bit as is64bit

def macro_call(macro_name, args, kwargs):
""" allow the programmer to perform limited processing on the server by passing macro names and args
Expand All @@ -11,7 +11,7 @@ def macro_call(macro_name, args, kwargs):
:kwargs - the connection keyword dictionary. ??key has been removed
--> the value to put in for kwargs['name'] = value
"""
if isinstance(args, (str, unicode)):
if isinstance(args, (str, str)):
args = [args] # the user forgot to pass a sequence, so make a string into args[0]
new_key = args[0]
try:
Expand Down Expand Up @@ -79,7 +79,7 @@ def process(args, kwargs, expand_macros=False): # --> connection string with key
if isinstance(a1, int):
kwargs['timeout'] = a1
# if the second positional argument is a string, then it is user
elif isinstance(a1, basestring):
elif isinstance(a1, str):
kwargs['user'] = a1
# if the second positional argument is a dictionary, use it as keyword arguments, too
elif isinstance(a1, dict):
Expand All @@ -101,7 +101,7 @@ def process(args, kwargs, expand_macros=False): # --> connection string with key
except KeyError:
raise TypeError ("Must define 'connection_string' for ado connections")
if expand_macros:
for kwarg in kwargs.keys():
for kwarg in list(kwargs.keys()):
if kwarg.startswith('macro_'): # If a key defines a macro
macro_name = kwarg[6:] # name without the "macro_"
macro_code = kwargs.pop(kwarg) # we remove the macro_key and get the code to execute
Expand Down
22 changes: 11 additions & 11 deletions adodbapi/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
or IronPython version 2.7 and later,
or, after running through 2to3.py, CPython 3.0 or later.
"""
from __future__ import absolute_import


__version__ = '2.6.0.4'
version = 'adodbapi.remote v' + __version__
Expand Down Expand Up @@ -64,8 +64,8 @@
print(version)

# --- define objects to smooth out Python3 <-> Python 2.x differences
unicodeType = unicode #this line will be altered by 2to3.py to '= str'
longType = long #this line will be altered by 2to3.py to '= int'
unicodeType = str #this line will be altered by 2to3.py to '= str'
longType = int #this line will be altered by 2to3.py to '= int'
if sys.version[0] >= '3': #python 3.x
StringTypes = str
makeByteBuffer = bytes
Expand All @@ -78,7 +78,7 @@ def makeByteBuffer(x): # special for remote to be pickle-able
bytes
except NameError:
bytes = str
StringTypes = (str,unicode) # will be messed up by 2to3 but never used
StringTypes = (str,str) # will be messed up by 2to3 but never used
# -----------------------------------------------------------
# conversion functions mandated by PEP 249
Binary = makeByteBuffer # override the function from apibase.py
Expand Down Expand Up @@ -155,7 +155,7 @@ def connect(*args, **kwargs): # --> a remote db-api connection object
time.sleep(1)
else:
raise api.DatabaseError ('Pyro error creating connection to/thru=%s' % repr(kwargs))
except _BaseException, e:
except _BaseException as e:
raise api.DatabaseError('Error creating remote connection to=%s, e=%s, %s' % (repr(kwargs), repr(e),sys.exc_info()[2]))
return myConn

Expand Down Expand Up @@ -231,7 +231,7 @@ def close(self):
an Error (or subclass) exception will be raised if any operation is attempted with the connection.
The same applies to all cursor objects trying to use the connection.
"""
for crsr in self.cursors.values()[:]: # copy the list, then close each one
for crsr in list(self.cursors.values())[:]: # copy the list, then close each one
crsr.close()
try:
"""close the underlying remote Connection object"""
Expand Down Expand Up @@ -328,7 +328,7 @@ def fixpickle(x):
if isinstance(x, dict):
# for 'named' paramstyle user will pass a mapping
newargs = {}
for arg,val in x.items():
for arg,val in list(x.items()):
if isinstance(val, memoryViewType):
newval = array.array('B')
newval.fromstring(val)
Expand Down Expand Up @@ -370,7 +370,7 @@ def prepare(self, operation):
def __iter__(self): # [2.1 Zamarev]
return iter(self.fetchone, None) # [2.1 Zamarev]

def next(self):
def __next__(self):
r = self.fetchone()
if r:
return r
Expand Down Expand Up @@ -481,7 +481,7 @@ def callproc(self, procname, parameters=None):
def fetchone(self):
try:
f1 = self.proxy.crsr_fetchone(self.id)
except _BaseException, e:
except _BaseException as e:
self._raiseCursorError(api.DatabaseError, e)
else:
if f1 is None:
Expand All @@ -496,7 +496,7 @@ def fetchmany(self, size=None):
return []
r = api.SQLrows(self.rs, len(self.rs), self)
return r
except Exception, e:
except Exception as e:
self._raiseCursorError(api.DatabaseError, e)

def fetchall(self):
Expand All @@ -505,7 +505,7 @@ def fetchall(self):
if not self.rs:
return []
return api.SQLrows(self.rs, len(self.rs), self)
except Exception, e:
except Exception as e:
self._raiseCursorError(api.DatabaseError, e)

def close(self):
Expand Down
Loading

0 comments on commit 7a65a7a

Please sign in to comment.