Adds a fragment to the database
@param {Object} params  The parameter info.
@param {Object} config  The optional config.
@param {Object} conn    The optional db connection.
@return {Object} Promise with success or fail.
559560
function addFragment(params, config, conn) {

  // validate
  if ( (!params.id || params.id === '') && (!params.uri || params.uri === '') ) {
    return 'You must enter a valid id or uri'
  }

  // defaults
  config = config || require('../config/config.js')

  debug(params)

  // main
  return new Promise((resolve, reject) => {

    if (!conn) {
      var conn = wc_db.getConnection(config.db)
    }

    var sql
    if (params.id) {
      sql = 'INSERT into Fragment values (:id, :start, :end, NULL, NOW(), 1)'
    } else {
      sql = 'INSERT into Fragment Select m.id, :start, :end, NULL, NOW(), u.id from Media m, User u where m.uri = :uri and u.uri = :webid'
    }
    debug(sql)

    conn.query(sql, { replacements: { "id" : params.id, "start" : params.start, "end" : params.end, "uri" : params.uri, "webid" : params.webid } }).then(function(ret){
      return resolve({"ret" : ret, "conn" : conn})
    }).catch(function(err) {
      return reject({"err" : err, "conn" : conn})
    })

  })

}
989278
function(params, callback) {
			var self = this;
			var collections = [];
		  // Get the collections for this dbName
	  	this.db.listCollections().toArray(function(err, colls) {
			  // Loop through the collections
	  		for (var n = 0; n < colls.length; n++) {

	  			var options = colls[n].options || {};
	  			// Remove the old name.
	  			delete options.create;
		  		// Remove the dbName from the collection name.
	  			options.name = parseName(colls[n].name);
	  			// Set the name as the _id.
	  			options._id = options.name;

	  			// Add it to the list.
	  	  	collections.push(options);
	  	  }

		  	// Async function to add stats to each collection.
		  	var addStats = function(coll, callback){
		  		// Switch databases
		  		var collection = self.db.collection(coll.name);
		  		// Get the stats. null if empty.
		  		collection.stats(function(err, stats){
		  			// Add the stats to the corresponding database.
		  			coll.stats = stats;
			  		callback(err, coll);
		  		});
		  	};

		  	async.each(collections, addStats, function(err){
	  	    if (err) {
	  	    	callback({error:err.errmsg});
	  	    } else {
	  	    	// Sort the collections
	  	    	collections.sort(function (a, b) {
	  	    		return (a.name > b.name) ? 1 : -1;
	  	    	});
	  	    	// Send the collections
					  return callback(null, collections);
	  	    }
		  	});
	  	});
		}
807867
function updateLastSeen(params, config, conn) {

  // validate
  if (!params.uri && !params.cacheURI) {
    return 'You must enter a valid uri'
  }

  var reviewer = params.reviewer || 'http://melvincarvalho.com/#me'

  // defaults
  config = config || require('../config/config.js')

  // main
  return new Promise((resolve, reject) => {

    if (!conn) {
      var conn = wc_db.getConnection(config.db)
    }

    getUserId({ "uri": reviewer}).then(function(ret){
      params.reviewer_id = ret.ret
      return params.reviewer_id
    }).then(function(reviewer_id){
      var sql
      if (params.uri) {
        sql = 'UPDATE Media set lastSeen = NOW() where uri = :uri'
      } else if (params.cacheURI) {
        sql = 'UPDATE Media set lastSeen = NOW() where cacheURI = :cacheURI'
      }
      debug('updateLastSeen', sql, params)

      return conn.query(sql, { replacements: { "uri" : params.uri, "cacheURI" : params.cacheURI } })
    }).then(function(ret) {

      var rating = {}
      rating.uri = params.uri
      rating.cacheURI = params.cacheURI
      rating.reviewer = params.reviewer_id
      debug(rating)
      return insertRating(rating, config, conn)
    }).then(function(ret) {
      return resolve({"ret" : ret, "conn" : conn})
    }).catch(function(err) {
      return reject({"err" : err, "conn" : conn})
    })

  })

}
106103
function createParams(routePattern, fragment, queryString) {
            var params = routePattern.exec(fragment).slice(1);

            for (var i = 0; i < params.length; i++) {
                var current = params[i];
                params[i] = current ? decodeURIComponent(current) : null;
            }

            var queryParams = router.parseQueryString(queryString);
            if (queryParams) {
                params.push(queryParams);
            }

            return {
                params:params,
                queryParams:queryParams
            };
        }
