A class representation of the BSON DBRef type.

@class
@param {string} namespace the collection name.
@param {ObjectID} oid the reference ObjectID.
@param {string} [db] optional db name, if omitted the reference is local to the current db.
@return {DBRef}
340267
function DBRef(namespace, oid, db) {
  if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db);
  
  this._bsontype = 'DBRef';
  this.namespace = namespace;
  this.oid = oid;
  this.db = db;
}
1317843
public Map<BsonValue, ChangeEvent<BsonDocument>> getEventsForNamespace(
      final MongoNamespace namespace
  ) {
    this.instanceLock.readLock().lock();
    final NamespaceChangeStreamListener streamer;
    try {
      streamer = nsStreamers.get(namespace);
    } finally {
      this.instanceLock.readLock().unlock();
    }
    if (streamer == null) {
      return new HashMap<>();
    }
    return streamer.getEvents();
  }
1155496
function(conn) {
    var coll = CollMethods.Instance(dbLit, conn);
    var dbMethods = DBMethods(dbLit, conn);
    var dbMethodKeys = Object.keys(dbMethods);

    return {
      getOwnPropertyNames: function() {
        conn.db.collectionNames(conn.flow.add());

        return conn.flow.wait().map(function(obj) {
          var collName = obj.name;
          return collName.substr(collName.indexOf('.') + 1);
        }).concat(dbMethodKeys.map(function(methodName) {
          return util.format('%s(', methodName);
        }));
      },
      getOwnPropertyDescriptor: function(proxy, collectionName) {
        return {
          writable: false,
          enumerable: false,
          configurable: true
        };
      },
      getPropertyDescriptor: function(proxy, collectionName) {
        return this.getOwnPropertyDescriptor(proxy, collectionName);
      },
      get: function(proxy, op1) {
        if (op1 === 'getConn') {
          return function() { return conn; };
        } else if (op1 === '_name') {
          return conn.db.databaseName;
        } else if (op1 === 'toString') {
          return function() { return conn.db.databaseName; };
        }

        if (dbMethodKeys.indexOf(op1) !== -1) {
          return dbMethods[op1];
        }

        var collOps = coll(op1);
        var collOpKeys = Object.keys(collOps);
        var _this = this;
        return Proxy.create({
          getOwnPropertyNames: function() {
            var collNames = _this.getOwnPropertyNames();
            var matchColls = collNames.filter(function(collName) {
              return collName !== op1 &&
                collName.indexOf(op1) !== -1;
            }).map(function(collName) {
              var ext = collName.substr(collName.indexOf('.') + 1);
              var subExt = ext.indexOf(op1);
              if (subExt != -1) {
                return '';
              }
              return ext;
            }).filter(function(collName) {
              return collName.length;
            });
            if (matchColls.length) {
              return matchColls;
            }
            return collOpKeys.map(function(collOpKey) {
              return util.format('%s(', collOpKey);
            });
          },
          getOwnPropertyDescriptor: function(proxy, op) {
            return _this.getOwnPropertyDescriptor(proxy, op);
          },
          getPropertyDescriptor: function(proxy, op) {
            return _this.getPropertyDescriptor(proxy, op);
          },
          get: function(proxy, op2) {
            if (collOpKeys.indexOf(op2) !== -1) {
              return collOps[op2];
            }
            return _this.get(proxy, op1 + '.' + op2);
          }
        });
      }
    };
  }
679646
function( options ){

			options 			= options || {};
			options.$db 		= cOptions.db;
			options.$dbName 	= cOptions.database;
			options.$model 		= cOptions.model;

			return new cOptions.cls( options );
		}
