summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorAraq <rumpf_a@web.de>2012-04-09 11:18:10 +0200
committerAraq <rumpf_a@web.de>2012-04-09 11:18:10 +0200
commitc53ad1b39fdd977b03b9cc2560b351ad6df4bfdd (patch)
tree064a972f7ee71f19302ecf509756076441d3d442 /lib
parente9260e6c4d332d3f3f27997d0985a3881745cc56 (diff)
downloadNim-c53ad1b39fdd977b03b9cc2560b351ad6df4bfdd.tar.gz
documentation improvements; higher level Mongodb wrapper
Diffstat (limited to 'lib')
-rw-r--r--lib/impure/db_mongo.nim213
-rwxr-xr-xlib/pure/json.nim47
-rwxr-xr-xlib/pure/os.nim2
-rwxr-xr-xlib/pure/pegs.nim4
-rw-r--r--lib/wrappers/mongo.nim598
5 files changed, 563 insertions, 301 deletions
diff --git a/lib/impure/db_mongo.nim b/lib/impure/db_mongo.nim
new file mode 100644
index 000000000..a2aebb6da
--- /dev/null
+++ b/lib/impure/db_mongo.nim
@@ -0,0 +1,213 @@
+#
+#
+#            Nimrod's Runtime Library
+#        (c) Copyright 2012 Andreas Rumpf
+#
+#    See the file "copying.txt", included in this
+#    distribution, for details about the copyright.
+#
+
+## This module implements a higher level wrapper for `mongodb`:idx:. Example:
+##
+## .. code-block:: nimrod
+##
+##    import mongo, db_mongo, oids, json
+##
+##    var conn = db_mongo.open()
+##
+##    # construct JSON data:
+##    var data = %{"a": %13, "b": %"my string value", 
+##                 "inner": %{"i": %71} }
+##
+##    var id = insertID(conn, "test.test", data)
+##
+##    for v in find(conn, "test.test", "this.a == 13"):
+##      print v
+##
+##    delete(conn, "test.test", id)
+##    close(conn)
+
+import mongo, oids, json
+
+type
+  EDb* = object of EIO ## exception that is raised if a database error occurs
+  TDbConn* = TMongo    ## a database connection; alias for ``TMongo``
+
+proc dbError*(db: TDbConn, msg: string) {.noreturn.} = 
+  ## raises an EDb exception with message `msg`.
+  var e: ref EDb
+  new(e)
+  if db.errstr[0] != '\0':
+    e.msg = $db.errstr
+  else:
+    e.msg = $db.err & " " & msg
+  raise e
+
+proc Close*(db: var TDbConn) = 
+  ## closes the database connection.
+  disconnect(db)
+  destroy(db)
+
+proc Open*(host: string = defaultHost, port: int = defaultPort): TDbConn =
+  ## opens a database connection. Raises `EDb` if the connection could not
+  ## be established.
+  init(result)
+  
+  let x = connect(result, host, port.cint)
+  if x != 0'i32:
+    dbError(result, "cannot open: " & host)
+
+proc jsonToBSon(b: var TBSon, key: string, j: PJsonNode) =
+  case j.kind
+  of JString:
+    add(b, key, j.str)
+  of JInt:
+    add(b, key, j.num)
+  of JFloat:
+    add(b, key, j.fnum)
+  of JBool:
+    addBool(b, key, ord(j.bval))
+  of JNull:
+    addNull(b, key)
+  of JObject:
+    addStartObject(b, key)
+    for k, v in items(j.fields):
+      jsonToBSon(b, k, v)
+    addFinishObject(b)
+  of JArray:
+    addStartArray(b, key)
+    for i, e in pairs(j.elems):
+      jsonToBSon(b, $i, e)
+    addFinishArray(b)
+
+proc jsonToBSon*(j: PJsonNode, oid: TOid): TBSon =
+  ## converts a JSON value into the BSON format. The result must be
+  ## ``destroyed`` explicitely!
+  init(result)
+  assert j.kind == JObject
+  add(result, "_id", oid)
+  for key, val in items(j.fields):
+    jsonToBSon(result, key, val)
+  finish(result)
+
+proc `[]`*(obj: var TBSon, fieldname: cstring): TBSon =
+  ## retrieves the value belonging to `fieldname`. Raises `EInvalidKey` if
+  ## the attribute does not exist.
+  var it = initIter(obj)
+  let res = find(it, result, fieldname)
+  if res == bkEOO:
+    raise newException(EInvalidIndex, "key not in object")
+
+proc getId*(obj: var TBSon): TOid =
+  ## retrieves the ``_id`` attribute of `obj`.
+  var it = initIter(obj)
+  var b: TBSon
+  let res = find(it, b, "_id")
+  if res == bkOID:
+    result = oidVal(it)[]
+  else:
+    raise newException(EInvalidIndex, "_id not in object")
+
+proc insertID*(db: var TDbConn, namespace: string, data: PJsonNode): TOid =
+  ## converts `data` to BSON format and inserts it in `namespace`. Returns
+  ## the generated OID for the ``_id`` field.
+  result = genOid()
+  var x = jsonToBSon(data, result)
+  insert(db, namespace, x)
+  destroy(x)
+
+proc insert*(db: var TDbConn, namespace: string, data: PJsonNode) =
+  ## converts `data` to BSON format and inserts it in `namespace`.  
+  discard InsertID(db, namespace, data)
+
+proc update*(db: var TDbConn, namespace: string, obj: var TBSon) =
+  ## updates `obj` in `namespace`.
+  var cond: TBson
+  init(cond)
+  cond.add("_id", getId(obj))
+  finish(cond)
+  update(db, namespace, cond, obj, ord(UPDATE_UPSERT))
+  destroy(cond)
+
+proc update*(db: var TDbConn, namespace: string, oid: TOid, obj: PJsonNode) =
+  ## updates the data with `oid` to have the new data `obj`.
+  var a = jsonToBSon(obj, oid)
+  Update(db, namespace, a)
+  destroy(a)
+
+proc delete*(db: var TDbConn, namespace: string, oid: TOid) =
+  ## Deletes the object belonging to `oid`.
+  var cond: TBson
+  init(cond)
+  cond.add("_id", oid)
+  finish(cond)
+  discard remove(db, namespace, cond)
+  destroy(cond)
+
+proc delete*(db: var TDbConn, namespace: string, obj: var TBSon) =
+  ## Deletes the object `obj`.
+  delete(db, namespace, getId(obj))
+
+iterator find*(db: var TDbConn, namespace: string): var TBSon =
+  ## iterates over any object in `namespace`.
+  var cursor: TCursor
+  init(cursor, db, namespace)
+  while next(cursor) == mongo.OK:
+    yield bson(cursor)[]
+  destroy(cursor)
+
+iterator find*(db: var TDbConn, namespace: string, 
+               query, fields: var TBSon): var TBSon =
+  ## yields the `fields` of any document that suffices `query`.
+  var cursor = find(db, namespace, query, fields, 0'i32, 0'i32, 0'i32)
+  if cursor != nil:
+    while next(cursor[]) == mongo.OK:
+      yield bson(cursor[])[]
+    destroy(cursor[])
+
+proc setupFieldnames(fields: openArray[string]): TBSon =
+  init(result)
+  for x in fields: add(result, x, 1'i32)
+  finish(result)
+
+iterator find*(db: var TDbConn, namespace: string, 
+               query: var TBSon, fields: openArray[string]): var TBSon =
+  ## yields the `fields` of any document that suffices `query`. If `fields` 
+  ## is ``[]`` the whole document is yielded.
+  var f = setupFieldnames(fields)
+  var cursor = find(db, namespace, query, f, 0'i32, 0'i32, 0'i32)
+  if cursor != nil:
+    while next(cursor[]) == mongo.OK:
+      yield bson(cursor[])[]
+    destroy(cursor[])
+  destroy(f)
+
+proc setupQuery(query: string): TBSon =
+  init(result)
+  add(result, "$where", query)
+  finish(result)
+
+iterator find*(db: var TDbConn, namespace: string, 
+               query: string, fields: openArray[string]): var TBSon =
+  ## yields the `fields` of any document that suffices `query`. If `fields` 
+  ## is ``[]`` the whole document is yielded.
+  var f = setupFieldnames(fields)
+  var q = setupQuery(query)
+  var cursor = find(db, namespace, q, f, 0'i32, 0'i32, 0'i32)
+  if cursor != nil:
+    while next(cursor[]) == mongo.OK:
+      yield bson(cursor[])[]
+    destroy(cursor[])
+  destroy(q)
+  destroy(f)
+
+when false:
+  # this doesn't work this way; would require low level hacking
+  iterator fieldPairs*(obj: var TBSon): tuple[key: cstring, value: TBSon] =
+    ## iterates over `obj` and yields all (key, value)-Pairs.
+    var it = initIter(obj)
+    var v: TBSon
+    while next(it) != bkEOO:
+      let key = key(it)
+      discard init(v, value(it))
+      yield (key, v)
diff --git a/lib/pure/json.nim b/lib/pure/json.nim
index 07e447aab..941d88dfc 100755
--- a/lib/pure/json.nim
+++ b/lib/pure/json.nim
@@ -495,16 +495,16 @@ type
     JArray
     
   PJsonNode* = ref TJsonNode ## JSON node 
-  TJsonNode* {.final, pure.} = object
+  TJsonNode* {.final, pure, acyclic.} = object
     case kind*: TJsonNodeKind
     of JString:
-      str*: String
+      str*: string
     of JInt:
       num*: biggestInt
     of JFloat:
-      fnum: Float
+      fnum*: float
     of JBool:
-      bval*: Bool
+      bval*: bool
     of JNull:
       nil
     of JObject:
@@ -558,6 +558,45 @@ proc newJArray*(): PJsonNode =
   result.kind = JArray
   result.elems = @[]
 
+
+proc `%`*(s: string): PJsonNode =
+  ## Generic constructor for JSON data. Creates a new `JString PJsonNode`.
+  new(result)
+  result.kind = JString
+  result.str = s
+
+proc `%`*(n: biggestInt): PJsonNode =
+  ## Generic constructor for JSON data. Creates a new `JInt PJsonNode`.
+  new(result)
+  result.kind = JInt
+  result.num  = n
+
+proc `%`*(n: float): PJsonNode =
+  ## Generic constructor for JSON data. Creates a new `JFloat PJsonNode`.
+  new(result)
+  result.kind = JFloat
+  result.fnum  = n
+
+proc `%`*(b: bool): PJsonNode =
+  ## Generic constructor for JSON data. Creates a new `JBool PJsonNode`.
+  new(result)
+  result.kind = JBool
+  result.bval = b
+
+proc `%`*(keyVals: openArray[tuple[key: string, val: PJsonNode]]): PJsonNode =
+  ## Generic constructor for JSON data. Creates a new `JObject PJsonNode`
+  new(result)
+  result.kind = JObject
+  newSeq(result.fields, keyVals.len)
+  for i, p in pairs(keyVals): result.fields[i] = p
+
+proc `%`*(elements: openArray[PJSonNode]): PJsonNode =
+  ## Generic constructor for JSON data. Creates a new `JArray PJsonNode`
+  new(result)
+  result.kind = JArray
+  newSeq(result.elems, elements.len)
+  for i, p in pairs(elements): result.elems[i] = p
+
 proc len*(n: PJsonNode): int = 
   ## If `n` is a `JArray`, it returns the number of elements.
   ## If `n` is a `JObject`, it returns the number of pairs.
diff --git a/lib/pure/os.nim b/lib/pure/os.nim
index e4835faea..570bf3e8a 100755
--- a/lib/pure/os.nim
+++ b/lib/pure/os.nim
@@ -1355,6 +1355,7 @@ when defined(macosx):
 
 proc getAppFilename*(): string {.rtl, extern: "nos$1".} =
   ## Returns the filename of the application's executable.
+  ## **Note**: This does not work reliably on BSD.
 
   # Linux: /proc/<pid>/exe
   # Solaris:
@@ -1410,6 +1411,7 @@ proc getApplicationDir*(): string {.rtl, extern: "nos$1", deprecated.} =
 
 proc getAppDir*(): string {.rtl, extern: "nos$1".} =
   ## Returns the directory of the application's executable.
+  ## **Note**: This does not work reliably on BSD.
   result = splitFile(getAppFilename()).dir
 
 proc sleep*(milsecs: int) {.rtl, extern: "nos$1".} =
diff --git a/lib/pure/pegs.nim b/lib/pure/pegs.nim
index e2f69e369..b5c72491c 100755
--- a/lib/pure/pegs.nim
+++ b/lib/pure/pegs.nim
@@ -1486,10 +1486,10 @@ proc primary(p: var TPegParser): TPeg =
     return !primary(p)
   of tkAt:
     getTok(p)
-    return @primary(p)
+    return @(primary(p))
   of tkCurlyAt:
     getTok(p)
-    return @@primary(p).token(p)
+    return @@(primary(p).token(p))
   else: nil
   case p.tok.kind
   of tkIdentifier:
diff --git a/lib/wrappers/mongo.nim b/lib/wrappers/mongo.nim
index 8dacfec5e..6673e8ddf 100644
--- a/lib/wrappers/mongo.nim
+++ b/lib/wrappers/mongo.nim
@@ -32,11 +32,17 @@ import oids, times
 {.deadCodeElim: on.}
 
 when defined(windows):
-  const mongodll* = "mongo.dll"
+  const
+    mongodll* = "mongoc.dll"
+    bsondll* = "bson.dll"
 elif defined(macosx):
-  const mongodll* = "libmongo.dylib"
+  const 
+    mongodll* = "libmongoc.dylib"
+    bsondll* = "libbson.dylib"
 else:
-  const mongodll* = "libmongo.so"
+  const 
+    mongodll* = "libmongoc.so"
+    bsondll* = "libbson.so"
 
 #
 #  This package supports both compile-time and run-time determination of CPU
@@ -60,6 +66,8 @@ const
   OK* = 0
   ERROR* = - 1
   SIZE_OVERFLOW* = 1
+  defaultHost* = "127.0.0.1"
+  defaultPort* = 27017
 
 type 
   TValidity* = enum ## validity
@@ -68,7 +76,7 @@ type
     FIELD_HAS_DOT = (1 shl 2),  ## Warning: key contains '.' character. 
     FIELD_INIT_DOLLAR = (1 shl 3),  ## Warning: key starts with '$' character. 
     ALREADY_FINISHED = (1 shl 4) ## Trying to modify a finished BSON object. 
-  TbinarySubtype* = enum 
+  TBinarySubtype* = enum 
     BIN_BINARY = 0, BIN_FUNC = 1, BIN_BINARY_OLD = 2, BIN_UUID = 3, BIN_MD5 = 5, 
     BIN_USER = 128
   TBsonKind* {.size: sizeof(cint).} = enum 
@@ -96,7 +104,7 @@ type
     cur*: cstring
     first*: TBsonBool
 
-  Tbson* {.pure, final.} = object 
+  TBson* {.pure, final.} = object 
     data*: cstring
     cur*: cstring
     dataSize*: cint
@@ -116,390 +124,391 @@ type
     i*: cint                  # increment 
     t*: cint                  # time in seconds 
 
-proc create*(): ptr Tbson{.stdcall, importc: "bson_create", dynlib: mongodll.}
-proc dispose*(b: ptr Tbson){.stdcall, importc: "bson_dispose", dynlib: mongodll.}
+proc create*(): ptr TBson{.stdcall, importc: "bson_create", dynlib: bsondll.}
+proc dispose*(b: ptr TBson){.stdcall, importc: "bson_dispose", dynlib: bsondll.}
 
-proc size*(b: ptr Tbson): cint {.stdcall, importc: "bson_size", dynlib: mongodll.}
+proc size*(b: var TBson): cint {.stdcall, importc: "bson_size", dynlib: bsondll.}
   ## Size of a BSON object.
 
-proc bufferSize*(b: ptr Tbson): cint{.stdcall, importc: "bson_buffer_size", 
-                                       dynlib: mongodll.}
+proc bufferSize*(b: var TBson): cint{.stdcall, importc: "bson_buffer_size", 
+                                      dynlib: bsondll.}
   ## Buffer size of a BSON object.
 
-proc print*(b: ptr Tbson){.stdcall, importc: "bson_print", dynlib: mongodll.}
+proc print*(b: var TBson){.stdcall, importc: "bson_print", dynlib: bsondll.}
   ## Print a string representation of a BSON object.
 
-proc data*(b: ptr Tbson): cstring{.stdcall, importc: "bson_data", 
-                                   dynlib: mongodll.}
-  ## Return a pointer to the raw buffer stored by this bson object.
+proc print*(TBson: cstring, depth: cint) {.stdcall, 
+    importc: "bson_print_raw", dynlib: bsondll.}
+  ## Print a string representation of a BSON object up to `depth`.
 
-proc printRaw*(Tbson: cstring, depth: cint) {.stdcall, 
-    importc: "bson_print_raw", dynlib: mongodll.}
-  ## Print a string representation of a BSON object.
+proc data*(b: var TBson): cstring{.stdcall, importc: "bson_data", 
+                                   dynlib: bsondll.}
+  ## Return a pointer to the raw buffer stored by this bson object.
 
-proc find*(it: var TIter, obj: ptr Tbson, name: cstring): TBsonKind {.stdcall, 
-    importc: "bson_find", dynlib: mongodll.}
+proc find*(it: var TIter, obj: var TBson, name: cstring): TBsonKind {.stdcall, 
+    importc: "bson_find", dynlib: bsondll.}
   ## Advance `it` to the named field. `obj` is the BSON object to use.
   ## `name` is the name of the field to find. Returns the type of the found
   ## object or ``bkEOO`` if it is not found.
   
 proc createIter*(): ptr TIter{.stdcall, importc: "bson_iterator_create", 
-                               dynlib: mongodll.}
+                               dynlib: bsondll.}
 proc dispose*(a2: ptr TIter){.stdcall, importc: "bson_iterator_dispose", 
-                              dynlib: mongodll.}
+                              dynlib: bsondll.}
 
-proc initIter*(b: ptr TBson): TIter =
+proc initIter*(b: var TBson): TIter =
   ## Initialize a bson iterator from the value `b`.
-  proc iterator_init(i: var TIter, b: ptr Tbson){.stdcall, 
-      importc: "bson_iterator_init", dynlib: mongodll.}
+  proc iterator_init(i: var TIter, b: var TBson){.stdcall, 
+      importc: "bson_iterator_init", dynlib: bsondll.}
 
   iterator_init(result, b)
-   
+
 proc fromBuffer*(i: var TIter, buffer: cstring) {.stdcall, 
-    importc: "bson_iterator_from_buffer", dynlib: mongodll.}
-  ## Initialize a bson iterator from a const char* buffer. Note
+    importc: "bson_iterator_from_buffer", dynlib: bsondll.}
+  ## Initialize a bson iterator from a cstring buffer. Note
   ## that this is mostly used internally.
 
 proc more*(i: var TIter): bool = 
   ## Check to see if the bson_iterator has more data.
   proc iterator_more(i: var TIter): TBsonBool{.stdcall, 
-      importc: "bson_iterator_more", dynlib: mongodll.}
+      importc: "bson_iterator_more", dynlib: bsondll.}
   result = iterator_more(i) != 0'i32
   
 proc next*(i: var TIter): TBsonKind {.stdcall, 
-    importc: "bson_iterator_next", dynlib: mongodll.}
+    importc: "bson_iterator_next", dynlib: bsondll.}
   ## Point the iterator at the next BSON object.
 
 proc kind*(i: var TIter): TBsonKind{.stdcall, 
-    importc: "bson_iterator_type", dynlib: mongodll.}
+    importc: "bson_iterator_type", dynlib: bsondll.}
   ## Get the type of the BSON object currently pointed to by the iterator.
 
 proc key*(i: var TIter): cstring{.stdcall, 
-    importc: "bson_iterator_key", dynlib: mongodll.}
+    importc: "bson_iterator_key", dynlib: bsondll.}
   ##  Get the key of the BSON object currently pointed to by the iterator.
   
