Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adodbapi: reduce _raiseConnectionError and _raiseCursorError to a single argument #2351

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ https://mhammond.github.io/pywin32_installers.html.
Coming in build 309, as yet unreleased
--------------------------------------

## pywin32
* Dropped support for Python 3.7 (#2207, @Avasam)
* Implement the creation of SAFEARRAY(VT_RECORD) from a sequence of COM Records (#2317, @geppi)
* Implement record pointers as [in, out] method parameters of a Dispatch Interface (#2304, #2310, @geppi)
Expand All @@ -28,6 +29,9 @@ Coming in build 309, as yet unreleased
* Fixed "Open GL Demo" (`Pythonwin/pywin/Demos/openGLDemo.py`) and restore "Font" demo in `Pythonwin/pywin/Demos/guidemo.py` (#2345, @Avasam)
* Fixed accidentally trying to raise an undefined name instead of an `Exception` in `Pythonwin/pywin/debugger/debugger.py` (#2326, @Avasam)

## adodbapi
* When `errorhandler` is called, the `errorvalue` argument is now always an `Exception` and the `errortype` is the `type` of that specific `errorvalue` (#2351, @Avasam)

Build 308, released 2024-10-12
------------------------------
* Fix Pythonwin displaying syntax errors in Python 3.13 (#2393)
Expand Down
66 changes: 31 additions & 35 deletions adodbapi/adodbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import copy
import decimal
import os
import sys
import weakref

from . import ado_consts as adc, apibase as api, process_connect_string
Expand Down Expand Up @@ -248,9 +247,9 @@ def connect(self, kwargs, connection_maker=make_COM_connecter):
self.connection_string = (
kwargs["connection_string"] % kwargs
) # insert keyword arguments
except Exception as e:
except Exception:
self._raiseConnectionError(
KeyError, "Python string format error in connection string->"
KeyError("Python string format error in connection string->")
)
self.timeout = kwargs.get("timeout", 30)
self.mode = kwargs.get("mode", adc.adModeUnknown)
Expand All @@ -266,8 +265,7 @@ def connect(self, kwargs, connection_maker=make_COM_connecter):
self.connector.Open() # Open the ADO connection
except api.Error:
self._raiseConnectionError(
api.DatabaseError,
"ADO error trying to Open=%s" % self.connection_string,
api.DatabaseError(f"ADO error trying to Open={self.connection_string}")
)

try: # Stefan Fuchs; support WINCCOLEDBProvider
Expand Down Expand Up @@ -298,11 +296,9 @@ def connect(self, kwargs, connection_maker=make_COM_connecter):
if verbose:
print("adodbapi New connection at %X" % id(self))

def _raiseConnectionError(self, errorclass, errorvalue):
eh = self.errorhandler
if eh is None:
eh = api.standardErrorHandler
eh(self, None, errorclass, errorvalue)
def _raiseConnectionError(self, errorvalue: BaseException):
eh = self.errorhandler or api.standardErrorHandler
eh(self, None, type(errorvalue), errorvalue)

def _closeAdoConnection(self): # all v2.1 Rose
"""close the underlying ADO Connection object,
Expand Down Expand Up @@ -334,7 +330,7 @@ def close(self):
try:
self._closeAdoConnection() # v2.1 Rose
except Exception as e:
self._raiseConnectionError(sys.exc_info()[0], sys.exc_info()[1])
self._raiseConnectionError(e)

self.connector = None # v2.4.2.2 fix subtle timeout bug
# per M.Hammond: "I expect the benefits of uninitializing are probably fairly small,
Expand Down Expand Up @@ -364,7 +360,7 @@ def commit(self):
# If not, we will have to start a new transaction by this command:
self.transaction_level = self.connector.BeginTrans()
except Exception as e:
self._raiseConnectionError(api.ProgrammingError, e)
self._raiseConnectionError(api.ProgrammingError(e))

def _rollback(self):
"""In case a database does provide transactions this method causes the the database to roll back to
Expand Down Expand Up @@ -400,7 +396,7 @@ def _rollback(self):
): # if self.transaction_level == 0 or self.transaction_level is None:
self.transaction_level = self.connector.BeginTrans()
except Exception as e:
self._raiseConnectionError(api.ProgrammingError, e)
self._raiseConnectionError(api.ProgrammingError(e))

def __setattr__(self, name, value):
if name == "autocommit": # extension: allow user to turn autocommit on or off
Expand All @@ -414,8 +410,9 @@ def __setattr__(self, name, value):
elif name == "paramstyle":
if value not in api.accepted_paramstyles:
self._raiseConnectionError(
api.NotSupportedError,
f"paramstyle={value!r} not in:{api.accepted_paramstyles!r}",
api.NotSupportedError(
f"paramstyle={value!r} not in:{api.accepted_paramstyles!r}"
)
)
elif name == "variantConversions":
# make a new copy -- no changes in the default, please
Expand Down Expand Up @@ -584,15 +581,13 @@ def __enter__(self):
"Allow database cursors to be used with context managers."
return self

def __exit__(self, exc_type, exc_val, exc_tb):
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
"Allow database cursors to be used with context managers."
self.close()

def _raiseCursorError(self, errorclass, errorvalue):
eh = self.errorhandler
if eh is None:
eh = api.standardErrorHandler
eh(self.connection, self, errorclass, errorvalue)
def _raiseCursorError(self, errorvalue: BaseException) -> None:
eh = self.errorhandler or api.standardErrorHandler
eh(self.connection, self, type(errorvalue), errorvalue)

def build_column_info(self, recordset):
self.converters = [] # convertion function for each column
Expand All @@ -619,7 +614,7 @@ def build_column_info(self, recordset):
) # conversion function for this column
except KeyError:
self._raiseCursorError(
api.InternalError, "Data column of Unknown ADO type=%s" % f.Type
api.InternalError(f"Data column of Unknown ADO type={f.Type}")
)
self.columnNames[f.Name.lower()] = i # columnNames lookup

Expand Down Expand Up @@ -717,7 +712,7 @@ def _new_command(self, command_type=adc.adCmdText):
self.messages = []

if self.connection is None:
self._raiseCursorError(api.InterfaceError, None)
self._raiseCursorError(api.InterfaceError())
return
try:
self.cmd = Dispatch("ADODB.Command")
Expand All @@ -728,8 +723,9 @@ def _new_command(self, command_type=adc.adCmdText):
self.cmd.Prepared = bool(self._ado_prepared)
except:
self._raiseCursorError(
api.DatabaseError,
f"Error creating new ADODB.Command object for {self.commandText!r}",
api.DatabaseError(
f"Error creating new ADODB.Command object for {self.commandText!r}"
),
)

def _execute_command(self):
Expand All @@ -752,7 +748,7 @@ def _execute_command(self):
format_parameters(self.cmd.Parameters, True),
)
klass = self.connection._suggest_error_class()
self._raiseCursorError(klass, _message)
self._raiseCursorError(klass(_message))
try:
self.rowcount = recordset.RecordCount
except:
Expand Down Expand Up @@ -858,7 +854,6 @@ def _buildADOparameterList(self, parameters, sproc=False):
except api.Error:
if verbose:
print("ADO Parameter Refresh failed")
pass
else:
if len(parameters) != self.cmd.Parameters.Count - 1:
raise api.ProgrammingError(
Expand All @@ -883,7 +878,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
parameters[pm_name],
)
self._raiseCursorError(
api.DataError, f"{_message}->{e.args!r}"
api.DataError(f"{_message}->{e.args!r}")
)
else: # regular sequence of parameters
for value in parameters:
Expand All @@ -903,7 +898,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
value,
)
self._raiseCursorError(
api.DataError, f"{_message}->{e.args!r}"
api.DataError(f"{_message}->{e.args!r}")
)
i += 1
else: # -- build own parameter list
Expand All @@ -929,7 +924,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
)
)
self._raiseCursorError(
api.DataError, f"{_message}->{e.args!r}"
api.DataError(f"{_message}->{e.args!r}")
)
else: # expecting the usual sequence of parameters
if sproc:
Expand Down Expand Up @@ -957,7 +952,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
)
)
self._raiseCursorError(
api.DataError, f"{_message}->{e.args!r}"
api.DataError(f"{_message}->{e.args!r}")
)
i += 1
if self._ado_prepared == "setup":
Expand Down Expand Up @@ -1038,7 +1033,7 @@ def _fetch(self, limit=None):
"""
if self.connection is None or self.rs is None:
self._raiseCursorError(
api.FetchFailedError, "fetch() on closed connection or empty query set"
api.FetchFailedError("fetch() on closed connection or empty query set")
)
return

Expand Down Expand Up @@ -1119,15 +1114,16 @@ def nextset(self):
self.messages = []
if self.connection is None or self.rs is None:
self._raiseCursorError(
api.OperationalError,
("nextset() on closed connection or empty query set"),
api.OperationalError(
"nextset() on closed connection or empty query set"
),
)
return None

try: # [begin 2.1 ekelund]
rsTuple = self.rs.NextRecordset() #
except pywintypes.com_error as exc: # return appropriate error
self._raiseCursorError(api.NotSupportedError, exc.args) # [end 2.1 ekelund]
self._raiseCursorError(api.NotSupportedError(exc.args)) # [end 2.1 ekelund]
recordset = rsTuple[0]
if recordset is None:
return None
Expand Down
Loading