@@ -386,6 +386,12 @@ def setencoding(self, encoding=None, ctype=None):
386386 ddbc_error = f"ctype must be SQL_CHAR ({ ConstantsDDBC .SQL_CHAR .value } ) or SQL_WCHAR ({ ConstantsDDBC .SQL_WCHAR .value } )" ,
387387 )
388388
389+ # Enforce UTF-16 encoding restriction for SQL_WCHAR
390+ if ctype == ConstantsDDBC .SQL_WCHAR .value and encoding not in UTF16_ENCODINGS :
391+ log ('warning' , "SQL_WCHAR only supports UTF-16 encodings. Attempted encoding '%s' is not allowed. Using default 'utf-16le' instead." ,
392+ sanitize_user_input (encoding ))
393+ encoding = 'utf-16le'
394+
389395 # Store the encoding settings
390396 self ._encoding_settings = {
391397 'encoding' : encoding ,
@@ -489,13 +495,26 @@ def setdecoding(self, sqltype, encoding=None, ctype=None):
489495 # Normalize encoding to lowercase for consistency
490496 encoding = encoding .lower ()
491497
498+ # Enforce UTF-16 encoding restriction for SQL_WCHAR and SQL_WMETADATA
499+ if (sqltype == ConstantsDDBC .SQL_WCHAR .value or sqltype == SQL_WMETADATA ) and encoding not in UTF16_ENCODINGS :
500+ sqltype_name = "SQL_WCHAR" if sqltype == ConstantsDDBC .SQL_WCHAR .value else "SQL_WMETADATA"
501+ log ('warning' , "%s only supports UTF-16 encodings. Attempted encoding '%s' is not allowed. Using default 'utf-16le' instead." ,
502+ sqltype_name , sanitize_user_input (encoding ))
503+ encoding = 'utf-16le'
504+
492505 # Set default ctype based on encoding if not provided
493506 if ctype is None :
494507 if encoding in UTF16_ENCODINGS :
495508 ctype = ConstantsDDBC .SQL_WCHAR .value
496509 else :
497510 ctype = ConstantsDDBC .SQL_CHAR .value
498511
512+ # Additional validation: if user explicitly sets ctype to SQL_WCHAR but encoding is not UTF-16
513+ if ctype == ConstantsDDBC .SQL_WCHAR .value and encoding not in UTF16_ENCODINGS :
514+ log ('warning' , "SQL_WCHAR ctype only supports UTF-16 encodings. Attempted encoding '%s' is not compatible. Using default 'utf-16le' instead." ,
515+ sanitize_user_input (encoding ))
516+ encoding = 'utf-16le'
517+
499518 # Validate ctype
500519 valid_ctypes = [ConstantsDDBC .SQL_CHAR .value , ConstantsDDBC .SQL_WCHAR .value ]
501520 if ctype not in valid_ctypes :
0 commit comments