-proc value*(i: ptr TIter): cstring{.stdcall, 
-    importc: "bson_iterator_value", dynlib: mongodll.}
+proc value*(i: var TIter): cstring{.stdcall, 
+    importc: "bson_iterator_value", dynlib: bsondll.}
   ## Get the value of the BSON object currently pointed to by the iterator.
   
 proc floatVal*(i: var TIter): float {.stdcall, 
-    importc: "bson_iterator_double", dynlib: mongodll.}
+    importc: "bson_iterator_double", dynlib: bsondll.}
   ## Get the double value of the BSON object currently pointed to by the
   ## iterator.
 
-proc intVal*(i: ptr TIter): cint{.stdcall, importc: "bson_iterator_int", 
-                                  dynlib: mongodll.}
+proc intVal*(i: var TIter): cint{.stdcall, importc: "bson_iterator_int", 
+                                  dynlib: bsondll.}
   ## Get the int value of the BSON object currently pointed to by the iterator.
 
 proc int64Val*(i: var TIter): int64{.stdcall, 
-    importc: "bson_iterator_long", dynlib: mongodll.}
+    importc: "bson_iterator_long", dynlib: bsondll.}
   ## Get the long value of the BSON object currently pointed to by the iterator.
 
 proc timestamp*(i: var TIter): Ttimestamp {.stdcall, 
-    importc: "bson_iterator_timestamp", dynlib: mongodll.}
+    importc: "bson_iterator_timestamp", dynlib: bsondll.}
   # return the bson timestamp as a whole or in parts 
 
 proc timestampTime*(i: var TIter): cint {.stdcall, 
-    importc: "bson_iterator_timestamp_time", dynlib: mongodll.}
+    importc: "bson_iterator_timestamp_time", dynlib: bsondll.}
   # return the bson timestamp as a whole or in parts 
