Commits

Adam S committed f48ec3a

Turning DB.open into a Future. This breaks existing unit tests.

  • Participants
  • Parent commits e056253

Comments (0)

Files changed (8)

examples/simple.dart

 #import("dart:builtin");
 main(){
   Db db = new Db("mongo-dart-test");
+  /*
+  db.open(() { 
+    print('opening connection');
+  }).then((connOpened){
+  */
+  db.open().then((connOpened){
+    if (connOpened==true) {
+      print('connection open');
+      MCollection coll = db.collection("simple_data");
+      // Remove all existing data from collection;
+      coll.remove();
+      for (var n = 0; n<1000; n++){  
+        coll.insert({"my_field":n});
+      }
+      
+      coll.findOne({"my_field": 17}).then((val){
+        print("Filtered by value: $val");     
+      });
+      
+      coll.find({"my_field": {"\$gt": 985}}).each((v)=>print(v)).then((dummy){    
+        db.close();
+        
+      });
+    } else {
+      print('connection could not be opened');
+    }
+  });
+    
+ 
+ /* 
   //Db db = new Db("mongo-dart-test", new ServerConfig("127.0.0.1",27017));
-  db.open();
+  db.open(() {
   MCollection coll = db.collection("simple_data");
   // Remove all existing data from collection;
   coll.remove();
   
   coll.find({"my_field": {"\$gt": 985}}).each((v)=>print(v)).then((dummy){    
     db.close();
+    //trySecondOpen();
   });
-    
+  }).then((t) => print("db.open completed $t"));
+  */
+
 }

