1313from typing import Any , AsyncIterator , Dict , List , Optional , Set , Tuple
1414
1515from rhosocial .activerecord .backend .base import AsyncStorageBackend
16+ from rhosocial .activerecord .backend .base .execution_logging import (
17+ log_batch_start ,
18+ log_batch_summary ,
19+ log_execution_error ,
20+ log_execution_start ,
21+ log_execution_summary ,
22+ )
1623from rhosocial .activerecord .backend .base .operations import AsyncSQLOperationsMixin
1724from rhosocial .activerecord .backend .base .transaction_management import AsyncTransactionManagementMixin
1825from rhosocial .activerecord .backend .errors import (
2330 OperationalError ,
2431 QueryError ,
2532)
33+ from rhosocial .activerecord .backend .options import ExecutionOptions , StatementType
2634from rhosocial .activerecord .backend .result import QueryResult
35+ from rhosocial .activerecord .logging .redaction import unwrap_sensitive
2736from rhosocial .activerecord .backend .introspection .backend_mixin import IntrospectorBackendMixin
2837from ..config import SQLServerConnectionConfig
2938from ..dialect import SQLServerDialect
@@ -70,7 +79,12 @@ class AsyncSQLServerBackend(
7079 >>> print(result.data)
7180 >>> await backend.disconnect()
7281 """
73-
82+
83+ # ``AsyncSQLServerBackend`` would otherwise be named
84+ # ``rhosocial.activerecord.backend.asyncsqlserver``; share the sync name so
85+ # both halves of the backend emit to one library logger.
86+ _logger_name = "rhosocial.activerecord.backend.sqlserver"
87+
7488 CONNECTION_ERROR_CODES = {
7589 53 , 64 , 232 , 233 , 18456 , 4060 , 40197 , 40501 , 40613 , 11001 ,
7690 }
@@ -227,7 +241,7 @@ async def connect(self) -> None:
227241 await self .introspect_and_adapt ()
228242
229243 except Exception as e :
230- self .log (logging .ERROR , f"Failed to connect to SQL Server: { str (e )} " )
244+ self .log (logging .DEBUG , f"Failed to connect to SQL Server: { str (e )} " )
231245 raise ConnectionError (f"Failed to connect to SQL Server: { str (e )} " ) from e
232246
233247 async def disconnect (self ) -> None :
@@ -366,10 +380,11 @@ async def _cursor_noscan(self, cursor: Any, noscan: Optional[bool]) -> AsyncIter
366380 async def _execute_statement (
367381 self , sql : str , params : Optional [Tuple ], options , start_time : Optional [float ] = None
368382 ) -> QueryResult :
369- from rhosocial .activerecord .backend .options import StatementType
370-
383+ """Execute one statement without re-entering the backend overrides."""
371384 sql_upper = sql .strip ().upper ()
372-
385+ params = unwrap_sensitive (params )
386+ log_execution_start (self , sql , params , options )
387+
373388 if not self ._connection :
374389 await self .connect ()
375390
@@ -438,10 +453,9 @@ async def _execute_statement(
438453 duration = time .perf_counter () - start_time
439454
440455 await self ._handle_auto_commit_if_needed ()
441-
442- self .log (
443- logging .DEBUG ,
444- f"Query executed in { duration :.3f} s, affected { cursor .rowcount } rows"
456+
457+ log_execution_summary (
458+ self , options .stmt_type , sql , cursor , data , duration , options
445459 )
446460
447461 result = self ._build_query_result (cursor , data , duration )
@@ -454,43 +468,55 @@ async def _execute_statement(
454468 return result
455469
456470 except Exception as e :
457- self . log ( logging . ERROR , f"Error executing query: { str ( e ) } " )
471+ log_execution_error ( self , e , options )
458472 await self ._handle_error (e )
459473
460- async def execute_many (self , sql : str , params_list : List [Tuple ]) -> QueryResult :
474+ async def execute_many (
475+ self ,
476+ sql : str ,
477+ params_list : List [Tuple ],
478+ * ,
479+ options : Optional [ExecutionOptions ] = None ,
480+ ) -> Optional [QueryResult ]:
461481 """Execute the same SQL statement multiple times asynchronously.
462-
482+
463483 Args:
464484 sql: SQL statement to execute
465485 params_list: List of parameter tuples
466-
486+ options: ExecutionOptions carrying the logging context
487+
467488 Returns:
468489 QueryResult with affected_rows populated
469490 """
491+ if options is None :
492+ options = ExecutionOptions (stmt_type = StatementType .DML )
493+ params_list = [unwrap_sensitive (params ) for params in params_list ]
494+ log_batch_start (self , sql , params_list , options )
495+
470496 if not self ._connection :
471497 await self .connect ()
472498
473499 start_time = time .perf_counter ()
474500
475501 try :
476- if not params_list :
477- self .log (logging .DEBUG , "Empty parameter list, returning zero affected rows" )
478- return QueryResult (affected_rows = 0 , data = None , duration = 0.0 )
479-
480502 async with await self ._get_cursor () as cursor :
503+ if not params_list :
504+ duration = time .perf_counter () - start_time
505+ log_batch_summary (self , sql , params_list , 0 , duration , options )
506+ return QueryResult (affected_rows = 0 , data = None , duration = duration )
507+
481508 await cursor .executemany (sql , params_list )
482-
509+
483510 duration = time .perf_counter () - start_time
484511 affected_rows = cursor .rowcount
485-
512+
513+ log_batch_summary (self , sql , params_list , affected_rows , duration , options )
486514 await self ._handle_auto_commit_if_needed ()
487-
488- self .log (logging .INFO , f"Batch operation completed, affected { affected_rows } rows" )
489-
515+
490516 return QueryResult (affected_rows = affected_rows , data = None , duration = duration )
491-
517+
492518 except Exception as e :
493- self . log ( logging . ERROR , f"Error in batch operation: { str ( e ) } " )
519+ log_execution_error ( self , e , options )
494520 await self ._handle_error (e )
495521
496522 async def get_server_version (self ) -> Tuple [int , int , int ]:
@@ -556,7 +582,7 @@ async def ping(self, reconnect: bool = True) -> bool:
556582 await self .connect ()
557583 return True
558584 except Exception as connect_error :
559- self .log (logging .ERROR , f"Reconnect failed: { str (connect_error )} " )
585+ self .log (logging .WARNING , f"Reconnect failed: { str (connect_error )} " )
560586 return False
561587 return False
562588
@@ -580,7 +606,7 @@ async def executescript(self, sql_script: str) -> None:
580606 Args:
581607 sql_script: SQL script with GO separators
582608 """
583- self .log (logging .INFO , "Executing SQL script (async)" )
609+ self .log (logging .DEBUG , "Executing SQL script (async)" )
584610 start_time = time .perf_counter ()
585611
586612 if not self ._connection :
@@ -600,7 +626,7 @@ async def executescript(self, sql_script: str) -> None:
600626 self .log (logging .INFO , f"SQL script executed successfully, duration={ duration :.3f} s" )
601627
602628 except Exception as e :
603- self .log (logging .ERROR , f"Error executing SQL script: { str (e )} " )
629+ self .log (logging .DEBUG , f"Error executing SQL script: { str (e )} " )
604630 await self ._handle_error (e )
605631
606632 async def _handle_error (self , error : Exception ) -> None :
@@ -621,23 +647,23 @@ async def _handle_error(self, error: Exception) -> None:
621647 or 'cannot insert the value null' in error_msg
622648 ):
623649 if "duplicate" in error_msg or "unique" in error_msg :
624- self .log (logging .ERROR , f"Unique constraint violation: { str (error )} " )
650+ self .log (logging .DEBUG , f"Unique constraint violation: { str (error )} " )
625651 raise IntegrityError (f"Unique constraint violation: { str (error )} " )
626652 elif "foreign key" in error_msg or "reference" in error_msg :
627- self .log (logging .ERROR , f"Foreign key constraint violation: { str (error )} " )
653+ self .log (logging .DEBUG , f"Foreign key constraint violation: { str (error )} " )
628654 raise IntegrityError (f"Foreign key constraint violation: { str (error )} " )
629- self .log (logging .ERROR , f"Integrity error: { str (error )} " )
655+ self .log (logging .DEBUG , f"Integrity error: { str (error )} " )
630656 raise IntegrityError (self ._normalize_integrity_message (str (error )))
631657
632658 if 'deadlock' in error_msg or '1205' in error_msg :
633- self .log (logging .ERROR , f"Deadlock detected: { str (error )} " )
659+ self .log (logging .DEBUG , f"Deadlock detected: { str (error )} " )
634660 raise DeadlockError (str (error ))
635661
636662 if 'timeout' in error_msg or 'connection' in error_msg :
637- self .log (logging .ERROR , f"Operational error: { str (error )} " )
663+ self .log (logging .DEBUG , f"Operational error: { str (error )} " )
638664 raise OperationalError (str (error ))
639665
640- self .log (logging .ERROR , f"Database error: { str (error )} " )
666+ self .log (logging .DEBUG , f"Database error: { str (error )} " )
641667 raise DatabaseError (str (error ))
642668
643669 async def _handle_auto_commit_if_needed (self ) -> None :
0 commit comments