-proc timestampIncrement*(i: ptr TIter): cint{.stdcall, 
-    importc: "bson_iterator_timestamp_increment", dynlib: mongodll.}
+proc timestampIncrement*(i: var TIter): cint{.stdcall, 
+    importc: "bson_iterator_timestamp_increment", dynlib: bsondll.}
   # return the bson timestamp as a whole or in parts 
 
 proc boolVal*(i: var TIter): TBsonBool{.stdcall, 
-    importc: "bson_iterator_bool", dynlib: mongodll.}
+    importc: "bson_iterator_bool", dynlib: bsondll.}
   ## Get the boolean value of the BSON object currently pointed to by
   ## the iterator.
   ##
   ## | false: boolean false, 0 in any type, or null 
   ## | true: anything else (even empty strings and objects) 
 
-proc floatRaw*(i: ptr TIter): cdouble{.stdcall, 
-    importc: "bson_iterator_double_raw", dynlib: mongodll.}
+proc floatRaw*(i: var TIter): cdouble{.stdcall, 
+    importc: "bson_iterator_double_raw", dynlib: bsondll.}
   ## Get the double value of the BSON object currently pointed to by the
   ## iterator. Assumes the correct type is used.
       
 proc intRaw*(i: var TIter): cint{.stdcall, 
-    importc: "bson_iterator_int_raw", dynlib: mongodll.}
+    importc: "bson_iterator_int_raw", dynlib: bsondll.}
   ## Get the int value of the BSON object currently pointed to by the
   ## iterator. Assumes the correct type is used.
     
-proc int64Raw*(i: ptr TIter): int64{.stdcall, 
-    importc: "bson_iterator_long_raw", dynlib: mongodll.}
+proc int64Raw*(i: var TIter): int64{.stdcall, 
+    importc: "bson_iterator_long_raw", dynlib: bsondll.}
   ## Get the long value of the BSON object currently pointed to by the
   ## iterator. Assumes the correct type is used.
 
-proc boolRaw*(i: ptr TIter): TBsonBool{.stdcall, 
-    importc: "bson_iterator_bool_raw", dynlib: mongodll.}
+proc boolRaw*(i: var TIter): TBsonBool{.stdcall, 
+    importc: "bson_iterator_bool_raw", dynlib: bsondll.}
   ## Get the bson_bool_t value of the BSON object currently pointed to by the
   ## iterator. Assumes the correct type is used.
 
 proc oidVal*(i: var TIter): ptr TOid {.stdcall, 
-    importc: "bson_iterator_oid", dynlib: mongodll.}
+    importc: "bson_iterator_oid", dynlib: bsondll.}
   ## Get the bson_oid_t value of the BSON object currently pointed to by the
   ## iterator.
 
 proc strVal*(i: var TIter): cstring {.stdcall, 
-    importc: "bson_iterator_string", dynlib: mongodll.}
+    importc: "bson_iterator_string", dynlib: bsondll.}
   ## Get the string value of the BSON object currently pointed to by the
   ## iterator.
 
 proc strLen*(i: var TIter): cint {.stdcall, 
-    importc: "bson_iterator_string_len", dynlib: mongodll.}
+    importc: "bson_iterator_string_len", dynlib: bsondll.}
   ## Get the string length of the BSON object currently pointed to by the
   ## iterator.
 
 proc code*(i: var TIter): cstring {.stdcall, 
-    importc: "bson_iterator_code", dynlib: mongodll.}
+    importc: "bson_iterator_code", dynlib: bsondll.}
   ## Get the code value of the BSON object currently pointed to by the
   ## iterator. Works with bson_code, bson_codewscope, and BSON_STRING
   ## returns ``nil`` for everything else.
     
-proc codeScope*(i: var TIter, scope: ptr Tbson) {.stdcall, 
-    importc: "bson_iterator_code_scope", dynlib: mongodll.}
+proc codeScope*(i: var TIter, scope: var TBson) {.stdcall, 
+    importc: "bson_iterator_code_scope", dynlib: bsondll.}
   ## Calls bson_empty on scope if not a bson_codewscope
   
 proc date*(i: var TIter): Tdate {.stdcall, 
-    importc: "bson_iterator_date", dynlib: mongodll.}
+    importc: "bson_iterator_date", dynlib: bsondll.}
   ## Get the date value of the BSON object currently pointed to by the
   ## iterator.
 
 proc time*(i: var TIter): TTime {.stdcall, 
-    importc: "bson_iterator_time_t", dynlib: mongodll.}
+    importc: "bson_iterator_time_t", dynlib: bsondll.}
   ## Get the time value of the BSON object currently pointed to by the
   ## iterator.
 
 proc binLen*(i: var TIter): cint {.stdcall, 
-    importc: "bson_iterator_bin_len", dynlib: mongodll.}
+    importc: "bson_iterator_bin_len", dynlib: bsondll.}
   ## Get the length of the BSON binary object currently pointed to by the
   ## iterator.
 
 proc binType*(i: var TIter): char {.stdcall, 
-    importc: "bson_iterator_bin_type", dynlib: mongodll.}
+    importc: "bson_iterator_bin_type", dynlib: bsondll.}
   ## Get the type of the BSON binary object currently pointed to by the
   ## iterator.
 
 proc binData*(i: var TIter): cstring {.stdcall, 
-    importc: "bson_iterator_bin_data", dynlib: mongodll.}
+    importc: "bson_iterator_bin_data", dynlib: bsondll.}
   ## Get the value of the BSON binary object currently pointed to by the
   ## iterator.
 
 proc regex*(i: var TIter): cstring {.stdcall, 
-    importc: "bson_iterator_regex", dynlib: mongodll.}
+    importc: "bson_iterator_regex", dynlib: bsondll.}
   ## Get the value of the BSON regex object currently pointed to by the
   ## iterator.
 
 proc regexOpts*(i: var TIter): cstring {.stdcall, 
-    importc: "bson_iterator_regex_opts", dynlib: mongodll.}
+    importc: "bson_iterator_regex_opts", dynlib: bsondll.}
   ## Get the options of the BSON regex object currently pointed to by the
   ## iterator.
 
-proc subobject*(i: var TIter, sub: ptr Tbson) {.stdcall, 
-    importc: "bson_iterator_subobject", dynlib: mongodll.}
+proc subobject*(i: var TIter, sub: var TBson) {.stdcall, 
+    importc: "bson_iterator_subobject", dynlib: bsondll.}
   ## Get the BSON subobject currently pointed to by the
   ## iterator.
 
-proc subiterator*(i: var TIter, sub: ptr TIter) {.stdcall, 
-    importc: "bson_iterator_subiterator", dynlib: mongodll.}
+proc subiterator*(i: var TIter, sub: var TIter) {.stdcall, 
+    importc: "bson_iterator_subiterator", dynlib: bsondll.}
   ## Get a bson_iterator that on the BSON subobject.
 
 
 # ----------------------------
 #   BUILDING
-#   ------------------------------ 
-#*
+# ----------------------------
 
-proc init*(b: ptr Tbson) {.stdcall, importc: "bson_init", dynlib: mongodll.}
+proc init*(b: var TBson) {.stdcall, importc: "bson_init", dynlib: bsondll.}
   ## Initialize a new bson object. If not created
   ## with bson_new, you must initialize each new bson
   ## object using this function.
   ##
   ## When finished, you must pass the bson object to bson_destroy().
 
-proc init*(b: ptr Tbson, data: cstring): cint {.stdcall, 
-    importc: "bson_init_data", dynlib: mongodll.}
+proc init*(b: var TBson, data: cstring): cint {.stdcall, 
+    importc: "bson_init_data", dynlib: bsondll.}
   ## Initialize a BSON object, and point its data
   ## pointer to the provided `data`.
   ## Returns OK or ERROR.
 
-proc initFinished*(b: ptr Tbson, data: cstring): cint {.stdcall, 
-    importc: "bson_init_finished_data", dynlib: mongodll.}
+proc initFinished*(b: var TBson, data: cstring): cint {.stdcall, 
+    importc: "bson_init_finished_data", dynlib: bsondll.}
 
-proc initSize*(b: ptr Tbson, size: cint) {.stdcall, importc: "bson_init_size", 
-    dynlib: mongodll.}
+proc initSize*(b: var TBson, size: cint) {.stdcall, importc: "bson_init_size", 
+    dynlib: bsondll.}
   ## Initialize a BSON object, and set its buffer to the given size.
-  ## Returns BSON_OK or BSON_ERROR.
+  ## Returns OK or ERROR.
 
-proc ensureSpace*(b: ptr Tbson, bytesNeeded: cint): cint {.stdcall, 
-    importc: "bson_ensure_space", dynlib: mongodll.}
+proc ensureSpace*(b: var TBson, bytesNeeded: cint): cint {.stdcall, 
+    importc: "bson_ensure_space", dynlib: bsondll.}
   ## Grow a bson object. `bytesNeeded` is the additional number of bytes needed.
 
-proc finish*(b: ptr Tbson): cint{.stdcall, importc: "bson_finish", 
-                                  dynlib: mongodll.}
+proc finish*(b: var TBson): cint{.stdcall, importc: "bson_finish", 
+                                  dynlib: bsondll, discardable.}
   ## Finalize a bson object. Returns the standard error code.
   ## To deallocate memory, call destroy on the bson object.
 
-proc destroy*(b: ptr Tbson){.stdcall, importc: "bson_destroy", dynlib: mongodll.}
+proc destroy*(b: var TBson){.stdcall, importc: "bson_destroy", dynlib: bsondll.}
   ## Destroy a bson object.
 
-proc empty*(obj: ptr Tbson): ptr Tbson {.stdcall, importc: "bson_empty", 
-                                         dynlib: mongodll.}
-  ## Returns a pointer to a static empty BSON object.
+proc empty*(obj: var TBson) {.stdcall, importc: "bson_empty", 
+                              dynlib: bsondll.}
+  ## Sets a pointer to a static empty BSON object.
   ## `obj` is the BSON object to initialize. 
 
-proc copy*(outp, inp: ptr Tbson): cint{.stdcall, importc: "bson_copy", 
-    dynlib: mongodll.}
+proc copy*(outp, inp: var TBson): cint{.stdcall, importc: "bson_copy", 
+    dynlib: bsondll.}
   ## Make a complete copy of the a BSON object.
   ## The source bson object must be in a finished
   ## state; otherwise, the copy will fail.
 
-proc add*(b: ptr Tbson, name: cstring, oid: TOid) =
+proc add*(b: var TBson, name: cstring, oid: TOid) =
   ## adds an OID to `b`.
-  proc appendOid(b: ptr Tbson, name: cstring, oid: ptr Toid): cint {.stdcall, 
-      importc: "bson_append_oid", dynlib: mongodll.}
+  proc appendOid(b: var TBson, name: cstring, oid: ptr TOid): cint {.stdcall, 
+      importc: "bson_append_oid", dynlib: bsondll.}
   
   var oid = oid
   discard appendOid(b, name, addr(oid))
 