examples/simpleUpdate.dart

 #import("dart:builtin");
 main(){
   Db db = new Db('mongo-dart-test');
-  db.open();  
-  MCollection coll = db.collection('collection-for-save');
-  coll.remove();  
-  List toInsert = [
-                   {"name":"a", "value": 10},
-                   {"name":"b", "value": 20},
-                   {"name":"c", "value": 30},
-                   {"name":"d", "value": 40}
-                 ];
-  coll.insertAll(toInsert);
-  coll.findOne({"name":"c"}).chain((v1){
-    print("Record c: $v1");
-    v1["value"] = 31;    
-    coll.save(v1);
-    return coll.findOne({"name":"c"});
-  }).then((v2){
-    print("Record c after update: $v2");
-    db.close();
-  });    
+ 
+  simpleUpdate() {
+    MCollection coll = db.collection('collection-for-save');
+    coll.remove();  
+    List toInsert = [
+                     {"name":"a", "value": 10},
+                     {"name":"b", "value": 20},
+                     {"name":"c", "value": 30},
+                     {"name":"d", "value": 40}
+                   ];
+    coll.insertAll(toInsert);
+    coll.findOne({"name":"c"}).chain((v1){
+      print("Record c: $v1");
+      v1["value"] = 31;    
+      coll.save(v1);
+      return coll.findOne({"name":"c"});
+    }).then((v2){
+      print("Record c after update: $v2");
+      db.close();
+    });   
+  };
+  
+  db.open().then((c)=>simpleUpdate()); 
 }
       Future<MongoReplyMessage> reply = db.executeQueryMessage(qm);
       reply.then((replyMessage){
         state = OPEN;
+        //print("${replyMessage.cursorId}");
         cursorId = replyMessage.cursorId;
         items.addAll(replyMessage.documents);
         if (items.length > 0){
   executeMessage(MongoMessage message){
     connection.execute(message);
   }    
-  open(){
-    connection.connect();
-    return this;
+  Future <bool> open([Function onOpen]){
+    return connection.connect(onOpen);
+    //return this;
   }
   Future<Map> executeDbCommand(MongoMessage message){
       Completer<bool> result = new Completer();
+      //print("executeDbCommand.message = ${message}");
       connection.query(message).then((replyMessage){
-        if (replyMessage.documents[0]["ok"] == 1.0){
+        //print("replyMessage = ${replyMessage}");
+        //print("replyMessage.documents = ${replyMessage.documents}");
+        
+        String errMsg;
+        if (replyMessage.documents.length == 0) {
+          errMsg = "Error executing Db command, Document length 0";
+          print("Error: $errMsg");
+          var m = new Map();
+          m["errmsg"]=errMsg;
+          result.complete(m);
+        } else  if (replyMessage.documents[0]["ok"] == 1.0){
           result.complete(replyMessage.documents[0]);
         } else {
-          String errMsg = "Error executing Db command";
+          errMsg = "Error executing Db command";
           if (replyMessage.documents[0].containsKey("errmsg")){
             errMsg = replyMessage.documents[0]["errmsg"];
           }

lib/mcollection.dart

     cursor.close();
     return result;
   }
-  drop() => db.dropCollection(collectionName);
+  Future drop() => db.dropCollection(collectionName);
   remove([Map selector = const {}]) => db.removeFromCollection(collectionName, selector);
-  count([Map selector = const {}]){
+  Future count([Map selector = const {}]){
     Completer completer = new Completer();
     db.executeDbCommand(DbCommand.createCountCommand(db,collectionName,selector)).then((reply){       
+      //print("reply = ${reply}");
       completer.complete(reply["n"]);      
     });
     return completer.future;

lib/networking/connection.dart

       serverConfig = new ServerConfig();
     }    
   }
-  connect(){
+  Future<bool> connect([Function onOpen]){
     replyCompleters = new Map();
     sendQueue = new Queue();
     socket = new Socket(serverConfig.host, serverConfig.port);
-    if (socket == null) {
-      throw "can't get send socket";
+    Completer completer = new Completer();
+    if (socket is! Socket) {
+      completer.completeException(new Exception( "can't get send socket"));
+    } else {
+      lengthBuffer = new Binary(4);
+      socket.onError = (e) {  
+        print("connect exception ${e}");
+        completer.completeException(e);
+      };
+      socket.onConnect = () { 
+        if (onOpen is Function) {
+          onOpen();
+        }
+        
+        completer.complete(true);
+      };
+      return completer.future;
     }
-    lengthBuffer = new Binary(4);
+    
   }
   close(){
     while (!sendQueue.isEmpty()){
       if(!sendQueue.isEmpty()){
         MongoMessage message = sendQueue.removeFirst();
         debug(message.toString());
+        //print(message.toString());
         bufferToSend = message.serialize();
       } else {
         bufferToSend = null;  
       bufferToSend.offset += socket.writeList(bufferToSend.bytes,
         bufferToSend.offset,bufferToSend.bytes.length-bufferToSend.offset);
       if (!bufferToSend.atEnd()){
-//        print("Buffer not send fully, offset: ${bufferToSend.offset}");
+       print("Buffer not send fully, offset: ${bufferToSend.offset}");
       }
       new Timer(0,(t)=>sendBufferFromTimer());              
     }        
     else {
+      //print("setting onwrite to null");
       socket.onWrite = null;        
     }    
   }  
       messageBuffer.writeInt(messageLength);
     }
     messageBuffer.offset += socket.readList(messageBuffer.bytes,messageBuffer.offset,messageBuffer.bytes.length-messageBuffer.offset);
+    //print("messageBuffer = ${messageBuffer}");
     if (messageBuffer.atEnd()){
       MongoReplyMessage reply = new MongoReplyMessage();
       messageBuffer.rewind();
+      //print("messageBuffer = ${messageBuffer.bytes}");
       reply.deserialize(messageBuffer);
       debug(reply.toString());
+      //print(reply.toString());
+      //print("messageBuffer = ${messageBuffer}");
       messageBuffer = null;
       lengthBuffer.rewind();
       Completer completer = replyCompleters.remove(reply.responseTo);      
-      if (completer !== null){        
+      if (completer !== null){
+        //print("messageBuffer = ${messageBuffer}");
         completer.complete(reply);       
       }
       else {

lib/networking/dbcommand.dart

   static DbCommand createCountCommand(Db db, String collectionName, [Map selector = const {}]) {
     var finalQuery = new Map();
 //    finalQuery["count"] = "${db.databaseName}.$collectionName";
-    finalQuery["count"] = collectionName;    
+    finalQuery["count"] = collectionName; 
+    finalQuery["fields"] = {}; 
     finalQuery["query"] = selector;
-    finalQuery["fields"] = null;                      
+                         
 
     return new DbCommand(db, SYSTEM_COMMAND_COLLECTION, MongoQueryMessage.OPTS_NO_CURSOR_TIMEOUT, 0, -1, finalQuery, null);
   }
-logger() => Utils.getLogger();
+logger() { 
+  Utils.setVerboseState(); 
+  Utils.getLogger();
+  
+}
 setVerboseState(){
   Utils.setVerboseState();  
 }