884595
function (DB_name, account, pass, onOpenDone) {

		var conn = SR._storage.openDB(DB_name, dbSetting.serverIP, dbSetting.serverPort);

		// load fail
		if (conn === undefined) {
			LOG.error('cannot open DB: ' + DB_name, 'SR.DB');
			return onOpenDone(false);
		}

		// open DB & load the collection data from DB
		conn.open(function (err, client) {

			// check if error
			if (err) {
				LOG.error(err, 'SR.DB');
				return UTIL.safeCall(onOpenDone, false);
			}

			var user_created = false;

			var auth_user = function () {

				// authenticate into the DB
				LOG.sys('authenticating DB [' + DB_name + ']...', 'SR.DB');

				// NOTE: use client.admin().authenticate will force using admin account
				//	   but in general we should not do that

				client.authenticate(account, pass, function (err, replies) {

					if (err) {

						// if this is repeated call
						if (user_created === true) {
							LOG.error(err, 'SR.DB');
							LOG.warn('DB authentication failure', 'SR.DB');
							return UTIL.safeCall(onOpenDone, false);
						}

						// create DB user/pass (assume it's a new DB)
						LOG.warn('auth error, assume DB does not exist, try to create new DB...', 'SR.DB');

						// NOTE: right now this action is always successful, so it's like no auth exists
						//	   might be a bug in MongoDB
						user_created = true;

						client.admin().authenticate(SR.Settings.DB_ADMIN.account, SR.Settings.DB_ADMIN.pass, function (err, replies) {
							if (err) {
								LOG.error(err, 'SR.DB');
								LOG.error('DB admin auth failure, please make sure DB_ADMIN is setup correctly either in system or project setting', 'SR.DB');
								return UTIL.safeCall(onOpenDone, false);
							}

							client.addUser(account, pass, function (err, result) {

								if (err) {
									LOG.error(err, 'SR.DB');
									LOG.warn('DB addUser failure', 'SR.DB');
									return UTIL.safeCall(onOpenDone, false);
								}

								LOG.warn('DB addUser success, re-authenticate', 'SR.DB');
								auth_user();
							});
						});

						return;
					}

					LOG.warn('DB authentication success', 'SR.DB');

					// store client for later access
					l_DBconn[DB_name] = conn;
					l_DBclient[DB_name] = client;
					UTIL.safeCall(onOpenDone, true);
				});
			}

			// perform first DB authentication
			auth_user();
		});
	}
1258381
def name(oid)
      current_oid = ObjectId.new(oid)
      index = []
      while current_oid.size > 1
        name = @by_oid[current_oid.to_s]
        if name
          return index.empty? ? name : "#{name}.#{index.join('.')}"
        end
        index.unshift current_oid.slice!(-1)
      end
      ObjectId.new(oid).to_s
    end
333990
function get(datastore, kind, namespace) {
    return function(id, cb) {
        var keyParam = [kind, id];
        if (namespace) {
            keyParam = {
                namespace: namespace,
                path: keyParam
            };
        }
        var key = datastore.key(keyParam);

        datastore.get(key, function(err, entity) {
            if (err)
                return cb(err);

            return cb(null, entity ? entity : null);
        });
    };
}
1122553
function _get_type_by_name(self, document_type) {
	return do_query(self, "SELECT * FROM types WHERE name = $1", [document_type]).then(get_results(NoPg.Type)).then(function(results) {
		debug.assert(results).is('array');
		if(results.length !== 1) {
			if(results.length === 0) {
				throw new TypeError("Database has no type: " + document_type);
			}
			throw new TypeError("Database has multiple types: " + document_type + " (" + results.length + ")");
		}
		var result = results.shift();
		debug.assert(result).is('object');
		return result;
	});
}
1229843
function _initStorage(options) {
	        var self = this;
	        var dbInfo = {
	            db: null
	        };

	        if (options) {
	            for (var i in options) {
	                dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
	            }
	        }

	        var dbInfoPromise = new Promise(function (resolve, reject) {
	            // Open the database; the openDatabase API will automatically
	            // create it for us if it doesn't exist.
	            try {
	                dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
	            } catch (e) {
	                return self.setDriver(self.LOCALSTORAGE).then(function () {
	                    return self._initStorage(options);
	                }).then(resolve)['catch'](reject);
	            }

	            // Create our key/value table if it doesn't exist.
	            dbInfo.db.transaction(function (t) {
	                t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () {
	                    self._dbInfo = dbInfo;
	                    resolve();
	                }, function (t, error) {
	                    reject(error);
	                });
	            });
	        });

	        return new Promise(function (resolve, reject) {
	            resolve(__webpack_require__(3));
	        }).then(function (lib) {
	            dbInfo.serializer = lib;
	            return dbInfoPromise;
	        });
	    }