-proc add*(b: ptr Tbson, name: cstring, i: cint): cint{.stdcall, 
-    importc: "bson_append_int", dynlib: mongodll, discardable.}
+proc add*(b: var TBson, name: cstring, i: cint): cint{.stdcall, 
+    importc: "bson_append_int", dynlib: bsondll, discardable.}
   ## Append an int to a bson.
 
-proc add*(b: ptr Tbson, name: cstring, i: int64): cint{.stdcall, 
-    importc: "bson_append_long", dynlib: mongodll, discardable.}
+proc add*(b: var TBson, name: cstring, i: int64): cint{.stdcall, 
+    importc: "bson_append_long", dynlib: bsondll, discardable.}
   ## Append an long to a bson.
 
-proc add*(b: ptr Tbson, name: cstring, d: float): cint{.stdcall, 
-    importc: "bson_append_double", dynlib: mongodll, discardable.}
+proc add*(b: var TBson, name: cstring, d: float): cint{.stdcall, 
+    importc: "bson_append_double", dynlib: bsondll, discardable.}
   ## Append an double to a bson.
 
-proc add*(b: ptr Tbson, name: cstring, str: cstring): cint {.stdcall, 
-    importc: "bson_append_string", dynlib: mongodll, discardable.}
+proc add*(b: var TBson, name: cstring, str: cstring): cint {.stdcall, 
+    importc: "bson_append_string", dynlib: bsondll, discardable.}
   ## Append a string to a bson.
 
-proc add*(b: ptr Tbson, name: cstring, str: cstring, len: cint): cint{.
-    stdcall, importc: "bson_append_string_n", dynlib: mongodll, discardable.}
+proc add*(b: var TBson, name: cstring, str: cstring, len: cint): cint{.
+    stdcall, importc: "bson_append_string_n", dynlib: bsondll, discardable.}
   ## Append len bytes of a string to a bson.
 
-proc add*(b: ptr Tbson, name: cstring, str: string) =
-  discard add(b, name, name.len.cint)
+proc add*(b: var TBson, name: cstring, str: string) =
+  ## Append a Nimrod string `str` to a bson.
+  discard add(b, name, str, str.len.cint)
 
-proc addSymbol*(b: ptr Tbson, name: cstring, str: cstring): cint{.stdcall, 
-    importc: "bson_append_symbol", dynlib: mongodll, discardable.}
+proc addSymbol*(b: var TBson, name: cstring, str: cstring): cint{.stdcall, 
+    importc: "bson_append_symbol", dynlib: bsondll, discardable.}
   ##  Append a symbol to a bson.
 
-proc addSymbol*(b: ptr Tbson, name: cstring, str: cstring, len: cint): cint{.
-    stdcall, importc: "bson_append_symbol_n", dynlib: mongodll, discardable.}
+proc addSymbol*(b: var TBson, name: cstring, str: cstring, len: cint): cint{.
+    stdcall, importc: "bson_append_symbol_n", dynlib: bsondll, discardable.}
   ## Append len bytes of a symbol to a bson.
 
-proc addCode*(b: ptr Tbson, name: cstring, str: cstring): cint{.stdcall, 
-    importc: "bson_append_code", dynlib: mongodll, discardable.}
+proc addCode*(b: var TBson, name: cstring, str: cstring): cint{.stdcall, 
+    importc: "bson_append_code", dynlib: bsondll, discardable.}
   ## Append code to a bson.
 
-proc addCode*(b: ptr Tbson, name: cstring, str: cstring, len: cint): cint{.
-    stdcall, importc: "bson_append_code_n", dynlib: mongodll, discardable.}
+proc addCode*(b: var TBson, name: cstring, str: cstring, len: cint): cint{.
+    stdcall, importc: "bson_append_code_n", dynlib: bsondll, discardable.}
   ## Append len bytes of code to a bson.
 
-proc addCode*(b: ptr Tbson, name: cstring, code: cstring, 
-                          scope: ptr Tbson): cint{.stdcall, 
-    importc: "bson_append_code_w_scope", dynlib: mongodll, discardable.}
+proc addCode*(b: var TBson, name: cstring, code: cstring, 
+                          scope: var TBson): cint{.stdcall, 
+    importc: "bson_append_code_w_scope", dynlib: bsondll, discardable.}
   ## Append code to a bson with scope.
 
-proc addCode*(b: ptr Tbson, name: cstring, code: cstring, 
-              size: cint, scope: ptr Tbson): cint{.stdcall, 
-    importc: "bson_append_code_w_scope_n", dynlib: mongodll, discardable.}
+proc addCode*(b: var TBson, name: cstring, code: cstring, 
+              size: cint, scope: var TBson): cint{.stdcall, 
+    importc: "bson_append_code_w_scope_n", dynlib: bsondll, discardable.}
   ## Append len bytes of code to a bson with scope.
 
-proc addBinary*(b: ptr Tbson, name: cstring, typ: char, str: cstring, 
+proc addBinary*(b: var TBson, name: cstring, typ: char, str: cstring, 
                 len: cint): cint{.stdcall, importc: "bson_append_binary", 
-                                 dynlib: mongodll, discardable.}
+                                 dynlib: bsondll, discardable.}
   ## Append binary data to a bson.
 
-proc addBool*(b: ptr Tbson, name: cstring, v: TBsonBool): cint{.stdcall, 
-    importc: "bson_append_bool", dynlib: mongodll, discardable.}
+proc addBinary*(b: var TBson, name: cstring, data: string) =
+  ## Append binary data to a bson.
+  addBinary(b, name, '\5', data, data.len.cint)
+
+proc addBool*(b: var TBson, name: cstring, v: TBsonBool): cint{.stdcall, 
+    importc: "bson_append_bool", dynlib: bsondll, discardable.}
   ## Append a bson_bool_t to a bson.
 
-proc addNull*(b: ptr Tbson, name: cstring): cint {.stdcall, 
-    importc: "bson_append_null", dynlib: mongodll, discardable.}
+proc addNull*(b: var TBson, name: cstring): cint {.stdcall, 
+    importc: "bson_append_null", dynlib: bsondll, discardable.}
   ## Append a null value to a bson.
 
-proc addUndefined*(b: ptr Tbson, name: cstring): cint{.stdcall, 
-    importc: "bson_append_undefined", dynlib: mongodll, discardable.}
+proc addUndefined*(b: var TBson, name: cstring): cint{.stdcall, 
+    importc: "bson_append_undefined", dynlib: bsondll, discardable.}
   ## Append an undefined value to a bson.
 
-proc addRegex*(b: ptr Tbson, name: cstring, pattern: cstring, opts: cstring): cint{.
-    stdcall, importc: "bson_append_regex", dynlib: mongodll, discardable.}
+proc addRegex*(b: var TBson, name: cstring, pattern: cstring, opts: cstring): cint{.
+    stdcall, importc: "bson_append_regex", dynlib: bsondll, discardable.}
   ## Append a regex value to a bson.
 
-proc add*(b: ptr Tbson, name: cstring, Tbson: ptr Tbson): cint {.stdcall, 
-    importc: "bson_append_bson", dynlib: mongodll, discardable.}
+proc add*(b: var TBson, name: cstring, TBson: var TBson): cint {.stdcall, 
+    importc: "bson_append_bson", dynlib: bsondll, discardable.}
   ## Append bson data to a bson.
 
-proc addElement*(b: ptr Tbson, name_or_null: cstring, elem: ptr TIter): cint{.
-    stdcall, importc: "bson_append_element", dynlib: mongodll, discardable.}
+proc addElement*(b: var TBson, name_or_null: cstring, elem: var TIter): cint{.
+    stdcall, importc: "bson_append_element", dynlib: bsondll, discardable.}
   ## Append a BSON element to a bson from the current point of an iterator.
 
-proc addTimestamp*(b: ptr Tbson, name: cstring, ts: ptr TTimestamp): cint{.
-    stdcall, importc: "bson_append_timestamp", dynlib: mongodll, discardable.}
+proc addTimestamp*(b: var TBson, name: cstring, ts: var TTimestamp): cint{.
+    stdcall, importc: "bson_append_timestamp", dynlib: bsondll, discardable.}
   ## Append a bson_timestamp_t value to a bson.
 
-proc addTimestamp2*(b: ptr Tbson, name: cstring, time: cint, increment: cint): cint{.
-    stdcall, importc: "bson_append_timestamp2", dynlib: mongodll, discardable.}
-proc addDate*(b: ptr Tbson, name: cstring, millis: TDate): cint{.stdcall, 
-    importc: "bson_append_date", dynlib: mongodll, discardable.}
+proc addTimestamp2*(b: var TBson, name: cstring, time: cint, increment: cint): cint{.
+    stdcall, importc: "bson_append_timestamp2", dynlib: bsondll, discardable.}
+proc addDate*(b: var TBson, name: cstring, millis: TDate): cint{.stdcall, 
+    importc: "bson_append_date", dynlib: bsondll, discardable.}
   ## Append a bson_date_t value to a bson.
 
-proc addTime*(b: ptr Tbson, name: cstring, secs: TTime): cint{.stdcall, 
-    importc: "bson_append_time_t", dynlib: mongodll, discardable.}
+proc addTime*(b: var TBson, name: cstring, secs: TTime): cint{.stdcall, 
+    importc: "bson_append_time_t", dynlib: bsondll, discardable.}
   ## Append a time_t value to a bson.
 
-proc addStartObject*(b: ptr Tbson, name: cstring): cint {.stdcall, 
-    importc: "bson_append_start_object", dynlib: mongodll, discardable.}
+proc addStartObject*(b: var TBson, name: cstring): cint {.stdcall, 
+    importc: "bson_append_start_object", dynlib: bsondll, discardable.}
   ## Start appending a new object to a bson.
 
-proc addStartArray*(b: ptr Tbson, name: cstring): cint {.stdcall, 
-    importc: "bson_append_start_array", dynlib: mongodll, discardable.}
+proc addStartArray*(b: var TBson, name: cstring): cint {.stdcall, 
+    importc: "bson_append_start_array", dynlib: bsondll, discardable.}
   ## Start appending a new array to a bson.
 
-proc addFinishObject*(b: ptr Tbson): cint {.stdcall, 
-    importc: "bson_append_finish_object", dynlib: mongodll, discardable.}
+proc addFinishObject*(b: var TBson): cint {.stdcall, 
+    importc: "bson_append_finish_object", dynlib: bsondll, discardable.}
   ## Finish appending a new object or array to a bson.
 
-proc addFinishArray*(b: ptr Tbson): cint {.stdcall, 
-    importc: "bson_append_finish_array", dynlib: mongodll, discardable.}
+proc addFinishArray*(b: var TBson): cint {.stdcall, 
+    importc: "bson_append_finish_array", dynlib: bsondll, discardable.}
   ## Finish appending a new object or array to a bson. This
   ## is simply an alias for bson_append_finish_object.
 
 proc numstr*(str: cstring, i: cint){.stdcall, importc: "bson_numstr", 
-                                     dynlib: mongodll.}
+                                     dynlib: bsondll.}
 proc incnumstr*(str: cstring){.stdcall, importc: "bson_incnumstr", 
-                               dynlib: mongodll.}
-
-# Error handling and standard library function over-riding. 
-# -------------------------------------------------------- 
-# bson_err_handlers shouldn't return!!! 
+                               dynlib: bsondll.}
 
 type 
