@@ -25,7 +25,28 @@ def check_django_compatability():
2525 )
2626
2727
28+ def set_wrapped_methods (cls ):
29+ """Initialize the wrapped methods on cls."""
30+ if hasattr (cls , "logging_wrapper" ):
31+ for attr in cls .wrapped_methods :
32+ setattr (cls , attr , cls .logging_wrapper (attr ))
33+ del cls .logging_wrapper
34+ return cls
35+
36+
37+ @set_wrapped_methods
2838class OperationDebugWrapper :
39+ # The PyMongo database and collection methods that this backend uses.
40+ wrapped_methods = {
41+ "aggregate" ,
42+ "create_collection" ,
43+ "drop" ,
44+ "insert_many" ,
45+ "delete_many" ,
46+ "rename" ,
47+ "update_many" ,
48+ }
49+
2950 def __init__ (self , db , collection = None ):
3051 self .collection = collection
3152 self .db = db
@@ -79,13 +100,20 @@ def wrapper(self, *args, **kwargs):
79100
80101 return wrapper
81102
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" )
90103
91- del logging_wrapper
104+ @set_wrapped_methods
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
0 commit comments