663393
function _initStorage(options) {
	        var self = this;
	        var dbInfo = {};
	        if (options) {
	            for (var i in options) {
	                dbInfo[i] = options[i];
	            }
	        }

	        dbInfo.keyPrefix = dbInfo.name + '/';

	        if (dbInfo.storeName !== self._defaultConfig.storeName) {
	            dbInfo.keyPrefix += dbInfo.storeName + '/';
	        }

	        self._dbInfo = dbInfo;

	        return new Promise(function (resolve, reject) {
	            resolve(__webpack_require__(3));
	        }).then(function (lib) {
	            dbInfo.serializer = lib;
	            return Promise.resolve();
	        });
	    }
1009037
function(db) {
		return db.query('SELECT name FROM types WHERE name IS NOT NULL').then(function(db) {
			var types = db.fetch();
			debug.assert(types).is('array');

			var queries = ARRAY(types).map(function step_builder(type) {
				if(type && type.name) {
					return NoPg.createTriggerQueriesForType(type.name);
				}
				return [];
			}).reduce(function(a, b) {
				return a.concat(b);
			}, []);

			return queries.map(function(q) {
				return db.query(q);
			}).reduce(_Q.when, _Q(db));
		});
	}
178224
function() {
				var doc = this;
				var outDoc = doc.toObject(); // Rely on the toObject() syntax to strip out rubbish

				doc.getOIDs().forEach(function(node) {
					switch (node.fkType) {
						case 'objectId':
							var oidLeaf = _.get(doc, node.docPath);
							if (_.isUndefined(oidLeaf)) return; // Ignore undefined

							if (!o.utilities.isObjectID(oidLeaf)) {
								if (_.has(oidLeaf, '_id')) { // Already populated?
									_.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf._id));
								} else { // Convert to an OID
									_.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf));
								}
							}
							break;
						case 'objectIdArray':
							var oidLeaf = _.get(doc, node.schemaPath);
							_.set(outDoc, node.schemaPath, oidLeaf.map(function(leaf) {
								return o.utilities.isObjectID(leaf) ? leaf : o.utilities.objectID(leaf);
							}));
							break;
						default:
							return; // Ignore unsupported OID types
					}
				});

				return outDoc;
			}
1369442
function _initStorage$1(options) {
    var self = this;
    var dbInfo = {
        db: null
    };

    if (options) {
        for (var i in options) {
            dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
        }
    }

    var dbInfoPromise = new Promise$1(function (resolve, reject) {
        // Open the database; the openDatabase API will automatically
        // create it for us if it doesn't exist.
        try {
            dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
        } catch (e) {
            return reject(e);
        }

        // Create our key/value table if it doesn't exist.
        dbInfo.db.transaction(function (t) {
            createDbTable(t, dbInfo, function () {
                self._dbInfo = dbInfo;
                resolve();
            }, function (t, error) {
                reject(error);
            });
        }, reject);
    });

    dbInfo.serializer = localforageSerializer;
    return dbInfoPromise;
}
159045
function(o, fields, callback) {
    
    var single, self = this;
    
    if (callback == null) {
      callback = fields;
      fields = null;
    } else if (fields instanceof Array) {
      if (fields.indexOf('id') === -1) {
        fields.unshift('id'); // Ensure ID is included in query
      }
      fields = fields.join(', ');
    }
    
    if (typeof o == 'number') { 
      
      // If `o` is number: Convert to object
      o = {id: o};

    } else if (util.isArray(o)) {
      
      // If `o` is an array of params, process args recursively using multi
      var arr = o;
      var multi = this.multi();
      
      for (var i=0; i < arr.length; i++) {
        multi.get(arr[i], fields);
      }
      
      return multi.exec(function(err, results) {
        results = results.filter(function(val) {
          return val; // Filter null values
        });
        callback.call(self, err, results);
      });
      
    } else if (typeof o == 'object') {
      
      // IF `o` is object: Validate without checking required fields
      this.propertyCheck(o);
      
    } else {
      
      return callback.call(self, new Error(util.format("%s: Wrong value for `o` argument", this.className)), null);
      
    }
    
    // Set single if ID is specified in query
    if (o.id) single = true;
    
    // Prepare custom query
    var condition, key, value;
    var keys = [], values = [];
    
    for (key in o) {
      keys.push(key);
      values.push(o[key]);
    }
    
    // Prevent empty args
    if (keys.length === 0) {
      return callback.call(self, new Error(util.format("%s: Empty arguments", this.className)));
    } else {
      var len;
      condition = [];
      for (i=0,len=keys.length; i < len; i++) {
        condition.push(util.format('%s=$%d', keys[i], (i+1)));
      }
      condition = condition.join(' AND ');
    }
    
    // Get model data & return generated model (if found)
    this.driver.queryWhere({
      condition: condition,
      columns: fields || undefined,
      params: values,
      table: this.context,
      appendSql: "ORDER BY id DESC"
    }, function(err, results) {
      if (err) {
        callback.call(self, err, null);
      } else {
        if (results.length === 0) {
          callback.call(self, null, single ? null : []);
        } else if (single) {
          callback.call(self, null, self.createModel(results[0]));
        } else {
          for (var models=[],i=0; i < results.length; i++) {
            models.push(self.createModel(results[i]));
          }
          callback.call(self, null, models);
        }
      }
    });
  }
