@@ -26,6 +26,17 @@ def check_django_compatability():
2626
2727
2828class OperationDebugWrapper :
29+ # The PyMongo database and collection methods that this backend uses.
30+ wrapped_methods = {
31+ "aggregate" ,
32+ "create_collection" ,
33+ "drop" ,
34+ "insert_many" ,
35+ "delete_many" ,
36+ "rename" ,
37+ "update_many" ,
38+ }
39+
2940 def __init__ (self , db , collection = None ):
3041 self .collection = collection
3142 self .db = db
@@ -79,13 +90,33 @@ def wrapper(self, *args, **kwargs):
7990
8091 return wrapper
8192
82- # These are the operations that this backend uses.
83- aggregate = logging_wrapper ("aggregate" )
84- create_collection = logging_wrapper ("create_collection" )
85- drop = logging_wrapper ("drop" )
86- insert_many = logging_wrapper ("insert_many" )
87- delete_many = logging_wrapper ("delete_many" )
88- rename = logging_wrapper ("rename" )
89- update_many = logging_wrapper ("update_many" )
9093
91- del logging_wrapper
94+ def set_wrapped_methods (cls ):
95+ """Initialize the wrapped methods on cls."""
96+ if hasattr (cls , "logging_wrapper" ):
97+ for attr in cls .wrapped_methods :
98+ setattr (cls , attr , cls .logging_wrapper (attr ))
99+ del cls .logging_wrapper
100+
101+
102+ set_wrapped_methods (OperationDebugWrapper )
103+
104+
105+ class OperationCollector (OperationDebugWrapper ):
106+ def __init__ (self , collected_sql = None , * , collection = None , db = None ):
107+ super ().__init__ (db , collection )
108+ self .collected_sql = collected_sql
109+
110+ def log (self , op , args , kwargs = None ):
111+ args = ", " .join (repr (arg ) for arg in args )
112+ operation = f"db.{ self .collection_name } { op } ({ args } )"
113+ self .collected_sql .append (operation )
114+
115+ def logging_wrapper (method ):
116+ def wrapper (self , * args , ** kwargs ):
117+ self .log (method , args , kwargs )
118+
119+ return wrapper
120+
121+
122+ set_wrapped_methods (OperationCollector )
0 commit comments