600432
function createPool(conn) {
  var conf = connectionConfig[conn.app][conn.env];
  conf.connStr = connStr(conn);
  console.log('Creating pool to : ' + conf.connStr);
  // Create the pool on the conf object for easy future access
  conf.pool = anydb.createPool(conf.connStr, {
    min: conf.min,
    max: conf.max,
    onConnect: function (conn, done) {
      done(null, conn);
    },
    reset: function (conn, done) {
      done(null);
    }
  });
  // Remember all connection pools for easy termination
  pools.push(conf.pool);
  return conf.pool;
}
469130
function initMongo(config, callback) {
  
  var self = this;
  
  // Set db
  self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: true});
  
  // Get client
  self.db.open(function(err, client) {
    if (err) throw err;
    else {
      self.client = client;
      client.collectionNames(function(err, names) {
        if (err) throw err;
        else {
          var name = config.database + '.' + config.collection;
          var exists = names.filter(function(col) {
            if (col.name == name) return col; 
          });
          
          // Collection options
          var opts = {capped: true, size: config.logSize};
          if (config.logLimit != null) opts.max = config.logLimit;
          
          if (exists.length === 0) {
            client.createCollection(config.collection, opts, function(err, collection) {
              if (err) throw err;
              else {
                self.collection = collection;
                callback.call(self);
              }
            });
          } else {
            // Get collection
            client.collection(config.collection, function(err, collection) {
              if (err) throw err;
              else {
                self.collection = collection;
                // Get collection options » Check if collection has already been capped
                collection.options(function(err, options) {
                  if (err) {
                    throw err;
                  } else {
                    // Check if collection's options match log requirements
                    var ready = (options.capped === true && options.size === opts.size);
                    if ('max' in opts) ready = (ready && options.max === opts.max);
                    if (!ready) {
                      // Convert collection to capped if it's not match log requirements
                      var cmd = {"convertToCapped": config.collection, size: opts.size};
                      if ('max' in opts) cmd.max = opts.max;
                      client.command(cmd, function(err) {
                        if (err) throw err;
                        else {
                          callback.call(self);
                        }
                      });
                    } else {
                      callback.call(self);
                    }
                  }
                });
              }
            });
          }
        }
      });
    }
  });
}
344123
public static boolean call(Connection conn, String sql, Object... params) throws SQLException {
		CallableStatement call = null;
		try {
			call = StatementUtil.prepareCall(conn, sql, params);
			return call.execute();
		} finally {
			DbUtil.close(call);
		}
	}
