Skip to content

Commit 27310da

Browse files
committed
Python linting issue
1 parent 10744c8 commit 27310da

File tree

3 files changed

+197
-174
lines changed

3 files changed

+197
-174
lines changed

mssql_python/connection.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@
5959

6060
# Valid encoding characters (alphanumeric, dash, underscore only)
6161
import string
62-
VALID_ENCODING_CHARS: frozenset[str] = frozenset(string.ascii_letters + string.digits + '-_')
62+
63+
VALID_ENCODING_CHARS: frozenset[str] = frozenset(string.ascii_letters + string.digits + "-_")
6364

6465

6566
def _validate_encoding(encoding: str) -> bool:
@@ -80,11 +81,11 @@ def _validate_encoding(encoding: str) -> bool:
8081
# First check for dangerous characters (security validation)
8182
if not all(c in VALID_ENCODING_CHARS for c in encoding):
8283
return False
83-
84+
8485
# Check length limit (prevent DOS)
8586
if len(encoding) > 100:
8687
return False
87-
88+
8889
# Then check if it's a valid Python codec
8990
try:
9091
codecs.lookup(encoding)
@@ -241,7 +242,7 @@ def __init__(
241242
# Initialize output converters dictionary and its lock for thread safety
242243
self._output_converters = {}
243244
self._converters_lock = threading.Lock()
244-
245+
245246
# Initialize encoding/decoding settings lock for thread safety
246247
# This lock protects both _encoding_settings and _decoding_settings dictionaries
247248
# to prevent race conditions when multiple threads are reading/writing encoding settings
@@ -449,7 +450,7 @@ def setencoding(self, encoding: Optional[str] = None, ctype: Optional[int] = Non
449450
# Normalize encoding to casefold for more robust Unicode handling
450451
encoding = encoding.casefold()
451452
logger.debug("setencoding: Encoding normalized to %s", encoding)
452-
453+
453454
# Reject 'utf-16' with BOM for SQL_WCHAR (ambiguous byte order)
454455
if encoding == "utf-16" and ctype == ConstantsDDBC.SQL_WCHAR.value:
455456
logger.debug(
@@ -489,7 +490,7 @@ def setencoding(self, encoding: Optional[str] = None, ctype: Optional[int] = Non
489490
f"SQL_WCHAR ({ConstantsDDBC.SQL_WCHAR.value})"
490491
),
491492
)
492-
493+
493494
# Validate that SQL_WCHAR ctype only used with UTF-16 encodings (not utf-16 with BOM)
494495
if ctype == ConstantsDDBC.SQL_WCHAR.value:
495496
if encoding == "utf-16":
@@ -540,7 +541,7 @@ def getencoding(self) -> Dict[str, Union[str, int]]:
540541
settings = cnxn.getencoding()
541542
print(f"Current encoding: {settings['encoding']}")
542543
print(f"Current ctype: {settings['ctype']}")
543-
544+
544545
Note:
545546
This method is thread-safe and can be called from multiple threads concurrently.
546547
"""
@@ -638,7 +639,7 @@ def setdecoding(
638639

639640
# Normalize encoding to lowercase for consistency
640641
encoding = encoding.lower()
641-
642+
642643
# Reject 'utf-16' with BOM for SQL_WCHAR (ambiguous byte order)
643644
if sqltype == ConstantsDDBC.SQL_WCHAR.value and encoding == "utf-16":
644645
logger.debug(
@@ -667,7 +668,7 @@ def setdecoding(
667668
f"SQL_WCHAR requires UTF-16 encodings (utf-16le, utf-16be)"
668669
),
669670
)
670-
671+
671672
# SQL_WMETADATA can use any valid encoding (UTF-8, UTF-16, etc.)
672673
# No restriction needed here - let users configure as needed
673674

@@ -693,7 +694,7 @@ def setdecoding(
693694
f"SQL_WCHAR ({ConstantsDDBC.SQL_WCHAR.value})"
694695
),
695696
)
696-
697+
697698
# Validate that SQL_WCHAR ctype only used with UTF-16 encodings (not utf-16 with BOM)
698699
if ctype == ConstantsDDBC.SQL_WCHAR.value:
699700
if encoding == "utf-16":
@@ -755,7 +756,7 @@ def getdecoding(self, sqltype: int) -> Dict[str, Union[str, int]]:
755756
settings = cnxn.getdecoding(mssql_python.SQL_CHAR)
756757
print(f"SQL_CHAR encoding: {settings['encoding']}")
757758
print(f"SQL_CHAR ctype: {settings['ctype']}")
758-
759+
759760
Note:
760761
This method is thread-safe and can be called from multiple threads concurrently.
761762
"""

mssql_python/cursor.py

Lines changed: 42 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,13 @@
2020
from mssql_python.helpers import check_error
2121
from mssql_python.logging import logger
2222
from mssql_python import ddbc_bindings
23-
from mssql_python.exceptions import InterfaceError, NotSupportedError, ProgrammingError, OperationalError, DatabaseError
23+
from mssql_python.exceptions import (
24+
InterfaceError,
25+
NotSupportedError,
26+
ProgrammingError,
27+
OperationalError,
28+
DatabaseError,
29+
)
2430
from mssql_python.row import Row
2531
from mssql_python import get_settings
2632

@@ -292,23 +298,21 @@ def _get_encoding_settings(self):
292298
Returns:
293299
dict: A dictionary with 'encoding' and 'ctype' keys, or default settings if not available
294300
"""
295-
if hasattr(self._connection, 'getencoding'):
301+
if hasattr(self._connection, "getencoding"):
296302
try:
297303
return self._connection.getencoding()
298304
except (OperationalError, DatabaseError) as db_error:
299305
# Only catch database-related errors, not programming errors
300306
from mssql_python.helpers import log
301-
log('warning', f"Failed to get encoding settings from connection due to database error: {db_error}")
302-
return {
303-
'encoding': 'utf-16le',
304-
'ctype': ddbc_sql_const.SQL_WCHAR.value
305-
}
307+
308+
log(
309+
"warning",
310+
f"Failed to get encoding settings from connection due to database error: {db_error}",
311+
)
312+
return {"encoding": "utf-16le", "ctype": ddbc_sql_const.SQL_WCHAR.value}
306313

307314
# Return default encoding settings if getencoding is not available
308-
return {
309-
'encoding': 'utf-16le',
310-
'ctype': ddbc_sql_const.SQL_WCHAR.value
311-
}
315+
return {"encoding": "utf-16le", "ctype": ddbc_sql_const.SQL_WCHAR.value}
312316

313317
def _get_decoding_settings(self, sql_type):
314318
"""
@@ -326,11 +330,15 @@ def _get_decoding_settings(self, sql_type):
326330
except (OperationalError, DatabaseError) as db_error:
327331
# Only handle expected database-related errors
328332
from mssql_python.helpers import log
329-
log('warning', f"Failed to get decoding settings for SQL type {sql_type} due to database error: {db_error}")
333+
334+
log(
335+
"warning",
336+
f"Failed to get decoding settings for SQL type {sql_type} due to database error: {db_error}",
337+
)
330338
if sql_type == ddbc_sql_const.SQL_WCHAR.value:
331-
return {'encoding': 'utf-16le', 'ctype': ddbc_sql_const.SQL_WCHAR.value}
339+
return {"encoding": "utf-16le", "ctype": ddbc_sql_const.SQL_WCHAR.value}
332340
else:
333-
return {'encoding': 'utf-8', 'ctype': ddbc_sql_const.SQL_CHAR.value}
341+
return {"encoding": "utf-8", "ctype": ddbc_sql_const.SQL_CHAR.value}
334342

335343
def _map_sql_type( # pylint: disable=too-many-arguments,too-many-positional-arguments,too-many-locals,too-many-return-statements,too-many-branches
336344
self,
@@ -1252,7 +1260,7 @@ def execute( # pylint: disable=too-many-locals,too-many-branches,too-many-state
12521260
parameters_type,
12531261
self.is_stmt_prepared,
12541262
use_prepare,
1255-
encoding_settings
1263+
encoding_settings,
12561264
)
12571265
# Check return code
12581266
try:
@@ -2130,7 +2138,12 @@ def fetchone(self) -> Union[None, Row]:
21302138
# Fetch raw data
21312139
row_data = []
21322140
try:
2133-
ret = ddbc_bindings.DDBCSQLFetchOne(self.hstmt, row_data, char_decoding.get('encoding', 'utf-8'), wchar_decoding.get('encoding', 'utf-16le'))
2141+
ret = ddbc_bindings.DDBCSQLFetchOne(
2142+
self.hstmt,
2143+
row_data,
2144+
char_decoding.get("encoding", "utf-8"),
2145+
wchar_decoding.get("encoding", "utf-16le"),
2146+
)
21342147

21352148
if self.hstmt:
21362149
self.messages.extend(ddbc_bindings.DDBCSQLGetAllDiagRecords(self.hstmt))
@@ -2184,7 +2197,13 @@ def fetchmany(self, size: Optional[int] = None) -> List[Row]:
21842197
# Fetch raw data
21852198
rows_data = []
21862199
try:
2187-
ret = ddbc_bindings.DDBCSQLFetchMany(self.hstmt, rows_data, size, char_decoding.get('encoding', 'utf-8'), wchar_decoding.get('encoding', 'utf-16le'))
2200+
ret = ddbc_bindings.DDBCSQLFetchMany(
2201+
self.hstmt,
2202+
rows_data,
2203+
size,
2204+
char_decoding.get("encoding", "utf-8"),
2205+
wchar_decoding.get("encoding", "utf-16le"),
2206+
)
21882207

21892208
if self.hstmt:
21902209
self.messages.extend(ddbc_bindings.DDBCSQLGetAllDiagRecords(self.hstmt))
@@ -2230,7 +2249,12 @@ def fetchall(self) -> List[Row]:
22302249
# Fetch raw data
22312250
rows_data = []
22322251
try:
2233-
ret = ddbc_bindings.DDBCSQLFetchAll(self.hstmt, rows_data, char_decoding.get('encoding', 'utf-8'), wchar_decoding.get('encoding', 'utf-16le'))
2252+
ret = ddbc_bindings.DDBCSQLFetchAll(
2253+
self.hstmt,
2254+
rows_data,
2255+
char_decoding.get("encoding", "utf-8"),
2256+
wchar_decoding.get("encoding", "utf-16le"),
2257+
)
22342258

22352259
if self.hstmt:
22362260
self.messages.extend(ddbc_bindings.DDBCSQLGetAllDiagRecords(self.hstmt))

0 commit comments

Comments
 (0)