From 364c2b4bcf9c6cfb20490e61521c70b5107101dd Mon Sep 17 00:00:00 2001 From: Avasam Date: Sat, 1 Jun 2024 15:39:21 -0400 Subject: [PATCH 1/4] adodbapi: prefer f-string > format > printf-style autofixes --- adodbapi/adodbapi.py | 104 ++++------ adodbapi/apibase.py | 4 +- adodbapi/examples/db_print.py | 4 +- adodbapi/examples/db_table_names.py | 2 +- adodbapi/examples/xls_read.py | 6 +- adodbapi/examples/xls_write.py | 4 +- adodbapi/process_connect_string.py | 2 +- adodbapi/setup.py | 2 +- adodbapi/test/adodbapitest.py | 256 ++++++++++--------------- adodbapi/test/adodbapitestconfig.py | 7 +- adodbapi/test/dbapi20.py | 84 ++++---- adodbapi/test/test_adodbapi_dbapi20.py | 24 +-- ruff.toml | 2 +- 13 files changed, 201 insertions(+), 300 deletions(-) diff --git a/adodbapi/adodbapi.py b/adodbapi/adodbapi.py index 3f6b0c48e7..0aaa2c3f2c 100644 --- a/adodbapi/adodbapi.py +++ b/adodbapi/adodbapi.py @@ -91,7 +91,7 @@ def connect(*args, **kwargs): # --> a db-api connection object co.connect(kwargs) return co except Exception as e: - message = 'Error opening connection to "%s"' % co.connection_string + message = f'Error opening connection to "{co.connection_string}"' raise api.OperationalError(e, message) @@ -124,8 +124,7 @@ def format_parameters(ADOparameters, show_value=False): try: if show_value: desc = [ - 'Name: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s", Precision: %s, NumericScale: %s' - % ( + 'Name: {}, Dir.: {}, Type: {}, Size: {}, Value: "{}", Precision: {}, NumericScale: {}'.format( p.Name, adc.directions[p.Direction], adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"), @@ -138,8 +137,7 @@ def format_parameters(ADOparameters, show_value=False): ] else: desc = [ - "Name: %s, Dir.: %s, Type: %s, Size: %s, Precision: %s, NumericScale: %s" - % ( + "Name: {}, Dir.: {}, Type: {}, Size: {}, Precision: {}, NumericScale: {}".format( p.Name, adc.directions[p.Direction], adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"), @@ -256,7 +254,7 @@ def connect(self, kwargs, connection_maker=make_COM_connecter): self.mode = kwargs.get("mode", adc.adModeUnknown) self.kwargs = kwargs if verbose: - print('%s attempting: "%s"' % (version, self.connection_string)) + print(f'{version} attempting: "{self.connection_string}"') self.connector = connection_maker() self.connector.ConnectionTimeout = self.timeout self.connector.ConnectionString = self.connection_string @@ -267,7 +265,7 @@ def connect(self, kwargs, connection_maker=make_COM_connecter): except api.Error: self._raiseConnectionError( api.DatabaseError, - "ADO error trying to Open=%s" % self.connection_string, + f"ADO error trying to Open={self.connection_string}", ) try: # Stefan Fuchs; support WINCCOLEDBProvider @@ -296,7 +294,7 @@ def connect(self, kwargs, connection_maker=make_COM_connecter): self.paramstyle = kwargs["paramstyle"] # let setattr do the error checking self.messages = [] if verbose: - print("adodbapi New connection at %X" % id(self)) + print(f"adodbapi New connection at {id(self):X}") def _raiseConnectionError(self, errorclass, errorvalue): eh = self.errorhandler @@ -317,7 +315,7 @@ def _closeAdoConnection(self): # all v2.1 Rose pass self.connector.Close() if verbose: - print("adodbapi Closed connection at %X" % id(self)) + print(f"adodbapi Closed connection at {id(self):X}") def close(self): """Close the connection now (rather than whenever __del__ is called). @@ -354,7 +352,7 @@ def commit(self): try: self.transaction_level = self.connector.CommitTrans() if verbose > 1: - print("commit done on connection at %X" % id(self)) + print(f"commit done on connection at {id(self):X}") if not ( self._autocommit or (self.connector.Attributes & adc.adXactAbortRetaining) @@ -388,7 +386,7 @@ def _rollback(self): try: self.transaction_level = self.connector.RollbackTrans() if verbose > 1: - print("rollback done on connection at %X" % id(self)) + print(f"rollback done on connection at {id(self):X}") if not self._autocommit and not ( self.connector.Attributes & adc.adXactAbortRetaining ): @@ -437,7 +435,7 @@ def __getattr__(self, item): return self._autocommit else: raise AttributeError( - 'no such attribute in ADO connection object as="%s"' % item + f'no such attribute in ADO connection object as="{item}"' ) def cursor(self): @@ -463,15 +461,17 @@ def printADOerrors(self): if j: print("ADO Errors:(%i)" % j) for e in self.connector.Errors: - print("Description: %s" % e.Description) - print("Error: %s %s " % (e.Number, adc.adoErrors.get(e.Number, "unknown"))) + print(f"Description: {e.Description}") + print( + "Error: {} {} ".format(e.Number, adc.adoErrors.get(e.Number, "unknown")) + ) if e.Number == adc.ado_error_TIMEOUT: print( "Timeout Error: Try using adodbpi.connect(constr,timeout=Nseconds)" ) - print("Source: %s" % e.Source) - print("NativeError: %s" % e.NativeError) - print("SQL State: %s" % e.SQLState) + print(f"Source: {e.Source}") + print(f"NativeError: {e.NativeError}") + print(f"SQL State: {e.SQLState}") def _suggest_error_class(self): """Introspect the current ADO Errors and determine an appropriate error class. @@ -563,8 +563,7 @@ def __init__(self, connection): connection._i_am_here(self) if verbose: print( - "%s New cursor at %X on conn %X" - % (version, id(self), id(self.connection)) + f"{version} New cursor at {id(self):X} on conn {id(self.connection):X}" ) def __iter__(self): # [2.1 Zamarev] @@ -620,7 +619,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 @@ -670,17 +669,14 @@ def format_description(self, d): self._makeDescriptionFromRS() 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], - ) + desc = "Name= {}, Type= {}, DispSize= {}, IntSize= {}, Precision= {}, Scale= {} NullOK={}".format( + d[0], + adc.adTypeNames.get(d[1], str(d[1]) + " (unknown type)"), + d[2], + d[3], + d[4], + d[5], + d[6], ) return desc @@ -705,7 +701,7 @@ def close(self, dont_tell_me=False): None # this will make all future method calls on me throw an exception ) if verbose: - print("adodbapi Closed cursor at %X" % id(self)) + print(f"adodbapi Closed cursor at {id(self):X}") def __del__(self): try: @@ -739,7 +735,7 @@ def _execute_command(self): recordset = None count = -1 # default value if verbose: - print('Executing command="%s"' % self.commandText) + print(f'Executing command="{self.commandText}"') try: # ----- the actual SQL is executed here --- recordset, count = self.cmd.Execute() @@ -748,10 +744,7 @@ def _execute_command(self): _message = "" if hasattr(e, "args"): _message += str(e.args) + "\n" - _message += "Command:\n%s\nParameters:\n%s" % ( - self.commandText, - format_parameters(self.cmd.Parameters, True), - ) + _message += f"Command:\n{self.commandText}\nParameters:\n{format_parameters(self.cmd.Parameters, True)}" klass = self.connection._suggest_error_class() self._raiseCursorError(klass, _message) try: @@ -781,9 +774,8 @@ def get_returned_parameters(self): for p in tuple(self.cmd.Parameters): if verbose > 2: print( - 'Returned=Name: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s",' - " Precision: %s, NumericScale: %s" - % ( + 'Returned=Name: {}, Dir.: {}, Type: {}, Size: {}, Value: "{}",' + " Precision: {}, NumericScale: {}".format( p.Name, adc.directions[p.Direction], adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"), @@ -877,12 +869,7 @@ def _buildADOparameterList(self, parameters, sproc=False): p, parameters[pm_name], p.Type, parameters_known ) except Exception as e: - _message = "Error Converting Parameter {}: {}, {} <- {!r}\n".format( - p.Name, - adc.ado_type_name(p.Type), - p.Value, - parameters[pm_name], - ) + _message = f"Error Converting Parameter {p.Name}: {adc.ado_type_name(p.Type)}, {p.Value} <- {parameters[pm_name]!r}\n" self._raiseCursorError( api.DataError, f"{_message}->{e.args!r}" ) @@ -897,12 +884,7 @@ def _buildADOparameterList(self, parameters, sproc=False): try: _configure_parameter(p, value, p.Type, parameters_known) except Exception as e: - _message = "Error Converting Parameter {}: {}, {} <- {!r}\n".format( - p.Name, - adc.ado_type_name(p.Type), - p.Value, - value, - ) + _message = f"Error Converting Parameter {p.Name}: {adc.ado_type_name(p.Type)}, {p.Value} <- {value!r}\n" self._raiseCursorError( api.DataError, f"{_message}->{e.args!r}" ) @@ -921,14 +903,7 @@ def _buildADOparameterList(self, parameters, sproc=False): try: self.cmd.Parameters.Append(p) except Exception as e: - _message = ( - "Error Building Parameter {}: {}, {} <- {!r}\n".format( - p.Name, - adc.ado_type_name(p.Type), - p.Value, - elem, - ) - ) + _message = f"Error Building Parameter {p.Name}: {adc.ado_type_name(p.Type)}, {p.Value} <- {elem!r}\n" self._raiseCursorError( api.DataError, f"{_message}->{e.args!r}" ) @@ -949,14 +924,7 @@ def _buildADOparameterList(self, parameters, sproc=False): try: self.cmd.Parameters.Append(p) except Exception as e: - _message = ( - "Error Building Parameter {}: {}, {} <- {!r}\n".format( - p.Name, - adc.ado_type_name(p.Type), - p.Value, - elem, - ) - ) + _message = f"Error Building Parameter {p.Name}: {adc.ado_type_name(p.Type)}, {p.Value} <- {elem!r}\n" self._raiseCursorError( api.DataError, f"{_message}->{e.args!r}" ) diff --git a/adodbapi/apibase.py b/adodbapi/apibase.py index 3231f78ac3..dbc54f72da 100644 --- a/adodbapi/apibase.py +++ b/adodbapi/apibase.py @@ -511,7 +511,7 @@ def __getattr__(self, name): # used for row.columnName type of value access try: return self._getValue(self.rows.columnNames[name.lower()]) except KeyError: - raise AttributeError('Unknown column name "{}"'.format(name)) + raise AttributeError(f'Unknown column name "{name}"') def _getValue(self, key): # key must be an integer if ( @@ -702,7 +702,7 @@ def changeFormatToQmark( s, chunk = sp[1].split(")s", 1) # find the ')s' except ValueError: raise ProgrammingError( - 'Pyformat SQL has incorrect format near "%s"' % chunk + f'Pyformat SQL has incorrect format near "{chunk}"' ) outparams.append(s) outOp += "?" # put in the Qmark diff --git a/adodbapi/examples/db_print.py b/adodbapi/examples/db_print.py index c0eb83ee4d..54ccadb0a6 100644 --- a/adodbapi/examples/db_print.py +++ b/adodbapi/examples/db_print.py @@ -39,8 +39,8 @@ # make a cursor on the connection with con.cursor() as c: # run an SQL statement on the cursor - sql = "select * from %s" % kw_args["table_name"] - print('performing query="%s"' % sql) + sql = "select * from {}".format(kw_args["table_name"]) + print(f'performing query="{sql}"') c.execute(sql) # check the results diff --git a/adodbapi/examples/db_table_names.py b/adodbapi/examples/db_table_names.py index 907bdb85ea..b21985054d 100644 --- a/adodbapi/examples/db_table_names.py +++ b/adodbapi/examples/db_table_names.py @@ -15,7 +15,7 @@ # create the connection con = adodbapi.connect(constr, db=databasename, macro_is64bit=provider) -print("Table names in= %s" % databasename) +print(f"Table names in= {databasename}") for table in con.get_table_names(): print(table) diff --git a/adodbapi/examples/xls_read.py b/adodbapi/examples/xls_read.py index 10bcc57e6b..223a9350cd 100644 --- a/adodbapi/examples/xls_read.py +++ b/adodbapi/examples/xls_read.py @@ -20,7 +20,7 @@ except IndexError: filename = "xx.xls" -constr = "Provider=%s;Data Source=%s;%s" % (driver, filename, extended) +constr = f"Provider={driver};Data Source={filename};{extended}" conn = adodbapi.connect(constr) @@ -30,10 +30,10 @@ # use ADO feature to get the name of the first worksheet sheet = conn.get_table_names()[0] -print("Shreadsheet=%s Worksheet=%s" % (filename, sheet)) +print(f"Shreadsheet={filename} Worksheet={sheet}") print("------------------------------------------------------------") crsr = conn.cursor() -sql = "SELECT * from [%s]" % sheet +sql = f"SELECT * from [{sheet}]" crsr.execute(sql) for row in crsr.fetchmany(10): print(repr(row)) diff --git a/adodbapi/examples/xls_write.py b/adodbapi/examples/xls_write.py index 38baefd812..3c37038e43 100644 --- a/adodbapi/examples/xls_write.py +++ b/adodbapi/examples/xls_write.py @@ -15,7 +15,7 @@ filename = "xx.xls" # file will be created if it does not exist extended = 'Extended Properties="Excel 8.0;Readonly=False;"' -constr = "Provider=%s;Data Source=%s;%s" % (driver, filename, extended) +constr = f"Provider={driver};Data Source={filename};{extended}" conn = adodbapi.connect(constr) with conn: # will auto commit if no errors @@ -38,4 +38,4 @@ sql, ["John Jones", "Pvt", 987654321, 140.0, datetime.date(1921, 7, 4)] ) # another row of data conn.close() -print("Created spreadsheet=%s worksheet=%s" % (filename, "SheetOne")) +print("Created spreadsheet={} worksheet={}".format(filename, "SheetOne")) diff --git a/adodbapi/process_connect_string.py b/adodbapi/process_connect_string.py index d8b29f280c..9f028485bb 100644 --- a/adodbapi/process_connect_string.py +++ b/adodbapi/process_connect_string.py @@ -56,7 +56,7 @@ def macro_call(macro_name, args, kwargs): not "user" in kwargs or not kwargs["user"] ): # missing, blank, or Null username return new_key, "Integrated Security=SSPI" - return new_key, "User ID=%(user)s; Password=%(password)s" % kwargs + return new_key, "User ID={user}; Password={password}".format(**kwargs) elif ( macro_name == "find_temp_test_path" diff --git a/adodbapi/setup.py b/adodbapi/setup.py index f6b274661d..bf50bcc436 100644 --- a/adodbapi/setup.py +++ b/adodbapi/setup.py @@ -35,7 +35,7 @@ for line in a: if "__version__" in line: VERSION = line.split("'")[1] - print('adodbapi version="%s"' % VERSION) + print(f'adodbapi version="{VERSION}"') break a.close() diff --git a/adodbapi/test/adodbapitest.py b/adodbapi/test/adodbapitest.py index b8d98593db..6df76e65ba 100644 --- a/adodbapi/test/adodbapitest.py +++ b/adodbapi/test/adodbapitest.py @@ -152,20 +152,17 @@ def testUserDefinedConversions(self): # create a variantConversions attribute on the connection conn.variantConversions = copy.copy(api.variantConversions) crsr = conn.cursor() - tabdef = ( - "CREATE TABLE xx_%s (fldData VARCHAR(100) NOT NULL, fld2 VARCHAR(20))" - % config.tmp - ) + tabdef = f"CREATE TABLE xx_{config.tmp} (fldData VARCHAR(100) NOT NULL, fld2 VARCHAR(20))" crsr.execute(tabdef) crsr.execute( - "INSERT INTO xx_%s(fldData,fld2) VALUES('gabba','booga')" % config.tmp + f"INSERT INTO xx_{config.tmp}(fldData,fld2) VALUES('gabba','booga')" ) crsr.execute( - "INSERT INTO xx_%s(fldData,fld2) VALUES('hey','yo')" % config.tmp + f"INSERT INTO xx_{config.tmp}(fldData,fld2) VALUES('hey','yo')" ) # change converter for ALL adoStringTypes columns conn.variantConversions[api.adoStringTypes] = duplicatingConverter - crsr.execute("SELECT fldData,fld2 FROM xx_%s ORDER BY fldData" % config.tmp) + crsr.execute(f"SELECT fldData,fld2 FROM xx_{config.tmp} ORDER BY fldData") rows = crsr.fetchall() row = rows[0] @@ -216,7 +213,7 @@ def testUserDefinedConversionForExactNumericTypes(self): self.helpTestDataType("numeric(18,2)", "NUMBER", "3.45") # now a completly weird user defined convertion adodbapi.variantConversions[ado_consts.adNumeric] = ( - lambda x: "!!This function returns a funny unicode string %s!!" % x + lambda x: f"!!This function returns a funny unicode string {x}!!" ) self.helpTestDataType( "numeric(18,2)", @@ -245,11 +242,10 @@ def helpTestDataType( conn = self.getConnection() crsr = conn.cursor() tabdef = ( - """ - CREATE TABLE xx_%s ( + f""" + CREATE TABLE xx_{config.tmp} ( fldId integer NOT NULL, fldData """ - % config.tmp + sqlDataTypeString + ")\n" ) @@ -257,50 +253,44 @@ def helpTestDataType( crsr.execute(tabdef) # Test Null values mapped to None - crsr.execute("INSERT INTO xx_%s (fldId) VALUES (1)" % config.tmp) + crsr.execute(f"INSERT INTO xx_{config.tmp} (fldId) VALUES (1)") - crsr.execute("SELECT fldId,fldData FROM xx_%s" % config.tmp) + crsr.execute(f"SELECT fldId,fldData FROM xx_{config.tmp}") rs = crsr.fetchone() self.assertEqual(rs[1], None) # Null should be mapped to None assert rs[0] == 1 # Test description related descTuple = crsr.description[1] - assert descTuple[0] in ["fldData", "flddata"], 'was "%s" expected "%s"' % ( + assert descTuple[0] in ["fldData", "flddata"], 'was "{}" expected "{}"'.format( descTuple[0], "fldData", ) if DBAPIDataTypeString == "STRING": - assert descTuple[1] == api.STRING, 'was "%s" expected "%s"' % ( - descTuple[1], - api.STRING.values, - ) + assert ( + descTuple[1] == api.STRING + ), f'was "{descTuple[1]}" expected "{api.STRING.values}"' elif DBAPIDataTypeString == "NUMBER": - assert descTuple[1] == api.NUMBER, 'was "%s" expected "%s"' % ( - descTuple[1], - api.NUMBER.values, - ) + assert ( + descTuple[1] == api.NUMBER + ), f'was "{descTuple[1]}" expected "{api.NUMBER.values}"' elif DBAPIDataTypeString == "BINARY": - assert descTuple[1] == api.BINARY, 'was "%s" expected "%s"' % ( - descTuple[1], - api.BINARY.values, - ) + assert ( + descTuple[1] == api.BINARY + ), f'was "{descTuple[1]}" expected "{api.BINARY.values}"' elif DBAPIDataTypeString == "DATETIME": - assert descTuple[1] == api.DATETIME, 'was "%s" expected "%s"' % ( - descTuple[1], - api.DATETIME.values, - ) + assert ( + descTuple[1] == api.DATETIME + ), f'was "{descTuple[1]}" expected "{api.DATETIME.values}"' elif DBAPIDataTypeString == "ROWID": - assert descTuple[1] == api.ROWID, 'was "%s" expected "%s"' % ( - descTuple[1], - api.ROWID.values, - ) + assert ( + descTuple[1] == api.ROWID + ), f'was "{descTuple[1]}" expected "{api.ROWID.values}"' elif DBAPIDataTypeString == "UUID": - assert descTuple[1] == api.OTHER, 'was "%s" expected "%s"' % ( - descTuple[1], - api.OTHER.values, - ) + assert ( + descTuple[1] == api.OTHER + ), f'was "{descTuple[1]}" expected "{api.OTHER.values}"' else: raise NotImplementedError # "DBAPIDataTypeString not provided" @@ -314,28 +304,23 @@ def helpTestDataType( fldId += 1 try: crsr.execute( - "INSERT INTO xx_%s (fldId,fldData) VALUES (?,?)" % config.tmp, + f"INSERT INTO xx_{config.tmp} (fldId,fldData) VALUES (?,?)", (fldId, inParam), ) except: conn.printADOerrors() raise - crsr.execute( - "SELECT fldData FROM xx_%s WHERE ?=fldID" % config.tmp, [fldId] - ) + crsr.execute(f"SELECT fldData FROM xx_{config.tmp} 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) + ), f'result type "{type(rs[0])}" must be one of {allowedTypes}' else: assert isinstance( rs[0], type(pyData) - ), 'result type "%s" must be instance of %s' % ( - type(rs[0]), - type(pyData), - ) + ), f'result type "{type(rs[0])}" must be instance of {type(pyData)}' if compareAlmostEqual and DBAPIDataTypeString == "DATETIME": iso1 = adodbapi.dateconverter.DateObjectToIsoFormatString(rs[0]) @@ -346,7 +331,7 @@ def helpTestDataType( v = float(rs[0]) assert ( abs(v - s) / s < 0.00001 - ), "Values not almost equal recvd=%s, expected=%f" % (rs[0], s) + ), f"Values not almost equal recvd={rs[0]}, expected={s:f}" else: if allowedReturnValues: ok = False @@ -358,8 +343,7 @@ def helpTestDataType( self.assertEqual( rs[0], pyData, - 'Values are not equal recvd="%s", expected="%s"' - % (rs[0], pyData), + f'Values are not equal recvd="{rs[0]}", expected="{pyData}"', ) def testDataTypeFloat(self): @@ -516,21 +500,18 @@ def helpForceDropOnTblTemp(self): conn = self.getConnection() with conn.cursor() as crsr: try: - crsr.execute("DROP TABLE xx_%s" % config.tmp) + crsr.execute(f"DROP TABLE xx_{config.tmp}") if not conn.autocommit: conn.commit() except: pass def helpCreateAndPopulateTableTemp(self, crsr): - tabdef = ( - """ - CREATE TABLE xx_%s ( + tabdef = f""" + CREATE TABLE xx_{config.tmp} ( fldData INTEGER ) """ - % config.tmp - ) try: # EAFP crsr.execute(tabdef) except api.DatabaseError: # was not dropped before @@ -543,7 +524,7 @@ def helpCreateAndPopulateTableTemp(self, crsr): def testFetchAll(self): crsr = self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) - crsr.execute("SELECT fldData FROM xx_%s" % config.tmp) + crsr.execute(f"SELECT fldData FROM xx_{config.tmp}") rs = crsr.fetchall() assert len(rs) == 9 # test slice of rows @@ -556,7 +537,7 @@ def testFetchAll(self): def testPreparedStatement(self): crsr = self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) - crsr.prepare("SELECT fldData FROM xx_%s" % config.tmp) + crsr.prepare(f"SELECT fldData FROM xx_{config.tmp}") crsr.execute(crsr.command) # remember the one that was prepared rs = crsr.fetchall() assert len(rs) == 9 @@ -568,7 +549,7 @@ def testWrongPreparedStatement(self): self.helpCreateAndPopulateTableTemp(crsr) crsr.prepare("SELECT * FROM nowhere") crsr.execute( - "SELECT fldData FROM xx_%s" % config.tmp + f"SELECT fldData FROM xx_{config.tmp}" ) # should execute this one, not the prepared one rs = crsr.fetchall() assert len(rs) == 9 @@ -578,7 +559,7 @@ def testWrongPreparedStatement(self): def testIterator(self): crsr = self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) - crsr.execute("SELECT fldData FROM xx_%s" % config.tmp) + crsr.execute(f"SELECT fldData FROM xx_{config.tmp}") for i, row in enumerate( crsr ): # using cursor as an iterator, rather than fetchxxx @@ -590,7 +571,7 @@ def testExecuteMany(self): self.helpCreateAndPopulateTableTemp(crsr) seq_of_values = [(111,), (222,)] crsr.executemany( - "INSERT INTO xx_%s (fldData) VALUES (?)" % config.tmp, seq_of_values + f"INSERT INTO xx_{config.tmp} (fldData) VALUES (?)", seq_of_values ) if crsr.rowcount == -1: print( @@ -599,7 +580,7 @@ def testExecuteMany(self): ) else: self.assertEqual(crsr.rowcount, 2) - crsr.execute("SELECT fldData FROM xx_%s" % config.tmp) + crsr.execute(f"SELECT fldData FROM xx_{config.tmp}") rs = crsr.fetchall() assert len(rs) == 11 self.helpRollbackTblTemp() @@ -607,7 +588,7 @@ def testExecuteMany(self): def testRowCount(self): crsr = self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) - crsr.execute("SELECT fldData FROM xx_%s" % config.tmp) + crsr.execute(f"SELECT fldData FROM xx_{config.tmp}") if crsr.rowcount == -1: # print("provider does not support rowcount on select") pass @@ -618,7 +599,7 @@ def testRowCount(self): def testRowCountNoRecordset(self): crsr = self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) - crsr.execute("DELETE FROM xx_%s WHERE fldData >= 5" % config.tmp) + crsr.execute(f"DELETE FROM xx_{config.tmp} WHERE fldData >= 5") if crsr.rowcount == -1: print(self.getEngine() + " Provider does not support rowcount (on DELETE)") else: @@ -628,7 +609,7 @@ def testRowCountNoRecordset(self): def testFetchMany(self): crsr = self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) - crsr.execute("SELECT fldData FROM xx_%s" % config.tmp) + crsr.execute(f"SELECT fldData FROM xx_{config.tmp}") rs = crsr.fetchmany(3) assert len(rs) == 3 rs = crsr.fetchmany(5) @@ -640,7 +621,7 @@ def testFetchMany(self): def testFetchManyWithArraySize(self): crsr = self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) - crsr.execute("SELECT fldData FROM xx_%s" % config.tmp) + crsr.execute(f"SELECT fldData FROM xx_{config.tmp}") rs = crsr.fetchmany() assert len(rs) == 1 # arraysize Defaults to one crsr.arraysize = 4 @@ -661,16 +642,13 @@ def testRowIterator(self): self.helpForceDropOnTblTemp() conn = self.getConnection() crsr = conn.cursor() - tabdef = ( - """ - CREATE TABLE xx_%s ( + tabdef = f""" + CREATE TABLE xx_{config.tmp} ( fldId integer NOT NULL, fldTwo integer, fldThree integer, fldFour integer) """ - % config.tmp - ) crsr.execute(tabdef) inputs = [(2, 3, 4), (102, 103, 104)] @@ -679,15 +657,14 @@ def testRowIterator(self): fldId += 1 try: crsr.execute( - "INSERT INTO xx_%s (fldId,fldTwo,fldThree,fldFour) VALUES (?,?,?,?)" - % config.tmp, + f"INSERT INTO xx_{config.tmp} (fldId,fldTwo,fldThree,fldFour) VALUES (?,?,?,?)", (fldId, inParam[0], inParam[1], inParam[2]), ) except: conn.printADOerrors() raise crsr.execute( - "SELECT fldTwo,fldThree,fldFour FROM xx_%s WHERE ?=fldID" % config.tmp, + f"SELECT fldTwo,fldThree,fldFour FROM xx_{config.tmp} WHERE ?=fldID", [fldId], ) rec = crsr.fetchone() @@ -695,7 +672,7 @@ def testRowIterator(self): for j in range(len(inParam)): assert ( rec[j] == inParam[j] - ), 'returned value:"%s" != test value:"%s"' % (rec[j], inParam[j]) + ), f'returned value:"{rec[j]}" != test value:"{inParam[j]}"' # check that we can get a complete tuple from a row assert ( tuple(rec) == inParam @@ -712,7 +689,7 @@ def testRowIterator(self): 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 xx_%s" % config.tmp) + crsr.execute(f"select fldThree,fldFour,fldTwo from xx_{config.tmp}") recs = crsr.fetchall() assert recs[1][0] == 103 assert recs[0][1] == 4 @@ -729,15 +706,12 @@ def testFormatParamstyle(self): conn = self.getConnection() conn.paramstyle = "format" # test nonstandard use of paramstyle crsr = conn.cursor() - tabdef = ( - """ - CREATE TABLE xx_%s ( + tabdef = f""" + CREATE TABLE xx_{config.tmp} ( fldId integer NOT NULL, fldData varchar(10), fldConst varchar(30)) """ - % config.tmp - ) crsr.execute(tabdef) inputs = ["one", "two", "three"] @@ -762,7 +736,7 @@ def testFormatParamstyle(self): self.assertEqual( rec[0], inParam, - 'returned value:"%s" != test value:"%s"' % (rec[0], inParam), + f'returned value:"{rec[0]}" != test value:"{inParam}"', ) self.assertEqual(rec[1], "thi%s :may cause? trouble") @@ -774,14 +748,14 @@ def testFormatParamstyle(self): crsr.execute(sel, params) # test the .query implementation - assert "(?," in crsr.query, 'expected:"%s" in "%s"' % ("(?,", crsr.query) + assert "(?," in crsr.query, 'expected:"{}" in "{}"'.format("(?,", crsr.query) # test the .command attribute - assert crsr.command == sel, 'expected:"%s" but found "%s"' % (sel, crsr.command) + assert crsr.command == sel, f'expected:"{sel}" but found "{crsr.command}"' # test the .parameters attribute self.assertEqual(crsr.parameters, params) # now make sure the data made it - crsr.execute("SELECT fldData FROM xx_%s WHERE fldID=20" % config.tmp) + crsr.execute(f"SELECT fldData FROM xx_{config.tmp} WHERE fldID=20") rec = crsr.fetchone() self.assertEqual(rec[0], "four%sfive") @@ -790,14 +764,11 @@ def testNamedParamstyle(self): conn = self.getConnection() crsr = conn.cursor() crsr.paramstyle = "named" # test nonstandard use of paramstyle - tabdef = ( - """ - CREATE TABLE xx_%s ( + tabdef = f""" + CREATE TABLE xx_{config.tmp} ( fldId integer NOT NULL, fldData varchar(10)) """ - % config.tmp - ) crsr.execute(tabdef) inputs = ["four", "five", "six"] @@ -806,28 +777,27 @@ def testNamedParamstyle(self): fldId += 1 try: crsr.execute( - "INSERT INTO xx_%s (fldId,fldData) VALUES (:Id,:f_Val)" - % config.tmp, + f"INSERT INTO xx_{config.tmp} (fldId,fldData) VALUES (:Id,:f_Val)", {"f_Val": inParam, "Id": fldId}, ) except: conn.printADOerrors() raise crsr.execute( - "SELECT fldData FROM xx_%s WHERE fldID=:Id" % config.tmp, {"Id": fldId} + f"SELECT fldData FROM xx_{config.tmp} WHERE fldID=:Id", {"Id": fldId} ) rec = crsr.fetchone() self.assertEqual( rec[0], inParam, - 'returned value:"%s" != test value:"%s"' % (rec[0], inParam), + f'returned value:"{rec[0]}" != test value:"{inParam}"', ) # now a test with a ":" as part of a literal crsr.execute( - "insert into xx_%s (fldId,fldData) VALUES (:xyz,'six:five')" % config.tmp, + f"insert into xx_{config.tmp} (fldId,fldData) VALUES (:xyz,'six:five')", {"xyz": 30}, ) - crsr.execute("SELECT fldData FROM xx_%s WHERE fldID=30" % config.tmp) + crsr.execute(f"SELECT fldData FROM xx_{config.tmp} WHERE fldID=30") rec = crsr.fetchone() self.assertEqual(rec[0], "six:five") @@ -836,14 +806,11 @@ def testPyformatParamstyle(self): conn = self.getConnection() crsr = conn.cursor() crsr.paramstyle = "pyformat" # test nonstandard use of paramstyle - tabdef = ( - """ - CREATE TABLE xx_%s ( + tabdef = f""" + CREATE TABLE xx_{config.tmp} ( fldId integer NOT NULL, fldData varchar(10)) """ - % config.tmp - ) crsr.execute(tabdef) inputs = ["four", "five", "six"] @@ -852,30 +819,28 @@ def testPyformatParamstyle(self): fldId += 1 try: crsr.execute( - "INSERT INTO xx_%s (fldId,fldData) VALUES (%%(Id)s,%%(f_Val)s)" - % config.tmp, + f"INSERT INTO xx_{config.tmp} (fldId,fldData) VALUES (%(Id)s,%(f_Val)s)", {"f_Val": inParam, "Id": fldId}, ) except: conn.printADOerrors() raise crsr.execute( - "SELECT fldData FROM xx_%s WHERE fldID=%%(Id)s" % config.tmp, + f"SELECT fldData FROM xx_{config.tmp} WHERE fldID=%(Id)s", {"Id": fldId}, ) rec = crsr.fetchone() self.assertEqual( rec[0], inParam, - 'returned value:"%s" != test value:"%s"' % (rec[0], inParam), + f'returned value:"{rec[0]}" != test value:"{inParam}"', ) # now a test with a "%" as part of a literal crsr.execute( - "insert into xx_%s (fldId,fldData) VALUES (%%(xyz)s,'six%%five')" - % config.tmp, + f"insert into xx_{config.tmp} (fldId,fldData) VALUES (%(xyz)s,'six%five')", {"xyz": 30}, ) - crsr.execute("SELECT fldData FROM xx_%s WHERE fldID=30" % config.tmp) + crsr.execute(f"SELECT fldData FROM xx_{config.tmp} WHERE fldID=30") rec = crsr.fetchone() self.assertEqual(rec[0], "six%five") @@ -884,15 +849,12 @@ def testAutomaticParamstyle(self): conn = self.getConnection() conn.paramstyle = "dynamic" # test nonstandard use of paramstyle crsr = conn.cursor() - tabdef = ( - """ - CREATE TABLE xx_%s ( + tabdef = f""" + CREATE TABLE xx_{config.tmp} ( fldId integer NOT NULL, fldData varchar(10), fldConst varchar(30)) """ - % config.tmp - ) crsr.execute(tabdef) inputs = ["one", "two", "three"] fldId = 2 @@ -917,7 +879,7 @@ def testAutomaticParamstyle(self): self.assertEqual( rec[0], inParam, - 'returned value:"%s" != test value:"%s"' % (rec[0], inParam), + f'returned value:"{rec[0]}" != test value:"{inParam}"', ) self.assertEqual(rec[1], trouble) # inputs = [u'four',u'five',u'six'] @@ -926,29 +888,26 @@ def testAutomaticParamstyle(self): fldId += 1 try: crsr.execute( - "INSERT INTO xx_%s (fldId,fldData) VALUES (:Id,:f_Val)" - % config.tmp, + f"INSERT INTO xx_{config.tmp} (fldId,fldData) VALUES (:Id,:f_Val)", {"f_Val": inParam, "Id": fldId}, ) except: conn.printADOerrors() raise crsr.execute( - "SELECT fldData FROM xx_%s WHERE :Id=fldID" % config.tmp, {"Id": fldId} + f"SELECT fldData FROM xx_{config.tmp} WHERE :Id=fldID", {"Id": fldId} ) rec = crsr.fetchone() self.assertEqual( rec[0], inParam, - 'returned value:"%s" != test value:"%s"' % (rec[0], inParam), + f'returned value:"{rec[0]}" != test value:"{inParam}"', ) # now a test with a ":" as part of a literal -- and use a prepared query - ppdcmd = ( - "insert into xx_%s (fldId,fldData) VALUES (:xyz,'six:five')" % config.tmp - ) + ppdcmd = f"insert into xx_{config.tmp} (fldId,fldData) VALUES (:xyz,'six:five')" crsr.prepare(ppdcmd) crsr.execute(ppdcmd, {"xyz": 30}) - crsr.execute("SELECT fldData FROM xx_%s WHERE fldID=30" % config.tmp) + crsr.execute(f"SELECT fldData FROM xx_{config.tmp} WHERE fldID=30") rec = crsr.fetchone() self.assertEqual(rec[0], "six:five") @@ -959,9 +918,9 @@ def testRollBack(self): self.helpCreateAndPopulateTableTemp(crsr) crsr.connection.commit() # commit the first bunch - crsr.execute("INSERT INTO xx_%s (fldData) VALUES(100)" % config.tmp) + crsr.execute(f"INSERT INTO xx_{config.tmp} (fldData) VALUES(100)") - selectSql = "SELECT fldData FROM xx_%s WHERE fldData=100" % config.tmp + selectSql = f"SELECT fldData FROM xx_{config.tmp} WHERE fldData=100" crsr.execute(selectSql) rs = crsr.fetchall() assert len(rs) == 1 @@ -970,7 +929,7 @@ def testRollBack(self): assert ( crsr.fetchone() is None ), "cursor.fetchone should return None if a query retrieves no rows" - crsr.execute("SELECT fldData from xx_%s" % config.tmp) + crsr.execute(f"SELECT fldData from xx_{config.tmp}") rs = crsr.fetchall() assert len(rs) == 9, "the original records should still be present" self.helpRollbackTblTemp() @@ -984,10 +943,10 @@ def testCommit(self): crsr = con2.cursor() self.helpCreateAndPopulateTableTemp(crsr) - crsr.execute("INSERT INTO xx_%s (fldData) VALUES(100)" % config.tmp) + crsr.execute(f"INSERT INTO xx_{config.tmp} (fldData) VALUES(100)") con2.commit() - selectSql = "SELECT fldData FROM xx_%s WHERE fldData=100" % config.tmp + selectSql = f"SELECT fldData FROM xx_{config.tmp} WHERE fldData=100" crsr.execute(selectSql) rs = crsr.fetchall() assert len(rs) == 1 @@ -1010,8 +969,8 @@ def testAutoRollback(self): assert not con2.autocommit, "unexpected beginning condition" crsr = con2.cursor() self.helpCreateAndPopulateTableTemp(crsr) - crsr.execute("INSERT INTO xx_%s (fldData) VALUES(100)" % config.tmp) - selectSql = "SELECT fldData FROM xx_%s WHERE fldData=100" % config.tmp + crsr.execute(f"INSERT INTO xx_{config.tmp} (fldData) VALUES(100)") + selectSql = f"SELECT fldData FROM xx_{config.tmp} WHERE fldData=100" crsr.execute(selectSql) rs = crsr.fetchall() assert len(rs) == 1 @@ -1037,10 +996,10 @@ def testAutoCommit(self): return # should be "SKIP" for ACCESS crsr = ac_conn.cursor() self.helpCreateAndPopulateTableTemp(crsr) - crsr.execute("INSERT INTO xx_%s (fldData) VALUES(100)" % config.tmp) + crsr.execute(f"INSERT INTO xx_{config.tmp} (fldData) VALUES(100)") crsr.close() with self.getCursor() as crsr: - selectSql = "SELECT fldData from xx_%s" % config.tmp + selectSql = f"SELECT fldData from xx_{config.tmp}" crsr.execute( selectSql ) # closing the connection should _not_ have forced rollback @@ -1057,12 +1016,12 @@ def testSwitchedAutoCommit(self): ac_conn.autocommit = True crsr = ac_conn.cursor() self.helpCreateAndPopulateTableTemp(crsr) - crsr.execute("INSERT INTO xx_%s (fldData) VALUES(100)" % config.tmp) + crsr.execute(f"INSERT INTO xx_{config.tmp} (fldData) VALUES(100)") crsr.close() conn = self.getConnection() ac_conn.close() with self.getCursor() as crsr: - selectSql = "SELECT fldData from xx_%s" % config.tmp + selectSql = f"SELECT fldData from xx_{config.tmp}" crsr.execute( selectSql ) # closing the connection should _not_ have forced rollback @@ -1086,22 +1045,19 @@ class XtendFloat(float): self.helpForceDropOnTblTemp() conn = self.getConnection() crsr = conn.cursor() - tabdef = ( - """ - CREATE TABLE xx_%s ( + tabdef = f""" + CREATE TABLE xx_{config.tmp} ( s VARCHAR(40) NOT NULL, i INTEGER NOT NULL, f REAL NOT NULL)""" - % config.tmp - ) crsr.execute(tabdef) crsr.execute( - "INSERT INTO xx_%s (s, i, f) VALUES (?, ?, ?)" % config.tmp, (xs, xi, xf) + f"INSERT INTO xx_{config.tmp} (s, i, f) VALUES (?, ?, ?)", (xs, xi, xf) ) crsr.close() conn = self.getConnection() with self.getCursor() as crsr: - selectSql = "SELECT s, i, f from xx_%s" % config.tmp + selectSql = f"SELECT s, i, f from xx_{config.tmp}" crsr.execute( selectSql ) # closing the connection should _not_ have forced rollback @@ -1172,17 +1128,13 @@ def testMultipleSetReturn(self): crsr = self.getCursor() self.helpCreateAndPopulateTableTemp(crsr) - spdef = """ + spdef = f""" CREATE PROCEDURE sp_DeleteMe_OnlyForTesting AS - SELECT fldData FROM xx_%s ORDER BY fldData ASC - SELECT fldData From xx_%s where fldData = -9999 - SELECT fldData FROM xx_%s ORDER BY fldData DESC - """ % ( - config.tmp, - config.tmp, - config.tmp, - ) + SELECT fldData FROM xx_{config.tmp} ORDER BY fldData ASC + SELECT fldData From xx_{config.tmp} where fldData = -9999 + SELECT fldData FROM xx_{config.tmp} ORDER BY fldData DESC + """ try: crsr.execute("DROP PROCEDURE sp_DeleteMe_OnlyForTesting") self.conn.commit() @@ -1224,7 +1176,7 @@ def testDatetimeProcedureParameter(self): [adodbapi.Timestamp(2014, 12, 25, 0, 1, 0), "Beep", " " * 30], ) - assert result[2] == "Dec 25 2014 12:01AM Beep", 'value was="%s"' % result[2] + assert result[2] == "Dec 25 2014 12:01AM Beep", f'value was="{result[2]}"' self.conn.rollback() def testIncorrectStoredProcedureParameter(self): @@ -1473,7 +1425,7 @@ def testCOMDate(self): 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 + assert abs(cmd - 37435.7604282) < 1.0 / 24, f"{cmd:f} more than an hour wrong" def testDateObjectFromCOMDate(self): cmd = self.tc.DateObjectFromCOMDate(37435.7604282) @@ -1573,7 +1525,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): with cleanup_manager(): defaultDateConverter = adodbapi.dateconverter print(__doc__) - print("Default Date Converter is %s" % (defaultDateConverter,)) + print(f"Default Date Converter is {defaultDateConverter}") dateconverter = defaultDateConverter unittest.TextTestRunner().run(mysuite) diff --git a/adodbapi/test/adodbapitestconfig.py b/adodbapi/test/adodbapitestconfig.py index 9ff2521c01..5f023a1645 100644 --- a/adodbapi/test/adodbapitestconfig.py +++ b/adodbapi/test/adodbapitestconfig.py @@ -23,8 +23,7 @@ node = platform.node() try: print( - "node=%s, is64bit.os()= %s, is64bit.Python()= %s" - % (node, is64bit.os(), is64bit.Python()) + f"node={node}, is64bit.os()= {is64bit.os()}, is64bit.Python()= {is64bit.Python()}" ) except: pass @@ -175,7 +174,7 @@ ] # get driver from http://www.postgresql.org/ftp/odbc/versions/ # test using positional and keyword arguments (bad example for real code) - print(" ...Testing PostgreSQL login to {}...".format(_computername)) + print(f" ...Testing PostgreSQL login to {_computername}...") doPostgresTest, connStrPostgres, dbPostgresConnect = tryconnection.try_connection( verbose, "%(prov_drv)s;Server=%(host)s;Database=%(database)s;uid=%(user)s;pwd=%(password)s;port=5430;", # note nonstandard port @@ -183,7 +182,7 @@ _password, _computername, _databasename, - **kws + **kws, ) assert ( diff --git a/adodbapi/test/dbapi20.py b/adodbapi/test/dbapi20.py index 5639e4c3c7..5bb6bc4966 100644 --- a/adodbapi/test/dbapi20.py +++ b/adodbapi/test/dbapi20.py @@ -113,10 +113,10 @@ class mytest(dbapi20.DatabaseAPI20Test): connect_kw_args = {} # Keyword arguments for connect table_prefix = "dbapi20test_" # If you need to specify a prefix for tables - ddl1 = "create table %sbooze (name varchar(20))" % table_prefix - ddl2 = "create table %sbarflys (name varchar(20), drink varchar(30))" % table_prefix - xddl1 = "drop table %sbooze" % table_prefix - xddl2 = "drop table %sbarflys" % table_prefix + ddl1 = f"create table {table_prefix}booze (name varchar(20))" + ddl2 = f"create table {table_prefix}barflys (name varchar(20), drink varchar(30))" + xddl1 = f"drop table {table_prefix}booze" + xddl2 = f"drop table {table_prefix}barflys" lowerfunc = "lower" # Name of stored procedure to convert string->lowercase @@ -267,9 +267,9 @@ def test_cursor_isolation(self): cur2 = con.cursor() self.executeDDL1(cur1) cur1.execute( - "insert into %sbooze values ('Victoria Bitter')" % (self.table_prefix) + f"insert into {self.table_prefix}booze values ('Victoria Bitter')" ) - cur2.execute("select name from %sbooze" % self.table_prefix) + cur2.execute(f"select name from {self.table_prefix}booze") booze = cur2.fetchall() self.assertEqual(len(booze), 1) self.assertEqual(len(booze[0]), 1) @@ -288,7 +288,7 @@ def test_description(self): "cursor.description should be none after executing a " "statement that can return no rows (such as DDL)", ) - cur.execute("select name from %sbooze" % self.table_prefix) + cur.execute(f"select name from {self.table_prefix}booze") self.assertEqual( len(cur.description), 1, "cursor.description describes too many columns" ) @@ -305,8 +305,7 @@ def test_description(self): self.assertEqual( cur.description[0][1], self.driver.STRING, - "cursor.description[x][1] must return column type. Got %r" - % cur.description[0][1], + f"cursor.description[x][1] must return column type. Got {cur.description[0][1]!r}", ) # Make sure self.description gets reset @@ -331,14 +330,14 @@ def test_rowcount(self): "statements", ) cur.execute( - "insert into %sbooze values ('Victoria Bitter')" % (self.table_prefix) + f"insert into {self.table_prefix}booze values ('Victoria Bitter')" ) self.assertTrue( cur.rowcount in (-1, 1), "cursor.rowcount should == number or rows inserted, or " "set to -1 after executing an insert statement", ) - cur.execute("select name from %sbooze" % self.table_prefix) + cur.execute(f"select name from {self.table_prefix}booze") self.assertTrue( cur.rowcount in (-1, 1), "cursor.rowcount should == number of rows returned, or " @@ -406,46 +405,40 @@ def test_execute(self): def _paraminsert(self, cur): self.executeDDL2(cur) cur.execute( - "insert into %sbarflys values ('Victoria Bitter', 'thi%%s :may ca%%(u)se? troub:1e')" - % (self.table_prefix) + f"insert into {self.table_prefix}barflys values ('Victoria Bitter', 'thi%s :may ca%(u)se? troub:1e')" ) self.assertTrue(cur.rowcount in (-1, 1)) if self.driver.paramstyle == "qmark": cur.execute( - "insert into %sbarflys values (?, 'thi%%s :may ca%%(u)se? troub:1e')" - % self.table_prefix, + f"insert into {self.table_prefix}barflys values (?, 'thi%s :may ca%(u)se? troub:1e')", ("Cooper's",), ) elif self.driver.paramstyle == "numeric": cur.execute( - "insert into %sbarflys values (:1, 'thi%%s :may ca%%(u)se? troub:1e')" - % self.table_prefix, + f"insert into {self.table_prefix}barflys values (:1, 'thi%s :may ca%(u)se? troub:1e')", ("Cooper's",), ) elif self.driver.paramstyle == "named": cur.execute( - "insert into %sbarflys values (:beer, 'thi%%s :may ca%%(u)se? troub:1e')" - % self.table_prefix, + f"insert into {self.table_prefix}barflys values (:beer, 'thi%s :may ca%(u)se? troub:1e')", {"beer": "Cooper's"}, ) elif self.driver.paramstyle == "format": cur.execute( - "insert into %sbarflys values (%%s, 'thi%%s :may ca%%(u)se? troub:1e')" - % self.table_prefix, + f"insert into {self.table_prefix}barflys values (%s, 'thi%s :may ca%(u)se? troub:1e')", ("Cooper's",), ) elif self.driver.paramstyle == "pyformat": cur.execute( - "insert into %sbarflys values (%%(beer)s, 'thi%%s :may ca%%(u)se? troub:1e')" - % self.table_prefix, + f"insert into {self.table_prefix}barflys values (%(beer)s, 'thi%s :may ca%(u)se? troub:1e')", {"beer": "Cooper's"}, ) else: self.fail("Invalid paramstyle") self.assertTrue(cur.rowcount in (-1, 1)) - cur.execute("select name, drink from %sbarflys" % self.table_prefix) + cur.execute(f"select name, drink from {self.table_prefix}barflys") res = cur.fetchall() self.assertEqual(len(res), 2, "cursor.fetchall returned too few rows") beers = [res[0][0], res[1][0]] @@ -483,23 +476,23 @@ def test_executemany(self): margs = [{"beer": "Cooper's"}, {"beer": "Boag's"}] if self.driver.paramstyle == "qmark": cur.executemany( - "insert into %sbooze values (?)" % self.table_prefix, largs + f"insert into {self.table_prefix}booze values (?)", largs ) elif self.driver.paramstyle == "numeric": cur.executemany( - "insert into %sbooze values (:1)" % self.table_prefix, largs + f"insert into {self.table_prefix}booze values (:1)", largs ) elif self.driver.paramstyle == "named": cur.executemany( - "insert into %sbooze values (:beer)" % self.table_prefix, margs + f"insert into {self.table_prefix}booze values (:beer)", margs ) elif self.driver.paramstyle == "format": cur.executemany( - "insert into %sbooze values (%%s)" % self.table_prefix, largs + f"insert into {self.table_prefix}booze values (%s)", largs ) elif self.driver.paramstyle == "pyformat": cur.executemany( - "insert into %sbooze values (%%(beer)s)" % (self.table_prefix), + f"insert into {self.table_prefix}booze values (%(beer)s)", margs, ) else: @@ -507,9 +500,9 @@ def test_executemany(self): self.assertTrue( cur.rowcount in (-1, 2), "insert using cursor.executemany set cursor.rowcount to " - "incorrect value %r" % cur.rowcount, + f"incorrect value {cur.rowcount!r}", ) - cur.execute("select name from %sbooze" % self.table_prefix) + cur.execute(f"select name from {self.table_prefix}booze") res = cur.fetchall() self.assertEqual( len(res), 2, "cursor.fetchall retrieved incorrect number of rows" @@ -517,7 +510,7 @@ def test_executemany(self): beers = [res[0][0], res[1][0]] beers.sort() self.assertEqual( - beers[0], "Boag's", 'incorrect data "%s" retrieved' % beers[0] + beers[0], "Boag's", f'incorrect data "{beers[0]}" retrieved' ) self.assertEqual(beers[1], "Cooper's", "incorrect data retrieved") finally: @@ -537,7 +530,7 @@ def test_fetchone(self): self.executeDDL1(cur) self.assertRaises(self.driver.Error, cur.fetchone) - cur.execute("select name from %sbooze" % self.table_prefix) + cur.execute(f"select name from {self.table_prefix}booze") self.assertEqual( cur.fetchone(), None, @@ -548,11 +541,11 @@ def test_fetchone(self): # cursor.fetchone should raise an Error if called after # executing a query that cannnot return rows cur.execute( - "insert into %sbooze values ('Victoria Bitter')" % (self.table_prefix) + f"insert into {self.table_prefix}booze values ('Victoria Bitter')" ) self.assertRaises(self.driver.Error, cur.fetchone) - cur.execute("select name from %sbooze" % self.table_prefix) + cur.execute(f"select name from {self.table_prefix}booze") r = cur.fetchone() self.assertEqual( len(r), 1, "cursor.fetchone should have retrieved a single row" @@ -583,8 +576,7 @@ def _populate(self): tests. """ populate = [ - "insert into %sbooze values ('%s')" % (self.table_prefix, s) - for s in self.samples + f"insert into {self.table_prefix}booze values ('{s}')" for s in self.samples ] return populate @@ -601,7 +593,7 @@ def test_fetchmany(self): for sql in self._populate(): cur.execute(sql) - cur.execute("select name from %sbooze" % self.table_prefix) + cur.execute(f"select name from {self.table_prefix}booze") r = cur.fetchmany() self.assertEqual( len(r), @@ -629,7 +621,7 @@ def test_fetchmany(self): # Same as above, using cursor.arraysize cur.arraysize = 4 - cur.execute("select name from %sbooze" % self.table_prefix) + cur.execute(f"select name from {self.table_prefix}booze") r = cur.fetchmany() # Should get 4 rows self.assertEqual( len(r), 4, "cursor.arraysize not being honoured by fetchmany" @@ -641,7 +633,7 @@ def test_fetchmany(self): self.assertTrue(cur.rowcount in (-1, 6)) cur.arraysize = 6 - cur.execute("select name from %sbooze" % self.table_prefix) + cur.execute(f"select name from {self.table_prefix}booze") rows = cur.fetchmany() # Should get all rows self.assertTrue(cur.rowcount in (-1, 6)) self.assertEqual(len(rows), 6) @@ -667,7 +659,7 @@ def test_fetchmany(self): self.assertTrue(cur.rowcount in (-1, 6)) self.executeDDL2(cur) - cur.execute("select name from %sbarflys" % self.table_prefix) + cur.execute(f"select name from {self.table_prefix}barflys") r = cur.fetchmany() # Should get empty sequence self.assertEqual( len(r), @@ -697,7 +689,7 @@ def test_fetchall(self): # after executing a a statement that cannot return rows self.assertRaises(self.driver.Error, cur.fetchall) - cur.execute("select name from %sbooze" % self.table_prefix) + cur.execute(f"select name from {self.table_prefix}booze") rows = cur.fetchall() self.assertTrue(cur.rowcount in (-1, len(self.samples))) self.assertEqual( @@ -721,7 +713,7 @@ def test_fetchall(self): self.assertTrue(cur.rowcount in (-1, len(self.samples))) self.executeDDL2(cur) - cur.execute("select name from %sbarflys" % self.table_prefix) + cur.execute(f"select name from {self.table_prefix}barflys") rows = cur.fetchall() self.assertTrue(cur.rowcount in (-1, 0)) self.assertEqual( @@ -742,7 +734,7 @@ def test_mixedfetch(self): for sql in self._populate(): cur.execute(sql) - cur.execute("select name from %sbooze" % self.table_prefix) + cur.execute(f"select name from {self.table_prefix}booze") rows1 = cur.fetchone() rows23 = cur.fetchmany(2) rows4 = cur.fetchone() @@ -830,8 +822,8 @@ def test_None(self): try: cur = con.cursor() self.executeDDL1(cur) - cur.execute("insert into %sbooze values (NULL)" % self.table_prefix) - cur.execute("select name from %sbooze" % self.table_prefix) + cur.execute(f"insert into {self.table_prefix}booze values (NULL)") + cur.execute(f"select name from {self.table_prefix}booze") r = cur.fetchall() self.assertEqual(len(r), 1) self.assertEqual(len(r[0]), 1) diff --git a/adodbapi/test/test_adodbapi_dbapi20.py b/adodbapi/test/test_adodbapi_dbapi20.py index 6218b7997e..26faab9b26 100644 --- a/adodbapi/test/test_adodbapi_dbapi20.py +++ b/adodbapi/test/test_adodbapi_dbapi20.py @@ -27,7 +27,7 @@ db.adodbapi.verbose = 3 print(adodbapi.version) -print("Tested with dbapi20 %s" % dbapi20.__version__) +print(f"Tested with dbapi20 {dbapi20.__version__}") try: onWindows = bool(sys.getwindowsversion()) # seems to work on all versions of Python @@ -65,21 +65,14 @@ _password = "12345678" _driver = "PostgreSQL Unicode" _provider = "" - connStr = "%sDriver={%s};Server=%s;Database=%s;uid=%s;pwd=%s;" % ( - _provider, - _driver, - _computername, - _databasename, - _username, - _password, - ) + connStr = f"{_provider}Driver={{{_driver}}};Server={_computername};Database={_databasename};uid={_username};pwd={_password};" elif node == "yyy": # ACCESS data base is known to fail some tests. if is64bit.Python(): driver = "Microsoft.ACE.OLEDB.12.0" else: driver = "Microsoft.Jet.OLEDB.4.0" testmdb = setuptestframework.makemdb(testfolder) - connStr = r"Provider=%s;Data Source=%s" % (driver, testmdb) + connStr = rf"Provider={driver};Data Source={testmdb}" print(f"Using Connection String like={connStr}") print(f"Keywords={conn_kws!r}") @@ -142,16 +135,13 @@ def tearDown(self): def help_nextset_setUp(self, cur): "Should create a procedure called deleteme" 'that returns two result sets, first the number of rows in booze then "name from booze"' - sql = """ + sql = f""" create procedure deleteme as begin - select count(*) from %sbooze - select name from %sbooze + select count(*) from {self.table_prefix}booze + select name from {self.table_prefix}booze end - """ % ( - self.table_prefix, - self.table_prefix, - ) + """ cur.execute(sql) def help_nextset_tearDown(self, cur): diff --git a/ruff.toml b/ruff.toml index dfe936c5c0..8e70c2b153 100644 --- a/ruff.toml +++ b/ruff.toml @@ -39,7 +39,7 @@ select = [ # Explicit re-exports is fine in __init__.py, still a code smell elsewhere. "__init__.py" = ["PLC0414"] # TODO: Make adodbapi changes in their own PRs -"adodbapi/*" = ["C4", "YTT301", "UP031", "UP032", "ISC002"] +"adodbapi/*" = ["C4", "YTT301", "ISC002"] [lint.isort] combine-as-imports = true From 3376deddf1f2c8955d268cb3e1795fffa6bb3cec Mon Sep 17 00:00:00 2001 From: Avasam Date: Fri, 18 Oct 2024 15:01:47 -0400 Subject: [PATCH 2/4] Move back 2 comments --- adodbapi/process_connect_string.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/adodbapi/process_connect_string.py b/adodbapi/process_connect_string.py index ac63f49dc6..790e93eedb 100644 --- a/adodbapi/process_connect_string.py +++ b/adodbapi/process_connect_string.py @@ -86,11 +86,11 @@ def process( dsn = args[0] except IndexError: dsn = None - if isinstance( - dsn, dict - ): # as a convenience the first argument may be django settings + # as a convenience the first argument may be django settings + if isinstance(dsn, dict): kwargs.update(dsn) - elif dsn: # the connection string is passed to the connection as part of the keyword dictionary + # the connection string is passed to the connection as part of the keyword dictionary + elif dsn: kwargs["connection_string"] = dsn try: a1 = args[1] From 1cc6940d920ed02706a7cf1353e97a51ed51a006 Mon Sep 17 00:00:00 2001 From: Avasam Date: Tue, 12 Nov 2024 00:42:06 -0500 Subject: [PATCH 3/4] Update ruff.toml --- ruff.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruff.toml b/ruff.toml index 162fe83c17..fdea95662a 100644 --- a/ruff.toml +++ b/ruff.toml @@ -45,7 +45,7 @@ extend-ignore = [ # Explicit re-exports is fine in __init__.py, still a code smell elsewhere. "__init__.py" = ["PLC0414"] # TODO: Make adodbapi changes in their own PRs -"adodbapi/*" = ["C4", "YTT301", "ISC002", "UP031", "UP032"] +"adodbapi/*" = ["C4", "YTT301"] [lint.isort] combine-as-imports = true From 5c7b4e207806faa579e8b1b20ef12725aa9732af Mon Sep 17 00:00:00 2001 From: Avasam Date: Tue, 7 Jan 2025 23:14:08 -0500 Subject: [PATCH 4/4] Ruff 0.8.6 update --- adodbapi/adodbapi.py | 7 +++---- adodbapi/examples/db_print.py | 15 ++++++++++----- adodbapi/test/adodbapitest.py | 2 +- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/adodbapi/adodbapi.py b/adodbapi/adodbapi.py index c56d9f018f..aacd5005ba 100644 --- a/adodbapi/adodbapi.py +++ b/adodbapi/adodbapi.py @@ -456,7 +456,7 @@ def _i_am_closing(self, crsr): def printADOerrors(self): j = self.connector.Errors.Count if j: - print("ADO Errors:(%i)" % j) + print(f"ADO Errors:({j})") for e in self.connector.Errors: print(f"Description: {e.Description}") print( @@ -850,8 +850,7 @@ def _buildADOparameterList(self, parameters, sproc=False): else: if len(parameters) != self.cmd.Parameters.Count - 1: raise api.ProgrammingError( - "You must supply %d parameters for this stored procedure" - % (self.cmd.Parameters.Count - 1) + f"You must supply {(self.cmd.Parameters.Count - 1)} parameters for this stored procedure" ) if sproc or parameters != []: i = 0 @@ -909,7 +908,7 @@ def _buildADOparameterList(self, parameters, sproc=False): self.cmd.Parameters.Append(p) for elem in parameters: - name = "p%i" % i + name = f"p{i}" adotype = api.pyTypeToADOType(elem) p = self.cmd.CreateParameter( name, adotype, adc.adParamInput diff --git a/adodbapi/examples/db_print.py b/adodbapi/examples/db_print.py index 514581169f..7c309f7e4f 100644 --- a/adodbapi/examples/db_print.py +++ b/adodbapi/examples/db_print.py @@ -44,16 +44,21 @@ c.execute(sql) # check the results - print( - 'result rowcount shows as= %d. (Note: -1 means "not known")' % (c.rowcount,) - ) + print('result rowcount shows as= c.rowcount. (Note: -1 means "not known")') print("") print("result data description is:") print(" NAME Type DispSize IntrnlSz Prec Scale Null?") for d in c.description: print( - ("%16s %-12s %8s %8d %4d %5d %s") - % (d[0], adc.adTypeNames[d[1]], d[2], d[3], d[4], d[5], bool(d[6])) + "{:>16} {:<12} {:>8} {:>8} {:>4} {:>5} {}".format( # noqa: UP032 + 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...") diff --git a/adodbapi/test/adodbapitest.py b/adodbapi/test/adodbapitest.py index cc375bf0fe..44f8671348 100644 --- a/adodbapi/test/adodbapitest.py +++ b/adodbapi/test/adodbapitest.py @@ -465,7 +465,7 @@ def helpCreateAndPopulateTableTemp(self, crsr): self.helpForceDropOnTblTemp() # so drop it now crsr.execute(tabdef) for i in range(9): # note: this poor SQL code, but a valid test - crsr.execute("INSERT INTO xx_%s (fldData) VALUES (%i)" % (config.tmp, i)) + crsr.execute(f"INSERT INTO xx_{config.tmp} (fldData) VALUES ({i})") # NOTE: building the test table without using parameter substitution def testFetchAll(self):