1218571
function (callback) {
                var self = this;

                var deferred = Q.defer();
                callback = Qext.makeNodeResolver(deferred, callback);

                var breakExec = {};
                Async.waterfall([
                    function (next) {
                        if (!self.collectionName) {
                            next({
                                name: 'InternalError',
                                err: "collectionName property is not set for model " + self.identity
                            });
                        } else {
                            var dbName = self.dbName || Shared.config("environment.defaultMongoDatabase");
                            var db = self.db(dbName);
                            if (db) {
                                next(null, db);
                            }
                            else {
                                next({
                                    name: 'InternalError',
                                    err: "No connection to database " + self.identity
                                });
                            }
                        }
                    },
                    function (db, next) {

                        if (!db || _.isEmpty(db)) {
                            Logger.error("No db connection");
                            next("No db connection");
                        }
                        else {
                            //try to get exiting collection
                            db.collection(self.collectionName, {strict: true}, function (err, collection) {
                                if (!err) {
                                    //collection exists already
                                    self._collection = collection;
                                    //do not apply indexes to exiting collection, since this operation is time consuming
                                    next(breakExec, collection);
                                }
                                else {
                                    var collectionOptions = self.collectionOptions || {};
                                    db.createCollection(self.collectionName, collectionOptions, function (err, collection) {
                                        if (!err) {
                                            next(null, collection);
                                        }
                                        else {
                                            db.collection(self.collectionName, {strict: true}, function (err, collection) {
                                                if (!err) {
                                                    //collection exists already
                                                    self._collection = collection;
                                                    //do not apply indexes to exiting collection, since this operation is time consuming
                                                    next(breakExec, collection);
                                                }
                                                else {
                                                    Logger.error(err);
                                                    next(err);
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    },
                    function (collection, next) {
                        //store new collection
                        self._collection = collection;

                        if (_skipDatabaseIndexingOnNewCollections()) {
                            return next(null, collection);
                        }

                        //apply all indexes on collection
                        self.ensureAllIndexes(function (err) {
                            next(err, collection);
                        });
                    },
                    function (collection, next) {
                        //return collection
                        next(null, collection);
                    }
                ], function (err, collection) {
                    if (!err || err === breakExec) {
                        callback(null, collection);
                    }
                    else {
                        callback(err);
                    }
                });

                return deferred.promise;
            }
1008690
function connStr(conn) {
  var conf = mergeDefaults(conn);
  var connString = conf.driver + '://' + conf.username + (conf.password ? ':' + conf.password : '') + '@' + conf.host
    + (conf.port ? ':' + conf.port : '') + '/' + conf.database;
  return connString;
}
1142971
function(sql, val, callback) {
  let qry = (typeof sql === 'object') ? sql : mysql.format(sql, val);
  if (!callback && typeof val === 'function') callback = val; // Handle 2 parm scenario

  _pool.getConnection((err, conn) => {
    _pool.query(qry, (err, items, fields) => {
      if (err) return callback(err);

      conn.release();

      callback(err, items);
    });
  });
}
1371121
async function getConnection(url, opts = {}) {

    const dbName = opts.databaseName;
    if (!dbName || dbName === '')
        throw boom.badImplementation('jollof-data-arangodb: databaseName config is required', { url, opts })

    const key = url + dbName;

    //Get connection
    let connection;
    if (connPool[key]) {
        connection = connPool[key];
    } else {
        connection = new Database(url)
        connPool[key] = connection;
    }

    //Now ensure database exists
    const dbNames = await connection.listDatabases();
    if (dbNames.indexOf(dbName) > -1) {
        //our db exists. use it.
        connection.useDatabase(dbName)
    } else {
        //our db does not exist. Attempting to create it
        await connection.createDatabase(dbName, [{ username: opts.username, passw: opts.password }])
        connection.useDatabase(dbName)
    }

    return connection;
}
1175009
function runQuery(query, connection) {
  const myConnection = mysql.createConnection({
    multipleStatements: true,
    host: connection.host,
    port: connection.port ? connection.port : 3306,
    user: connection.username,
    password: connection.password,
    database: connection.database,
    insecureAuth: connection.mysqlInsecureAuth,
    timezone: 'Z',
    supportBigNumbers: true
  });

  return new Promise((resolve, reject) => {
    let incomplete = false;
    const rows = [];

    myConnection.connect(err => {
      if (err) {
        return reject(err);
      }
      let queryError;
      let resultsSent = false;

      function continueOn() {
        if (!resultsSent) {
          resultsSent = true;
          if (queryError) {
            return reject(queryError);
          }
          return resolve({ rows, incomplete });
        }
      }

      const myQuery = myConnection.query(query);
      myQuery
        .on('error', function(err) {
          // Handle error,
          // an 'end' event will be emitted after this as well
          // so we'll call the callback there.
          queryError = err;
        })
        .on('result', function(row) {
          // If we haven't hit the max yet add row to results
          if (rows.length < connection.maxRows) {
            return rows.push(row);
          }

          // Too many rows
          incomplete = true;

          // Stop the query stream
          myConnection.pause();

          // Destroy the underlying connection
          // Calling end() will wait and eventually time out
          myConnection.destroy();
          continueOn();
        })
        .on('end', function() {
          // all rows have been received
          // This will not fire if we end the connection early
          // myConnection.end()
          // myConnection.destroy()
          myConnection.end(error => {
            if (error) {
              console.error('Error ending MySQL connection', error);
            }
            continueOn();
          });
        });
    });
  });
}
1044404
function appRequest(params, cb) {
  params = params || {};
  var mbaasConf = params[constants.MBAAS_CONF_KEY];
  params[constants.MBAAS_CONF_KEY] = undefined;
  //Adding Mbaas Config Params
  var fullParams = _.extend(_.clone(params), mbaasConf);

  var invalidParamError = validateAppParams(fullParams);

  if (invalidParamError) {
    return cb(invalidParamError);
  }

  fullParams = _buildAppRequestParams(fullParams);

  return doFHMbaaSRequest(fullParams, cb);
}
759380
function buildDbConfig(appName, config) {
    var dbDriver = fetchFromConfig(appName, config, 'dbDriver') || 'mongo';
    var defaultPort = dbDriver === 'mongo' ? 27017 : 5432;
    return {
        dbName:         fetchFromConfig(appName, config, 'dbName'),
        dbPath:         fetchFromConfig(appName, config, 'dbPath'),
        dbDriver:       dbDriver,
        dbType:         fetchFromConfig(appName, config, 'dbType')        || 'mongo',
        dbUser:         fetchFromConfig(appName, config, 'dbUser')        || 'nodejs',
        dbPassword:     fetchFromConfig(appName, config, 'dbPassword')    || null,
        dbConnections:  parseInt(fetchFromConfig(appName, config, 'dbConnections')) || 20,
        dbConcurrency:  parseInt(fetchFromConfig(appName, config, 'dbConcurrency')) || 5,
        dbConnectionTimeout: parseInt(fetchFromConfig(appName, config, 'dbConnectionTimeout')) || 60000,
        dbPort: fetchFromConfig(appName, config, 'dbPort') || defaultPort,
        knexDebug: fetchFromConfig(appName, config, 'knexDebug') || false
    };
}
549847
function getConnection(options) {
  debug('getConnection','start',options);

  let key = null;
  let promise = null;
  try {
    //clone options
    options = clone(options);

    //serialize the options as a key for pools
    key = stringify(options || {});

    //if there's already a promise for the given connection, return it
    if (promises[key]) return promises[key];

    //create a new promise for the given connection options
    promise = promises[key] = createConnectionPromise(key, options);

    debug('getConnection','success')
    return promise;
  } catch(err) {
    debug('getConnection','error',err);
    return Promise.reject(err);
  }
}
1200621
async function getConnection(url, opts = {}) {
    try {
        const dbName = opts.databaseName;
        if (!dbName || dbName === '')
            throw boom.badImplementation('jollof-data-arangodb: databaseName config is required', { url, opts })

        const key = url + dbName;

        //Get connection
        let connection;
        if (connPool[key]) {
            connection = connPool[key];
        } else {
            connection = new Database(opts)
            connection.useBasicAuth(opts.username, opts.password)
            connPool[key] = connection;
        }

        //Now ensure database exists
        const dbNames = await connection.listDatabases();
        if (dbNames.indexOf(dbName) > -1) {
            //our db exists. use it.
            connection.useDatabase(dbName)
        } else {
            //our db does not exist. Attempting to create it
            await connection.createDatabase(dbName)
            connection.useDatabase(dbName)
        }

        return connection;
    } catch (e) {
        console.error(`There was an issue creating/ensuring connection to DB: ${url} with opts: ${util.inspect(opts)}`)
        throw new Error(e);
    }
}
200185
function (params) {
  assert.ok(params.__fhdb, "__fhdb parameter required for shared database");

  /**
   * Copy the default options that are always required by ditcher
   * @param target The options object to copy them to
   * @returns The options object plus the default properties
   */
  this.copyDefaultOptions = function (target) {
    target.__fhdb = params.__fhdb;
    target.__dbperapp = params.__dbperapp;
    return target;
  };

  /**
   * Create a new collection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#createCollection
   * @param name collection name
   * @param (optional) options
   * @param (optional) callback results callback
   * @returns Promise if no callback passed
   */
  this.createCollection = function (name, options, callback) {
    assert.ok(name, "collection name required");

    if (typeof options === "function") {
      callback = options;
      options = {};
    }

    options = this.copyDefaultOptions(options || {});
    options.type = name;

    if (callback) {
      params.ditcher.doCreate(options, callback);
    } else {
      return new Promise(function (resolve, reject) {
        params.ditcher.doCreate(options, function (err, collection) {
          if (err) {
            return reject(err);
          }

          resolve(collection);
        });
      });
    }
  };

  /**
   * Drop a collection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#dropCollection
   * @param name
   * @param (optional) callback
   * @returns Promise if no callback passed
   */
  this.dropCollection = function (name, callback) {
    assert.ok(name, "collection name required");

    var options = {
      type: name
    };

    options = this.copyDefaultOptions(options || {});

    if (callback) {
      params.ditcher.doDropCollection(options, callback);
    } else {
      return new Promise(function (resolve, reject) {
        params.ditcher.doDropCollection(options, function (err, result) {
          if (err) {
            return reject(err);
          }

          resolve(result);
        });
      });
    }
  };

  /**
   * List all collections
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#listCollections
   * @param filter Query to filter collections by
   * @param options (optional) Optional settings
   * @returns Cursor
   */
  this.listCollections = function (filter, options) {
    options = this.copyDefaultOptions(options || {});
    return params.ditcher.doGetCollectionsListCursor(filter, options);
  };

  /**
   * Return collections instance
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#collection
   * @param name Query to filter collections by
   * @param options (optional) Optional settings
   * @param callback (optional) result callback
   * @returns Collection instance if no callback passed
   */
  this.collection = function (name, options, callback) {
    assert.ok(name, "collection name required");

    options = this.copyDefaultOptions(options || {});
    options.type = name;

    return params.ditcher.doGetCollectionInstance(options, callback);
  };

  /**
   * Create an index on collection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#createIndex
   * @param name Name of the collection
   * @param fieldOrSpec Field to use for the index
   * @param options (optional) Options
   * @param callback (optional) result callback
   * @returns Promise if no callback passed
   */
  this.createIndex = function (name, fieldOrSpec, options, callback) {
    assert.ok(name, "collection name required");
    assert.ok(fieldOrSpec, "index spec required");

    if(typeof options === "function") {
      callback = options;
      options = {};
    }

    options = this.copyDefaultOptions(options || {});
    options.type = name;
    options.index = fieldOrSpec;

    if (callback) {
      params.ditcher.doIndex(options, callback);
    } else {
      return new Promise(function (resolve, reject) {
        params.ditcher.doIndex(options, function (err, result) {
          if (err) {
            return reject(err);
          }

          resolve(result);
        });
      });
    }
  };

  /**
   * Rename a collection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#renameCollection
   * @param fromCollection Current name
   * @param toCollection New name
   * @param options (optional) Options
   * @param callback (optional) Result callback
   */
  this.renameCollection = function (fromCollection, toCollection, options, callback) {
    assert.ok(fromCollection, "current collection name required");
    assert.ok(toCollection, "new collection name required");

    if(typeof options === "function") {
      callback = options;
      options = {};
    }

    options = this.copyDefaultOptions(options || {});
    options.type = fromCollection;
    options.toCollection = toCollection;

    if (callback) {
      params.ditcher.doRenameCollection(options, callback);
    } else {
      return new Promise(function (resolve, reject) {
        params.ditcher.doRenameCollection(options, function (err, result) {
          if (err) {
            return reject(err);
          }

          resolve(result);
        });
      });
    }
  };

  /**
   * Close the database connection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#close
   * @param force Force close, emitting no events
   * @param callback (optional) result callback
   */
  this.close = function (force, callback) {
    if (typeof force === "function") {
      callback = force;
      force = false;
    }

    return params.ditcher.database.close(force, callback);
  };
}