1076161
function db(op, fn){
  if(!indexedDB){
    return fn(new Error('store `indexeddb` not supported by this browser'));
  }
  if(typeof op === 'function'){
    fn = op;
    op = 'readwrite';
  }

  if(source !== null){
    return fn(null, source.transaction(module.exports.prefix, op).objectStore(module.exports.prefix));
  }
  var req = indexedDB.open(module.exports.prefix, 1);
  req.onerror = function(e){
    fn(e);
  };
  req.onupgradeneeded = function(){
    // First time setup: create an empty object store
    req.result.createObjectStore(module.exports.prefix);
  };
  req.onsuccess = function() {
    source = req.result;
    db(op, fn);
  };
}
494411
function getStorageObj(client, namespace) {
    return {
        get: function(id, cb) {
            client.hget(namespace, id, function(err, res) {
                cb(err, res ? JSON.parse(res) : null);
            });
        },
        save: function(object, cb) {
            if (!object.id) {
                return cb(new Error('The given object must have an id property'), {});
            }

            client.hset(namespace, object.id, JSON.stringify(object), cb);
        },
        remove: function(id, cb) {
            client.hdel(namespace, [id], cb);
        },
        all: function(cb, options) {
            client.hgetall(namespace, function(err, res) {
                if (err) {
                    return cb(err);
                }

                var parsed,
                    array = [];

                for (var i in res) {
                    parsed = JSON.parse(res[i]);
                    res[i] = parsed;
                    array.push(parsed);
                }

                cb(null, options && options.type === 'object' ? res : array);
            });
        }
    };
}
894601
function (DB_name, name, onDone, prefix) {

	//LOG.warn('init ' + DB_name + ' collection: ' + name, 'SR.DB');

	if (l_DBclient.hasOwnProperty(DB_name) === false) {
		LOG.error('DBclient not init or authenticated for DB [' + DB_name + ']', 'SR.DB');
		return UTIL.safeCall(onDone, false);
	}

	// check if already init
	if (l_getCollection(name, undefined, DB_name) !== undefined) {
		LOG.warn('DB [' + DB_name + '] collection [' + name + '] already loaded', 'SR.DB');
		LOG.warn('please check if different codes are using the same collection names', 'SR.DB');
		// NOTE: we assume double declaration of collection name is ok
		return UTIL.safeCall(onDone, true);
	}

	// build collection name to prefix with server name or a specified prefix
	var collection_name = (prefix || SR.Settings.SERVER_INFO.name) + ':' + name;

	// original simple version
	//var collection_name = name;

	l_DBclient[DB_name].collection(collection_name,
		function (err, collection) {
			if (err) {
				LOG.error(err, 'SR.DB');
				LOG.error('init DB [' + DB_name + ' ] collection [' + collection_name + '] error', 'SR.DB');
				UTIL.safeCall(onDone, false);
			} else {
				// store each name as a collection entry in collection object
				// collection name, instance(conn) , cache (idx by _id)
				var msg = 'init DB [' + DB_name + '] collection [' + collection_name + '] success';
				LOG.debug(msg, 'SR.DB');
				if (l_clts.hasOwnProperty(DB_name) === false) {
					l_clts[DB_name] = {};
				}

				// store collection instance into a two-level map
				l_clts[DB_name][name] = collection;

				// attach entity list to collection (for object caching)
				l_clts[DB_name][name].cache = {};

				UTIL.safeCall(onDone, true);
			}
		}
	);
}