-  TErrHandler* = proc (errmsg: cstring){.stdcall.}
+  TErrHandler* = proc (errmsg: cstring){.
+    stdcall.} ## an error handler. Error handlers shouldn't return!
 
 proc setBsonErrHandler*(func: TErrHandler): TErrHandler {.stdcall, 
-    importc: "set_bson_err_handler", dynlib: mongodll.}
+    importc: "set_bson_err_handler", dynlib: bsondll.}
   ## Set a function for error handling.
   ## Returns the old error handling function, or nil.
 
-proc fatal*(ok: cint){.stdcall, importc: "bson_fatal", dynlib: mongodll.}
+proc fatal*(ok: cint){.stdcall, importc: "bson_fatal", dynlib: bsondll.}
   ## does nothing if ok != 0. Exit fatally.
 
 proc fatal*(ok: cint, msg: cstring){.stdcall, importc: "bson_fatal_msg", 
-    dynlib: mongodll.}
+    dynlib: bsondll.}
   ## Exit fatally with an error message.
 
-proc builderError*(b: ptr Tbson){.stdcall, importc: "bson_builder_error", 
-                                   dynlib: mongodll.}
+proc builderError*(b: var TBson){.stdcall, importc: "bson_builder_error", 
+                                   dynlib: bsondll.}
   ## Invoke the error handler, but do not exit.
 
 proc int64ToDouble*(i64: int64): cdouble {.stdcall, 
-    importc: "bson_int64_to_double", dynlib: mongodll.}
+    importc: "bson_int64_to_double", dynlib: bsondll.}
   ## Cast an int64_t to double. This is necessary for embedding in
   ## certain environments.
 
@@ -507,7 +516,6 @@ const
   MAJOR* = 0
   MINOR* = 4
   PATCH* = 0
-  DEFAULT_PORT* = 27017
 
 type 
   TError*{.size: sizeof(cint).} = enum ## connection errors
@@ -531,7 +539,7 @@ type
                         ## See conn.lasterrcode and conn.lasterrstr for details. 
     CURSOR_BSON_ERROR ## Something is wrong with the BSON provided. See conn.err
                       ## for details. 
-  TcursorFlags* = enum ## cursor flags
+  TCursorFlags* = enum ## cursor flags
     CURSOR_MUST_FREE = 1,     ## mongo_cursor_destroy should free cursor. 
     CURSOR_QUERY_SENT = (1 shl 1) ## Initial query has been sent. 
   TindexOpts* = enum 
@@ -541,7 +549,7 @@ type
     UPDATE_UPSERT = 0x00000001, 
     UPDATE_MULTI = 0x00000002, 
     UPDATE_BASIC = 0x00000004
-  TcursorOpts* = enum 
+  TCursorOpts* = enum 
     TAILABLE = (1 shl 1),     ## Create a tailable cursor. 
     SLAVE_OK = (1 shl 2),     ## Allow queries on a non-primary node. 
     NO_CURSOR_TIMEOUT = (1 shl 4),  ## Disable cursor timeouts. 
@@ -575,37 +583,37 @@ type
   THostPort*{.pure, final.} = object 
     host*: array[0..255 - 1, char]
     port*: cint
-    next*: ptr Thost_port
+    next*: ptr THostPort
 
   TReplset*{.pure, final.} = object ## replset
-    seeds*: ptr Thost_port    ## List of seeds provided by the user. 
-    hosts*: ptr Thost_port    ## List of host/ports given by the replica set 
-    name*: cstring            ## Name of the replica set. 
+    seeds*: ptr THostPort    ## List of seeds provided by the user. 
+    hosts*: ptr THostPort    ## List of host/ports given by the replica set 
+    name*: cstring           ## Name of the replica set. 
     primary_connected*: TBsonBool ## Primary node connection status. 
   
   TMongo*{.pure, final.} = object ## mongo
-    primary*: ptr Thost_port  ## Primary connection info. 
-    replset*: ptr Treplset    ## replset object if connected to a replica set. 
+    primary*: ptr THostPort   ## Primary connection info. 
+    replset*: ptr TReplSet    ## replset object if connected to a replica set. 
     sock*: cint               ## Socket file descriptor. 
     flags*: cint              ## Flags on this connection object. 
     conn_timeout_ms*: cint    ## Connection timeout in milliseconds. 
     op_timeout_ms*: cint      ## Read and write timeout in milliseconds. 
     connected*: TBsonBool     ## Connection status. 
-    err*: Terror              ## Most recent driver error code. 
+    err*: TError              ## Most recent driver error code. 
     errstr*: array[0..128 - 1, char] ## String version of most recent driver error code. 
     lasterrcode*: cint        ## getlasterror code given by the server on error. 
     lasterrstr*: cstring      ## getlasterror string generated by server. 
   
   TCursor*{.pure, final.} = object ## cursor
-    reply*: ptr Treply        ## reply is owned by cursor 
-    conn*: ptr Tmongo         ## connection is *not* owned by cursor 
+    reply*: ptr TReply        ## reply is owned by cursor 
+    conn*: ptr TMongo         ## connection is *not* owned by cursor 
     ns*: cstring              ## owned by cursor 
     flags*: cint              ## Flags used internally by this drivers. 
     seen*: cint               ## Number returned so far. 
-    current*: Tbson           ## This cursor's current bson object. 
-    err*: Tcursor_error       ## Errors on this cursor. 
-    query*: ptr Tbson         ## Bitfield containing cursor options. 
-    fields*: ptr Tbson        ## Bitfield containing cursor options. 
+    current*: TBson           ## This cursor's current bson object. 
+    err*: TCursorError        ## Errors on this cursor. 
+    query*: ptr TBson         ## Bitfield containing cursor options. 
+    fields*: ptr TBson        ## Bitfield containing cursor options. 
     options*: cint            ## Bitfield containing cursor options. 
     limit*: cint              ## Bitfield containing cursor options. 
     skip*: cint               ## Bitfield containing cursor options. 
@@ -613,135 +621,135 @@ type
 
 # Connection API 
 
