@@ -26,6 +26,17 @@ def check_django_compatability():
26
26
27
27
28
28
class 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
+
29
40
def __init__ (self , db , collection = None ):
30
41
self .collection = collection
31
42
self .db = db
@@ -82,13 +93,34 @@ def wrapper(self, *args, **kwargs):
82
93
83
94
return wrapper
84
95
85
- # These are the operations that this backend uses.
86
- aggregate = logging_wrapper ("aggregate" )
87
- create_collection = logging_wrapper ("create_collection" )
88
- drop = logging_wrapper ("drop" )
89
- insert_many = logging_wrapper ("insert_many" )
90
- delete_many = logging_wrapper ("delete_many" )
91
- rename = logging_wrapper ("rename" )
92
- update_many = logging_wrapper ("update_many" )
93
96
94
- del logging_wrapper
97
+ if hasattr (OperationDebugWrapper , "logging_wrapper" ):
98
+ for attr in OperationDebugWrapper .wrapped_methods :
99
+ setattr (OperationDebugWrapper , attr , OperationDebugWrapper .logging_wrapper (attr ))
100
+ del OperationDebugWrapper .logging_wrapper
101
+
102
+
103
+ class OperationCollector (OperationDebugWrapper ):
104
+ def __init__ (self , collected_sql = None , * , collection = None , db = None ):
105
+ super ().__init__ (db , collection )
106
+ self .collected_sql = collected_sql
107
+
108
+ def log (self , op , args , kwargs = None ):
109
+ # If kwargs are used by any operations in the future, they must be
110
+ # added to this logging.
111
+ args = ", " .join (repr (arg ) for arg in args )
112
+ collection_name = f"{ self .collection .name } ." if self .collection is not None else ""
113
+ operation = f"db.{ collection_name } { op } ({ args } )"
114
+ self .collected_sql .append (operation )
115
+
116
+ def logging_wrapper (method ):
117
+ def wrapper (self , * args , ** kwargs ):
118
+ self .log (method , args , kwargs )
119
+
120
+ return wrapper
121
+
122
+
123
+ if hasattr (OperationCollector , "logging_wrapper" ):
124
+ for attr in OperationCollector .wrapped_methods :
125
+ setattr (OperationCollector , attr , OperationCollector .logging_wrapper (attr ))
126
+ del OperationCollector .logging_wrapper
0 commit comments