@@ -67,6 +67,7 @@ def __init__(self, connection, name):
6767 self .__outgoing_manipulators = []
6868 self .__outgoing_copying_manipulators = []
6969 self .add_son_manipulator (ObjectIdInjector ())
70+ self .__system_js = SystemJS (self )
7071
7172 def __check_name (self , name ):
7273 for invalid_char in [" " , "." , "$" , "/" , "\\ " ]:
@@ -99,6 +100,16 @@ def method_overwritten(instance, method):
99100 if method_overwritten (manipulator , "transform_outgoing" ):
100101 self .__outgoing_manipulators .insert (0 , manipulator )
101102
103+ @property
104+ def system_js (self ):
105+ """A :class:`SystemJS` helper for this :class:`Database`.
106+
107+ See the documentation for :class:`SystemJS` for more details.
108+
109+ .. versionadded:: 1.4+
110+ """
111+ return self .__system_js
112+
102113 @property
103114 def connection (self ):
104115 """The :class:`~pymongo.connection.Connection` instance for this
@@ -520,3 +531,51 @@ def __call__(self, *args, **kwargs):
520531 raise TypeError ("'Database' object is not callable. If you meant to "
521532 "call the '%s' method on a 'Collection' object it is "
522533 "failing because no such method exists." % self .__name )
534+
535+
536+ class SystemJS (object ):
537+ """Helper class for dealing with stored JavaScript.
538+ """
539+
540+ def __init__ (self , database ):
541+ """Get a system js helper for the database `database`.
542+
543+ An instance of :class:`SystemJS` is automatically created for
544+ each :class:`Database` instance as :attr:`Database.system_js`,
545+ manual instantiation of this class should not be necessary.
546+
547+ :class:`SystemJS` instances allow for easy manipulation and
548+ access to `server-side JavaScript`_:
549+
550+ .. doctest::
551+
552+ >>> db.system_js.add1 = "function (x) { return x + 1; }"
553+ >>> db.system.js.find({"_id": "add1"}).count()
554+ 1
555+ >>> db.system_js.add1(5)
556+ 6.0
557+ >>> del db.system_js.add1
558+ >>> db.system.js.find({"_id": "add1"}).count()
559+ 0
560+
561+ .. note:: Requires server version **>= 1.1.1**
562+
563+ .. versionadded:: 1.4+
564+
565+ .. _server-side JavaScript: http://www.mongodb.org/display/DOCS/Server-side+Code+Execution#Server-sideCodeExecution-Storingfunctionsserverside
566+ """
567+ # can't just assign it since we've overridden __setattr__
568+ object .__setattr__ (self , "_database" , database )
569+
570+ def __setattr__ (self , name , code ):
571+ self ._database .system .js .save ({"_id" : name , "value" : Code (code )},
572+ safe = True )
573+
574+ def __delattr__ (self , name ):
575+ self ._database .system .js .remove ({"_id" : name }, safe = True )
576+
577+ def __getattr__ (self , name ):
578+ return lambda * args : self ._database .eval ("function() { return %s."
579+ "apply(this, "
580+ "arguments); }" % name ,
581+ * args )
0 commit comments