-proc createMongo*(): ptr Tmongo{.stdcall, importc: "mongo_create", dynlib: mongodll.}
-proc dispose*(conn: ptr Tmongo){.stdcall, importc: "mongo_dispose", 
+proc createMongo*(): ptr TMongo{.stdcall, importc: "mongo_create", dynlib: mongodll.}
+proc dispose*(conn: ptr TMongo){.stdcall, importc: "mongo_dispose", 
                                  dynlib: mongodll.}
-proc getErr*(conn: ptr Tmongo): cint{.stdcall, importc: "mongo_get_err", 
+proc getErr*(conn: var TMongo): cint{.stdcall, importc: "mongo_get_err", 
                                      dynlib: mongodll.}
-proc isConnected*(conn: ptr Tmongo): cint{.stdcall, 
+proc isConnected*(conn: var TMongo): cint{.stdcall, 
     importc: "mongo_is_connected", dynlib: mongodll.}
-proc getOpTimeout*(conn: ptr Tmongo): cint{.stdcall, 
+proc getOpTimeout*(conn: var TMongo): cint{.stdcall, 
     importc: "mongo_get_op_timeout", dynlib: mongodll.}
-proc getPrimary*(conn: ptr Tmongo): cstring{.stdcall, 
+proc getPrimary*(conn: var TMongo): cstring{.stdcall, 
     importc: "mongo_get_primary", dynlib: mongodll.}
-proc getSocket*(conn: ptr Tmongo): cint {.stdcall, importc: "mongo_get_socket", 
+proc getSocket*(conn: var TMongo): cint {.stdcall, importc: "mongo_get_socket", 
     dynlib: mongodll.}
-proc getHostCount*(conn: ptr Tmongo): cint{.stdcall, 
+proc getHostCount*(conn: var TMongo): cint{.stdcall, 
     importc: "mongo_get_host_count", dynlib: mongodll.}
-proc getHost*(conn: ptr Tmongo, i: cint): cstring {.stdcall, 
+proc getHost*(conn: var TMongo, i: cint): cstring {.stdcall, 
     importc: "mongo_get_host", dynlib: mongodll.}
-proc createCursor*(): ptr Tcursor{.stdcall, importc: "mongo_cursor_create", 
+proc createCursor*(): ptr TCursor{.stdcall, importc: "mongo_cursor_create", 
                                   dynlib: mongodll.}
-proc dispose*(cursor: ptr Tcursor){.stdcall, 
+proc dispose*(cursor: ptr TCursor){.stdcall, 
     importc: "mongo_cursor_dispose", dynlib: mongodll.}
-proc getServerErr*(conn: ptr Tmongo): cint{.stdcall, 
+proc getServerErr*(conn: var TMongo): cint{.stdcall, 
     importc: "mongo_get_server_err", dynlib: mongodll.}
-proc getServerErrString*(conn: ptr Tmongo): cstring{.stdcall, 
+proc getServerErrString*(conn: var TMongo): cstring{.stdcall, 
     importc: "mongo_get_server_err_string", dynlib: mongodll.}
 
-proc init*(conn: ptr Tmongo){.stdcall, importc: "mongo_init", dynlib: mongodll.}
+proc init*(conn: var TMongo){.stdcall, importc: "mongo_init", dynlib: mongodll.}
   ## Initialize a new mongo connection object. You must initialize each mongo
   ## object using this function.
   ## When finished, you must pass this object to ``destroy``.
 
-proc connect*(conn: ptr Tmongo, host: cstring = "localhost", 
-              port: cint = 27017): cint {.stdcall, 
+proc connect*(conn: var TMongo, host: cstring = defaultHost, 
+              port: cint = defaultPort): cint {.stdcall, 
     importc: "mongo_connect", dynlib: mongodll.}
   ## Connect to a single MongoDB server.
 
-proc replsetInit*(conn: ptr Tmongo, name: cstring){.stdcall, 
+proc replsetInit*(conn: var TMongo, name: cstring){.stdcall, 
     importc: "mongo_replset_init", dynlib: mongodll.}
   ## Set up this connection object for connecting to a replica set.
   ## To connect, pass the object to replsetConnect.
   ## `name` is the name of the replica set to connect to.
 
-proc replsetAddSeed*(conn: ptr Tmongo, host: cstring = "localhost", 
-  port: cint = 27017){.stdcall,
+proc replsetAddSeed*(conn: var TMongo, host: cstring = defaultHost, 
+  port: cint = defaultPort){.stdcall,
   importc: "mongo_replset_add_seed", dynlib: mongodll.}
   ## Add a seed node to the replica set connection object.
   ## You must specify at least one seed node before connecting
   ## to a replica set.
 
-proc parseHost*(hostString: cstring, hostPort: ptr ThostPort){.stdcall, 
+proc parseHost*(hostString: cstring, hostPort: var ThostPort){.stdcall, 
     importc: "mongo_parse_host", dynlib: mongodll.}
   ## Utility function for converting a host-port string to a mongo_host_port.
   ## `hostString` is a string containing either a host or a host and port
   ## separated by a colon.
   ## `hostPort` is the mongo_host_port object to write the result to.
 
-proc replsetConnect*(conn: ptr Tmongo): cint{.stdcall, 
+proc replsetConnect*(conn: var TMongo): cint{.stdcall, 
     importc: "mongo_replset_connect", dynlib: mongodll.}
   ## Connect to a replica set.
   ## Before passing a connection object to this function, you must already
   ## have called setReplset and replsetAddSeed.
 
-proc setOpTimeout*(conn: ptr Tmongo, millis: cint): cint{.stdcall, 
+proc setOpTimeout*(conn: var TMongo, millis: cint): cint{.stdcall, 
     importc: "mongo_set_op_timeout", dynlib: mongodll.}
   ## Set a timeout for operations on this connection. This
   ## is a platform-specific feature, and only work on Unix-like
   ## systems. You must also compile for linux to support this.
 
-proc checkConnection*(conn: ptr Tmongo): cint {.stdcall, 
+proc checkConnection*(conn: var TMongo): cint {.stdcall, 
     importc: "mongo_check_connection", dynlib: mongodll.}
   ## Ensure that this connection is healthy by performing
   ## a round-trip to the server.
   ## Returns OK if connected; otherwise ERROR.
 
-proc reconnect*(conn: ptr Tmongo): cint {.stdcall, importc: "mongo_reconnect", 
+proc reconnect*(conn: var TMongo): cint {.stdcall, importc: "mongo_reconnect", 
     dynlib: mongodll.}
   ## Try reconnecting to the server using the existing connection settings.
   ## This function will disconnect the current socket. If you've authenticated,
   ## you'll need to re-authenticate after calling this function.
 
-proc disconnect*(conn: ptr Tmongo){.stdcall, importc: "mongo_disconnect", 
+proc disconnect*(conn: var TMongo){.stdcall, importc: "mongo_disconnect", 
                                     dynlib: mongodll.}
   ## Close the current connection to the server. After calling
   ## this function, you may call reconnect with the same
   ## connection object.
 
-proc destroy*(conn: ptr Tmongo){.stdcall, importc: "mongo_destroy", 
+proc destroy*(conn: var TMongo){.stdcall, importc: "mongo_destroy", 
                                  dynlib: mongodll.}
   ## Close any existing connection to the server and free all allocated
   ## memory associated with the conn object.
   ## You must always call this function when finished with the connection
   ## object.
 
-proc insert*(conn: ptr Tmongo, ns: cstring, data: ptr Tbson): cint{.stdcall, 
-    importc: "mongo_insert", dynlib: mongodll.}
+proc insert*(conn: var TMongo, ns: cstring, data: var TBson): cint{.stdcall, 
+    importc: "mongo_insert", dynlib: mongodll, discardable.}
   ## Insert a BSON document into a MongoDB server. This function
   ## will fail if the supplied BSON struct is not UTF-8 or if
   ## the keys are invalid for insert (contain '.' or start with '$').
 
-proc insert_batch*(conn: ptr Tmongo, namespace: cstring, 
-                   data: ptr ptr Tbson, num: cint): cint{.
-    stdcall, importc: "mongo_insert_batch", dynlib: mongodll.}
+proc insertBatch*(conn: var TMongo, ns: cstring, 
+                  data: ptr ptr TBson, num: cint): cint{.
+    stdcall, importc: "mongo_insert_batch", dynlib: mongodll, discardable.}
   ## Insert a batch of BSON documents into a MongoDB server. This function
   ## will fail if any of the documents to be inserted is invalid.
   ## `num` is the number of documents in data.
 
-proc update*(conn: ptr Tmongo, ns: cstring, cond: ptr Tbson, op: ptr Tbson, 
+proc update*(conn: var TMongo, ns: cstring, cond, op: var TBson, 
              flags: cint): cint{.stdcall, importc: "mongo_update", 
-                                 dynlib: mongodll.}
+                                 dynlib: mongodll, discardable.}
   ## Update a document in a MongoDB server.
   ## 
-  ##  | conn a mongo object.
-  ##  | ns the namespace.
-  ##  | cond the bson update query.
-  ##  | op the bson update data.
-  ##  | flags flags for the update.
-  ##  | returns OK or ERROR with error stored in conn object.
-
-proc remove*(conn: ptr Tmongo, namespace: cstring, cond: ptr Tbson): cint{.stdcall, 
+  ## | conn a mongo object.
+  ## | ns the namespace.
+  ## | cond the bson update query.
+  ## | op the bson update data.
+  ## | flags flags for the update.
+  ## | returns OK or ERROR with error stored in conn object.
+
+proc remove*(conn: var TMongo, namespace: cstring, cond: var TBson): cint{.stdcall, 
     importc: "mongo_remove", dynlib: mongodll.}
-  ##  Remove a document from a MongoDB server.
+  ## Remove a document from a MongoDB server.
   ##
   ## | conn a mongo object.
   ## | ns the namespace.
   ## | cond the bson query.
   ## | returns OK or ERROR with error stored in conn object.
 
-proc find*(conn: ptr Tmongo, namespace: cstring, query: ptr Tbson, fields: ptr Tbson, 
-           limit: cint, skip: cint, options: cint): ptr Tcursor{.stdcall, 
+proc find*(conn: var TMongo, namespace: cstring, query, fields: var TBson, 
+           limit, skip: cint, options: cint): ptr TCursor{.stdcall, 
     importc: "mongo_find", dynlib: mongodll.}
   ## Find documents in a MongoDB server.
   ##
@@ -749,21 +757,21 @@ proc find*(conn: ptr Tmongo, namespace: cstring, query: ptr Tbson, fields: ptr T
   ## | ns the namespace.
   ## | query the bson query.
   ## | fields a bson document of fields to be returned.
-  ## | limit the maximum number of documents to retrun.
+  ## | limit the maximum number of documents to return.
   ## | skip the number of documents to skip.
   ## | options A bitfield containing cursor options.
   ## | returns A cursor object allocated on the heap or nil if
   ##   an error has occurred. For finer-grained error checking,
   ##   use the cursor builder API instead.
 
-proc init*(cursor: ptr Tcursor, conn: ptr Tmongo, namespace: cstring){.stdcall, 
+proc init*(cursor: var TCursor, conn: var TMongo, namespace: cstring){.stdcall, 
     importc: "mongo_cursor_init", dynlib: mongodll.}
   ## Initalize a new cursor object.
   ##
   ## The namespace is represented as the database
   ## name and collection name separated by a dot. e.g., "test.users".
 
-proc setQuery*(cursor: ptr Tcursor, query: ptr Tbson) {.stdcall, 
+proc setQuery*(cursor: var TCursor, query: var TBson) {.stdcall, 
     importc: "mongo_cursor_set_query", dynlib: mongodll.}
   ##  Set the bson object specifying this cursor's query spec. If
   ## your query is the empty bson object "{}", then you need not
@@ -774,47 +782,47 @@ proc setQuery*(cursor: ptr Tcursor, query: ptr Tbson) {.stdcall,
   ## $query, $orderby, $hint, and/or $explain. See
   ## http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol for details.
 
-proc setFields*(cursor: ptr Tcursor, fields: ptr Tbson){.stdcall, 
+proc setFields*(cursor: var TCursor, fields: var TBson){.stdcall, 
     importc: "mongo_cursor_set_fields", dynlib: mongodll.}
   ## Set the fields to return for this cursor. If you want to return
   ## all fields, you need not set this value.
   ## `fields` is a bson object representing the fields to return.
   ## See http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields.
 
-proc setSkip*(cursor: ptr Tcursor, skip: cint){.stdcall, 
+proc setSkip*(cursor: var TCursor, skip: cint){.stdcall, 
     importc: "mongo_cursor_set_skip", dynlib: mongodll.}
   ##  Set the number of documents to skip.
 
-proc setLimit*(cursor: ptr Tcursor, limit: cint){.stdcall, 
+proc setLimit*(cursor: var TCursor, limit: cint){.stdcall, 
     importc: "mongo_cursor_set_limit", dynlib: mongodll.}
   ## Set the number of documents to return.
 
-proc setOptions*(cursor: ptr Tcursor, options: cint){.stdcall, 
+proc setOptions*(cursor: var TCursor, options: cint){.stdcall, 
     importc: "mongo_cursor_set_options", dynlib: mongodll.}
   ## Set any of the available query options (e.g., TAILABLE).
   ## See `TCursorOpts` for available constants.
 
-proc data*(cursor: ptr Tcursor): cstring {.stdcall, 
+proc data*(cursor: var TCursor): cstring {.stdcall, 
     importc: "mongo_cursor_data", dynlib: mongodll.}
   ## Return the current BSON object data as a ``cstring``. This is useful
   ## for creating bson iterators.
 
-proc bson*(cursor: ptr Tcursor): ptr Tbson{.stdcall, 
+proc bson*(cursor: var TCursor): ptr TBson{.stdcall, 
     importc: "mongo_cursor_bson", dynlib: mongodll.}
   ## Return the current BSON object.
 
-proc next*(cursor: ptr Tcursor): cint {.stdcall, 
+proc next*(cursor: var TCursor): cint {.stdcall, 
     importc: "mongo_cursor_next", dynlib: mongodll.}
   ## Iterate the cursor, returning the next item. When successful,
   ## the returned object will be stored in cursor.current;
 
-proc destroy*(cursor: ptr Tcursor): cint {.stdcall,
+proc destroy*(cursor: var TCursor): cint {.stdcall,
     importc: "mongo_cursor_destroy", dynlib: mongodll, discardable.}
   ## Destroy a cursor object. When finished with a cursor, you
   ## must pass it to this function.
 
-proc findOne*(conn: ptr Tmongo, namespace: cstring, query: ptr Tbson, 
-              fields: ptr Tbson, outp: ptr Tbson): cint{.stdcall, 
+proc findOne*(conn: var TMongo, namespace: cstring, query: var TBson, 
+              fields: var TBson, outp: var TBson): cint{.stdcall, 
     importc: "mongo_find_one", dynlib: mongodll.}
   ## Find a single document in a MongoDB server.
   ##
@@ -825,7 +833,7 @@ proc findOne*(conn: ptr Tmongo, namespace: cstring, query: ptr Tbson,
   ## | outp a bson document in which to put the query result.
   ##   outp can be nil if you don't care about results. Useful for commands.
 
-proc count*(conn: ptr Tmongo, db: cstring, coll: cstring, query: ptr Tbson): cdouble{.
+proc count*(conn: var TMongo, db: cstring, coll: cstring, query: var TBson): cdouble{.
     stdcall, importc: "mongo_count", dynlib: mongodll.}
   ## Count the number of documents in a collection matching a query.
   ##
@@ -836,8 +844,8 @@ proc count*(conn: ptr Tmongo, db: cstring, coll: cstring, query: ptr Tbson): cdo
   ## | returns the number of matching documents. If the command fails,
   ##   ERROR is returned.
 
-proc createIndex*(conn: ptr Tmongo, namespace: cstring, key: ptr Tbson, 
-                   options: cint, outp: ptr Tbson): cint {.stdcall, 
+proc createIndex*(conn: var TMongo, namespace: cstring, key: var TBson, 
+                   options: cint, outp: var TBson): cint {.stdcall, 
     importc: "mongo_create_index", dynlib: mongodll.}
   ##  Create a compouned index.
   ##
@@ -850,8 +858,8 @@ proc createIndex*(conn: ptr Tmongo, namespace: cstring, key: ptr Tbson,
   ## | out a bson document containing errors, if any.
   ## | returns MONGO_OK if index is created successfully; otherwise, MONGO_ERROR.
 
-proc createSimpleIndex*(conn: ptr Tmongo, namespace, field: cstring, 
-                        options: cint, outp: ptr Tbson): TBsonBool {.stdcall, 
+proc createSimpleIndex*(conn: var TMongo, namespace, field: cstring, 
+                        options: cint, outp: var TBson): TBsonBool {.stdcall, 
     importc: "mongo_create_simple_index", dynlib: mongodll.}
   ## Create an index with a single key.
   ##
@@ -868,8 +876,8 @@ proc createSimpleIndex*(conn: ptr Tmongo, namespace, field: cstring,
 # ----------------------------
 
 
-proc runCommand*(conn: ptr Tmongo, db: cstring, command: ptr Tbson, 
-                  outp: ptr Tbson): cint{.stdcall, importc: "mongo_run_command", 
+proc runCommand*(conn: var TMongo, db: cstring, command: var TBson, 
+                  outp: var TBson): cint{.stdcall, importc: "mongo_run_command", 
     dynlib: mongodll.}
   ## Run a command on a MongoDB server.
   ## 
@@ -879,8 +887,8 @@ proc runCommand*(conn: ptr Tmongo, db: cstring, command: ptr Tbson,
   ## | out the BSON result of the command.
   ## | returns OK if the command ran without error.
 
-proc simpleIntCommand*(conn: ptr Tmongo, db: cstring, cmd: cstring, arg: cint, 
-                         outp: ptr Tbson): cint{.stdcall, 
+proc simpleIntCommand*(conn: var TMongo, db: cstring, cmd: cstring, arg: cint, 
+                         outp: var TBson): cint{.stdcall, 
     importc: "mongo_simple_int_command", dynlib: mongodll.}
   ## Run a command that accepts a simple string key and integer value.
   ##
@@ -891,8 +899,8 @@ proc simpleIntCommand*(conn: ptr Tmongo, db: cstring, cmd: cstring, arg: cint,
   ## | out the BSON result of the command.
   ## | returns OK or an error code.
 
-proc simpleStrCommand*(conn: ptr Tmongo, db: cstring, cmd: cstring, 
-                         arg: cstring, outp: ptr Tbson): cint{.stdcall, 
+proc simpleStrCommand*(conn: var TMongo, db: cstring, cmd: cstring, 
+                         arg: cstring, outp: var TBson): cint{.stdcall, 
     importc: "mongo_simple_str_command", dynlib: mongodll.}
   ## Run a command that accepts a simple string key and value.
   ##
@@ -903,16 +911,16 @@ proc simpleStrCommand*(conn: ptr Tmongo, db: cstring, cmd: cstring,
   ## | out the BSON result of the command.
   ## | returns true if the command ran without error.
 
-proc cmdDropDb*(conn: ptr Tmongo, db: cstring): cint{.stdcall, 
+proc cmdDropDb*(conn: var TMongo, db: cstring): cint{.stdcall, 
     importc: "mongo_cmd_drop_db", dynlib: mongodll.}
   ## Drop a database.
   ##
   ## | conn a mongo object.
   ## | db the name of the database to drop.
-  ## | returns MONGO_OK or an error code.
+  ## | returns OK or an error code.
 
-proc cmdDropCollection*(conn: ptr Tmongo, db: cstring, collection: cstring, 
-                          outp: ptr Tbson): cint{.stdcall, 
+proc cmdDropCollection*(conn: var TMongo, db: cstring, collection: cstring, 
+                          outp: var TBson): cint{.stdcall, 
     importc: "mongo_cmd_drop_collection", dynlib: mongodll.}
   ## Drop a collection.
   ##
@@ -922,7 +930,7 @@ proc cmdDropCollection*(conn: ptr Tmongo, db: cstring, collection: cstring,
   ## | out a BSON document containing the result of the command.
   ## | returns true if the collection drop was successful.
 
-proc cmdAddUser*(conn: ptr Tmongo, db: cstring, user: cstring, pass: cstring): cint{.
+proc cmdAddUser*(conn: var TMongo, db: cstring, user: cstring, pass: cstring): cint{.
     stdcall, importc: "mongo_cmd_add_user", dynlib: mongodll.}
   ## Add a database user.
   ##
@@ -932,7 +940,7 @@ proc cmdAddUser*(conn: ptr Tmongo, db: cstring, user: cstring, pass: cstring): c
   ## | pass the user password
   ## | returns OK or ERROR.
 
-proc cmdAuthenticate*(conn: ptr Tmongo, db: cstring, user: cstring, 
+proc cmdAuthenticate*(conn: var TMongo, db: cstring, user: cstring, 
                       pass: cstring): cint{.stdcall, 
     importc: "mongo_cmd_authenticate", dynlib: mongodll.}
   ## Authenticate a user.
@@ -943,7 +951,7 @@ proc cmdAuthenticate*(conn: ptr Tmongo, db: cstring, user: cstring,
   ## | pass the user's password.
   ## | returns OK on sucess and ERROR on failure.
 
-proc cmdIsMaster*(conn: ptr Tmongo, outp: ptr Tbson): TBsonBool {.stdcall, 
+proc cmdIsMaster*(conn: var TMongo, outp: var TBson): TBsonBool {.stdcall, 
     importc: "mongo_cmd_ismaster", dynlib: mongodll.}
   ## Check if the current server is a master.
   ##
@@ -951,7 +959,7 @@ proc cmdIsMaster*(conn: ptr Tmongo, outp: ptr Tbson): TBsonBool {.stdcall,
   ## | outp a BSON result of the command.
   ## | returns true if the server is a master.
 
-proc cmdGetLastError*(conn: ptr Tmongo, db: cstring, outp: ptr Tbson): cint{.
+proc cmdGetLastError*(conn: var TMongo, db: cstring, outp: var TBson): cint{.
     stdcall, importc: "mongo_cmd_get_last_error", dynlib: mongodll.}
   ## Get the error for the last command with the current connection.
   ##
@@ -960,7 +968,7 @@ proc cmdGetLastError*(conn: ptr Tmongo, db: cstring, outp: ptr Tbson): cint{.
   ## | outp a BSON object containing the error details.
   ## | returns OK or ERROR
 
-proc cmdGetPrevError*(conn: ptr Tmongo, db: cstring, outp: ptr Tbson): cint{.
+proc cmdGetPrevError*(conn: var TMongo, db: cstring, outp: var TBson): cint{.
     stdcall, importc: "mongo_cmd_get_prev_error", dynlib: mongodll.}
   ## Get the most recent error with the current connection.
   ##
@@ -969,7 +977,7 @@ proc cmdGetPrevError*(conn: ptr Tmongo, db: cstring, outp: ptr Tbson): cint{.
   ## | outp a BSON object containing the error details.
   ## | returns OK or ERROR.
   
-proc cmdResetError*(conn: ptr Tmongo, db: cstring){.stdcall, 
+proc cmdResetError*(conn: var TMongo, db: cstring){.stdcall, 
     importc: "mongo_cmd_reset_error", dynlib: mongodll.}
   ## Reset the error state for the connection. `db` is the name of the database.
 
@@ -979,13 +987,13 @@ const
   DEFAULT_CHUNK_SIZE* = 262144
 
 type 
-  Toffset* = int64
+  TOffset* = int64
 
 # A GridFS represents a single collection of GridFS files in the database. 
 
 type 
-  Tgridfs*{.pure, final.} = object 
-    client*: ptr Tmongo       ## The client to db-connection. 
+  TGridfs*{.pure, final.} = object 
+    client*: ptr TMongo       ## The client to db-connection. 
     dbname*: cstring          ## The root database name 
     prefix*: cstring          ## The prefix of the GridFS's collections,
                               ## default is nil 
@@ -997,34 +1005,34 @@ type
 # A GridFile is a single GridFS file. 
 
 type 
-  Tgridfile*{.pure, final.} = object 
-    gfs*: ptr Tgridfs         ## GridFS where the GridFile is located 
-    meta*: ptr Tbson          ## GridFile's bson object where all
+  TGridFile*{.pure, final.} = object 
+    gfs*: ptr TGridfs         ## GridFS where the GridFile is located 
+    meta*: ptr TBson          ## GridFile's bson object where all
                               ## its metadata is located 
-    pos*: Toffset             ## position is the offset in the file 
-    id*: Toid                 ## files_id of the gridfile 
+    pos*: TOffset             ## position is the offset in the file 
+    id*: TOid                 ## files_id of the gridfile 
     remote_name*: cstring     ## name of the gridfile as a string 
     content_type*: cstring    ## gridfile's content type 
-    length*: Toffset          ## length of this gridfile 
+    length*: TOffset          ## length of this gridfile 
     chunk_num*: cint          ## number of the current chunk being written to 
     pending_data*: cstring    ## buffer storing data still to be
                               ## written to chunks 
     pending_len*: cint        ## length of pending_data buffer 
   
 
-proc createGridfs*(): ptr Tgridfs{.stdcall, importc: "gridfs_create", dynlib: mongodll.}
-proc dispose*(gfs: ptr Tgridfs){.stdcall, importc: "gridfs_dispose", 
+proc createGridfs*(): ptr TGridfs{.stdcall, importc: "gridfs_create", dynlib: mongodll.}
+proc dispose*(gfs: ptr TGridfs){.stdcall, importc: "gridfs_dispose", 
                                  dynlib: mongodll.}
-proc createGridfile*(): ptr Tgridfile{.stdcall, importc: "gridfile_create", 
+proc createGridfile*(): ptr TGridFile{.stdcall, importc: "gridfile_create", 
                                dynlib: mongodll.}
-proc dispose*(gf: ptr Tgridfile){.stdcall, importc: "gridfile_dispose", 
+proc dispose*(gf: ptr TGridFile){.stdcall, importc: "gridfile_dispose", 
                                   dynlib: mongodll.}
-proc getDescriptor*(gf: ptr Tgridfile, outp: ptr Tbson){.stdcall, 
+proc getDescriptor*(gf: var TGridFile, outp: var TBson){.stdcall, 
     importc: "gridfile_get_descriptor", dynlib: mongodll.}
 
 
-proc init*(client: ptr Tmongo, dbname: cstring, prefix: cstring, 
-           gfs: ptr Tgridfs): cint{.stdcall, importc: "gridfs_init", 
+proc init*(client: var TMongo, dbname: cstring, prefix: cstring, 
+           gfs: var TGridfs): cint{.stdcall, importc: "gridfs_init", 
                                     dynlib: mongodll.}
   ## Initializes a GridFS object
   ## 
@@ -1034,30 +1042,30 @@ proc init*(client: ptr Tmongo, dbname: cstring, prefix: cstring,
   ## | gfs - the GridFS object to initialize
   ## | returns - OK or ERROR.
 
-proc destroy*(gfs: ptr Tgridfs){.stdcall, importc: "gridfs_destroy", 
+proc destroy*(gfs: var TGridfs){.stdcall, importc: "gridfs_destroy", 
                                  dynlib: mongodll.}
   ## Destroys a GridFS object. Call this when finished with the object.
 
-proc writerInit*(gfile: ptr Tgridfile, gfs: ptr Tgridfs, remote_name: cstring, 
+proc writerInit*(gfile: var TGridFile, gfs: var TGridfs, remote_name: cstring, 
                   content_type: cstring){.stdcall, 
     importc: "gridfile_writer_init", dynlib: mongodll.}
   ## Initializes a gridfile for writing incrementally with ``writeBuffer``.
   ## Once initialized, you can write any number of buffers with ``writeBuffer``.
   ## When done, you must call ``writerDone`` to save the file metadata.
 
-proc writeBuffer*(gfile: ptr Tgridfile, data: cstring, length: Toffset){.
+proc writeBuffer*(gfile: var TGridFile, data: cstring, length: TOffset){.
     stdcall, importc: "gridfile_write_buffer", dynlib: mongodll.}
   ## Write to a GridFS file incrementally. You can call this function any number
   ## of times with a new buffer each time. This allows you to effectively
   ## stream to a GridFS file. When finished, be sure to call ``writerDone``.
 
-proc writerDone*(gfile: ptr Tgridfile): cint{.stdcall, 
+proc writerDone*(gfile: var TGridFile): cint{.stdcall, 
     importc: "gridfile_writer_done", dynlib: mongodll.}
   ## Signal that writing of this gridfile is complete by
   ## writing any buffered chunks along with the entry in the
   ## files collection. Returns OK or ERROR.
 
-proc storeBuffer*(gfs: ptr Tgridfs, data: cstring, length: Toffset, 
+proc storeBuffer*(gfs: var TGridfs, data: cstring, length: TOffset, 
                    remotename: cstring, contenttype: cstring): cint{.stdcall, 
     importc: "gridfs_store_buffer", dynlib: mongodll.}
   ## Store a buffer as a GridFS file.
@@ -1069,7 +1077,7 @@ proc storeBuffer*(gfs: ptr Tgridfs, data: cstring, length: Toffset,
   ## | contenttype - optional MIME type for this object
   ## | returns - MONGO_OK or MONGO_ERROR.
 
-proc storeFile*(gfs: ptr Tgridfs, filename: cstring, remotename: cstring, 
+proc storeFile*(gfs: var TGridfs, filename: cstring, remotename: cstring, 
                  contenttype: cstring): cint{.stdcall, 
     importc: "gridfs_store_file", dynlib: mongodll.}
   ## Open the file referenced by filename and store it as a GridFS file.
@@ -1080,89 +1088,89 @@ proc storeFile*(gfs: ptr Tgridfs, filename: cstring, remotename: cstring,
   ## | contenttype - optional MIME type for this object
   ## | returns - OK or ERROR.
 
-proc removeFilename*(gfs: ptr Tgridfs, filename: cstring){.stdcall, 
+proc removeFilename*(gfs: var TGridfs, filename: cstring){.stdcall, 
     importc: "gridfs_remove_filename", dynlib: mongodll.}
   ## Removes the files referenced by filename from the db.
 
-proc findQuery*(gfs: ptr Tgridfs, query: ptr Tbson, gfile: ptr Tgridfile): cint{.
+proc findQuery*(gfs: var TGridfs, query: var TBson, gfile: var TGridFile): cint{.
     stdcall, importc: "gridfs_find_query", dynlib: mongodll.}
   ## Find the first file matching the provided query within the
   ## GridFS files collection, and return the file as a GridFile.
   ## Returns OK if successful, ERROR otherwise.
   
-proc findFilename*(gfs: ptr Tgridfs, filename: cstring, gfile: ptr Tgridfile): cint{.
+proc findFilename*(gfs: var TGridfs, filename: cstring, gfile: var TGridFile): cint{.
     stdcall, importc: "gridfs_find_filename", dynlib: mongodll.}
   ## Find the first file referenced by filename within the GridFS
   ## and return it as a GridFile. Returns OK or ERROR.
 
-proc init*(gfs: ptr Tgridfs, meta: ptr Tbson, gfile: ptr Tgridfile): cint{.
+proc init*(gfs: var TGridfs, meta: var TBson, gfile: var TGridFile): cint{.
     stdcall, importc: "gridfile_init", dynlib: mongodll.}
   ## Initializes a GridFile containing the GridFS and file bson.
 
-proc destroy*(gfile: ptr Tgridfile){.stdcall, importc: "gridfile_destroy", 
+proc destroy*(gfile: var TGridFile){.stdcall, importc: "gridfile_destroy", 
                                      dynlib: mongodll.}
   ## Destroys the GridFile.
 
-proc exists*(gfile: ptr Tgridfile): TBsonBool{.stdcall, 
+proc exists*(gfile: var TGridFile): TBsonBool{.stdcall, 
     importc: "gridfile_exists", dynlib: mongodll.}
   ## Returns whether or not the GridFile exists.
 
-proc getFilename*(gfile: ptr Tgridfile): cstring{.stdcall, 
+proc getFilename*(gfile: var TGridFile): cstring{.stdcall, 
     importc: "gridfile_get_filename", dynlib: mongodll.}
   ## Returns the filename of GridFile.
 
-proc getChunksize*(gfile: ptr Tgridfile): cint{.stdcall, 
+proc getChunksize*(gfile: var TGridFile): cint{.stdcall, 
     importc: "gridfile_get_chunksize", dynlib: mongodll.}
   ## Returns the size of the chunks of the GridFile.
 
-proc getContentlength*(gfile: ptr Tgridfile): Toffset{.stdcall, 
+proc getContentlength*(gfile: var TGridFile): TOffset{.stdcall, 
     importc: "gridfile_get_contentlength", dynlib: mongodll.}
   ## Returns the length of GridFile's data.
 
-proc getContenttype*(gfile: ptr Tgridfile): cstring{.stdcall, 
+proc getContenttype*(gfile: var TGridFile): cstring{.stdcall, 
     importc: "gridfile_get_contenttype", dynlib: mongodll.}
   ## Returns the MIME type of the GridFile (nil if no type specified).
 
-proc getUploaddate*(gfile: ptr Tgridfile): Tdate{.stdcall, 
+proc getUploaddate*(gfile: var TGridFile): Tdate{.stdcall, 
     importc: "gridfile_get_uploaddate", dynlib: mongodll.}
   ## Returns the upload date of GridFile.
 
-proc getMd5*(gfile: ptr Tgridfile): cstring {.stdcall, 
+proc getMd5*(gfile: var TGridFile): cstring {.stdcall, 
     importc: "gridfile_get_md5", dynlib: mongodll.}
   ## Returns the MD5 of GridFile.
 
-proc getField*(gfile: ptr Tgridfile, name: cstring): cstring{.stdcall, 
+proc getField*(gfile: var TGridFile, name: cstring): cstring{.stdcall, 
     importc: "gridfile_get_field", dynlib: mongodll.}
   ## Returns the field in GridFile specified by name. Returns the data of the
   ## field specified (nil if none exists).
 
-proc getBoolean*(gfile: ptr Tgridfile, name: cstring): TBsonBool{.stdcall, 
+proc getBoolean*(gfile: var TGridFile, name: cstring): TBsonBool{.stdcall, 
     importc: "gridfile_get_boolean", dynlib: mongodll.}
   ## Returns a boolean field in GridFile specified by name.
 
-proc getMetadata*(gfile: ptr Tgridfile, outp: ptr Tbson){.stdcall, 
+proc getMetadata*(gfile: var TGridFile, outp: var TBson){.stdcall, 
     importc: "gridfile_get_metadata", dynlib: mongodll.}
   ## Returns the metadata of GridFile (an empty bson is returned if none
   ## exists).
 
-proc getNumchunks*(gfile: ptr Tgridfile): cint{.stdcall, 
+proc getNumchunks*(gfile: var TGridFile): cint{.stdcall, 
     importc: "gridfile_get_numchunks", dynlib: mongodll.}
   ## Returns the number of chunks in the GridFile.
 
-proc getChunk*(gfile: ptr Tgridfile, n: cint, outp: ptr Tbson){.stdcall, 
+proc getChunk*(gfile: var TGridFile, n: cint, outp: var TBson){.stdcall, 
     importc: "gridfile_get_chunk", dynlib: mongodll.}
   ## Returns chunk `n` of GridFile.
 
-proc getChunks*(gfile: ptr Tgridfile, start: cint, size: cint): ptr Tcursor{.
+proc getChunks*(gfile: var TGridFile, start: cint, size: cint): ptr TCursor{.
     stdcall, importc: "gridfile_get_chunks", dynlib: mongodll.}
   ## Returns a mongo_cursor of `size` chunks starting with chunk `start`.
   ## The cursor must be destroyed after use.
 
-proc writeFile*(gfile: ptr Tgridfile, stream: TFile): Toffset{.stdcall, 
+proc writeFile*(gfile: ptr TGridFile, stream: TFile): TOffset{.stdcall, 
     importc: "gridfile_write_file", dynlib: mongodll.}
   ## Writes the GridFile to a stream.
 
-proc read*(gfile: ptr Tgridfile, size: Toffset, buf: cstring): Toffset{.stdcall, 
+proc read*(gfile: var TGridFile, size: TOffset, buf: cstring): TOffset{.stdcall, 
     importc: "gridfile_read", dynlib: mongodll.}
   ## Reads length bytes from the GridFile to a buffer
   ## and updates the position in the file.
@@ -1170,7 +1178,7 @@ proc read*(gfile: ptr Tgridfile, size: Toffset, buf: cstring): Toffset{.stdcall,
   ## (if size is greater than EOF gridfile_read reads until EOF).
   ## Returns the number of bytes read.
 
-proc seek*(gfile: ptr Tgridfile, offset: Toffset): Toffset{.stdcall, 
+proc seek*(gfile: var TGridFile, offset: TOffset): TOffset{.stdcall, 
     importc: "gridfile_seek", dynlib: mongodll.}
   ## Updates the position in the file
   ## (If the offset goes beyond the contentlength,