Inserts rating to the database
@param {Object} rating  The rating to add.
@param {Object} config  The optional config.
@param {Object} conn    The optional db connection.
@return {Object} Promise with success or fail.
355799
function insertRating(rating, config, conn) {


  // validate
  if ( (!rating.uri || rating.uri === '') && (!rating.cacheURI || rating.cacheURI === '') ) {
    return 'You must enter a valid uri'
  }
  if (!rating.reviewer || rating.reviewer === '') {
    return 'You must enter a valid reviewer'
  }

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


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

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

    var sql
    if (rating.uri) {
      sql = 'INSERT into Rating values (NULL, :uri, :rating, NULL, :reviewer, NULL, NOW())'
    } else {
      sql = 'INSERT into Rating SELECT NULL, a.uri, :rating, NULL, :reviewer, NULL, NOW() from Media a where a.cacheURI = :cacheURI '
    }
    debug('insertRating', sql, rating)

    conn.query(sql, { replacements: { "uri" : rating.uri, "cacheURI" : rating.cacheURI, "reviewer" : rating.reviewer, "rating" : rating.rating ? rating.rating : null } }).then(function(ret){
      return resolve({"ret" : ret, "conn" : conn})
    }).catch(function(err) {
      return reject({"err" : err, "conn" : conn})
    })

  })

}
1034544
function Pool(config) {
	if(!(this instanceof Pool)) {
		return new Pool(config);
	}
	var self = this;
	if(!config) { throw new TypeError("config not set"); }
	self._pool = require('mysql').createPool(config);
	self._get_connection = Q.nfbind(self._pool.getConnection.bind(self._pool));
	db.Pool.call(this);
}
452406
def update(postid, userid, rating):
        '''
        
        '''
        rating_recs = TabRating.select().where(
            (TabRating.post_id == postid) & (TabRating.user_id == userid)
        )
        if rating_recs.count() > 0:
            MRating.__update_rating(rating_recs.get().uid, rating)
        else:
            MRating.__insert_data(postid, userid, rating)
196030
public void addConnection(WebSocketConnection conn) {
        WebSocketScope scope = getScope(conn);
        scope.addConnection(conn);
    }
65047
def set_config(self, config):
        
        with self._conn:
            self._conn.execute("DELETE FROM config")
            self._conn.execute('INSERT INTO config VALUES(?)',
                               (serialize_config(config),))
289130
function putDB(cb) {
    request.put({url: db_url}, function(error, response, body) {
      if (error) {
        console.log("Error creating DB: " + error);
      } else {
        cb();
      }
    });
  }
177246
function addMeta(params, config, conn) {

  params = params || {}

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

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

  debug(params)

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

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

    if (!params.subtitlesURI) {
      params.subtitlesURI = null
    }

    if (!params.charenc) {
      params.charenc = null
    }

    var sql = 'INSERT into Meta select a.id, :length, :subtitlesURI, :charenc from Media a where a.uri = :uri ;'
    debug('addMeta', sql, params)

    conn.query(sql, { replacements: { "length" : params.length, "subtitlesURI": params.subtitlesURI, "uri" : params.uri, "charenc" : params.charenc } }).then(function(ret){
      return resolve({"ret" : ret, "conn" : conn})
    }).catch(function(err) {
      return reject({"err" : err, "conn" : conn})
    })

  })

}
855361
function _checkConnection(conn) {
  // Return Promise for getConnection callback wrapping
  return new Promise((resolve, reject) => {
    if (conn) {
      resolve(conn);
    } else {
      _pool.getConnection((err, conn) => {
        if (err) reject(err); // Reject this error
        else resolve(conn); // Resolve the connection
      })
    }
  });
}
309215
function CreateConnection (gammu, opts) {

    gammu.Debug (3, "MySQL creating connection [%s]", gammu.uid);
    gammu.base = mysql.createConnection(opts);

    // register event for asynchronous server errors
    gammu.base.on('error', function(err) {
        gammu.Debug (1, "MySQL server error=[%s]", err);

        // Sever was restarted or network connection was lost let restart connection
        if(err.code === 'PROTOCOL_CONNECTION_LOST') {
            gammu.Debug.call (gammu, 4, "MySQL connection lost [%s/%d] automatic connect retry in 10s]", gammu.uid);
            setTimeout(function () {CreateConnection (gammu,opts);}, MYSQL_RECONNECT_TIMER);
        } else {
            throw err;  // server variable configures this)
        }
    });

    // force an initial connectiion at object construction time
    gammu.base.connect (function(err) {
        if (err) {
            gammu.Debug.call (gammu, 1, "MySQL connection fail [%s] automatic connect retry in 10s]", err);
            setTimeout(function () {CreateConnection (gammu,opts);}, MYSQL_RECONNECT_TIMER);

        } else {
            gammu.Debug.call (gammu, 5,"MySQL Connect Done [%s]",  gammu.uid);
        }
    });
}
678475
function(pool) {
    const conn = new Connection(options.connOptions);
    return conn
      .connect()
      .then(() => {
        if (pool.closed) {
          conn
            .end()
            .then(() => {})
            .catch(() => {});
          return Promise.reject(
            Errors.createError(
              'Cannot create new connection to pool, pool closed',
              true,
              null,
              '08S01',
              Errors.ER_ADD_CONNECTION_CLOSED_POOL,
              null
            )
          );
        }

        conn.releaseWithoutError = () => {
          conn.release().catch(() => {});
        };

        conn.forceEnd = conn.end;

        conn.release = () => {
          if (pool.closed) {
            pool._discardConnection(conn);
            return Promise.resolve();
          }
          if (options.noControlAfterUse) {
            pool._releaseConnection(conn);
            return Promise.resolve();
          }
          //if server permit it, reset the connection, or rollback only if not
          let revertFunction = conn.rollback;
          if (
            options.resetAfterUse &&
            ((conn.info.isMariaDB() && conn.info.hasMinVersion(10, 2, 4)) ||
              (!conn.info.isMariaDB() && conn.info.hasMinVersion(5, 7, 3)))
          ) {
            revertFunction = conn.reset;
          }

          return revertFunction()
            .then(() => {
              pool._releaseConnection(conn);
              return Promise.resolve();
            })
            .catch(err => {
              //uncertain connection state.
              // discard it
              pool._discardConnection(conn);
              return Promise.resolve();
            });
        };
        conn.end = conn.release;
        return Promise.resolve(conn);
      })
      .catch(err => {
        return Promise.reject(err);
      });
  }
1297904
function runQuery(query, connection) {
  const config = {
    user: connection.username,
    password: connection.password,
    connection_string: connection.connection_string
  };
  // TODO use connection pool
  // TODO handle connection.maxRows

  let cn = config.connection_string;

  // Not all drivers require auth
  if (config.user) {
    cn = cn + ';Uid=' + config.user;
  }
  if (config.password) {
    cn = cn + ';Pwd=' + config.password;
  }

  return openConnection(cn)
    .then(() => executeQuery(query))
    .then(queryResult => {
      odbc.close(); // TODO consider putting into finally()?
      return Promise.resolve({ rows: queryResult, incomplete: false });
    })
    .catch(function(e) {
      console.error(e, e.stack);
    });
}
60876
public static function insert($table, $data = array(), $config = array()) {
        DB::connect();
        return DB::$connection->insert($table, $data, $config);
    }
1098228
function loadConfig(configPath) {
	return new Promise((resolve, reject) => {
		configPath = resolveConfigPath(configPath);
		let config;
		try {
			config = loadLocalConfigUnmodified(configPath);
			if (!config) {
				config = loadLocalConfigWithJs(configPath);
			}
			if (!config) {
				config = loadLocalConfigWithJson(configPath);
			}
			if (program.config && !config) {
				return reject(new Error(`The config file "${configPath}" could not be loaded`));
			}
		} catch (error) {
			return reject(
				new Error(`There was a problem loading "${configPath}":\n${error.stack}`)
			);
		}

		// Allow loaded configs to return a promise
		Promise.resolve(config).then(config => {
			resolve(defaultConfig(config || {}));
		});
	});
}
369816
function addReview(reviews, review) {
  if (!reviews.length) {
    return [review];
  }

  var i = reviews.length - 1;
  for (; i >= 0; i -= 1) {
    if (reviews[i].ts <= review.ts) {
      break;
    }
  }

  var newReviews = reviews.slice(0);
  newReviews.splice(i + 1, 0, review);

  return newReviews;
}
1137946
function search(params, config, conn) {


  if (!params.q && !params.tag) {
    return 'You must enter a valid query or tag'
  }


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


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

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

    limit = params.limit || 1000

    if (params.q) {
      var sql = "SELECT * from Media m where uri like '%" + params.q + "%' order by rating desc LIMIT 1000"
    }
    if (params.tag) {
      var sql = 'SELECT uri from Media m left join MediaTag mt on m.id = mt.media_id left join Tag t on mt.tag_id = t.id  where t.tag = :tag order by t.tag LIMIT :limit '
    }

    conn.query(sql, { replacements: { "tag" : params.tag, "limit" : limit } }).then(function(ret){
      return resolve({"ret" : ret, "conn" : conn})
    }).catch(function(err) {
      return reject({"err" : err, "conn" : conn})
    })

  })

}
705571
function bin(argv) {
  // setup config
  var config = require('../config/config.js')



  program
  .arguments('<uri> <amount> <reviewer>')
  .option('-d, --database <database>', 'Database')
  .parse(argv)


  var defaultDatabase = 'webcredits'

  config.database = program.database || config.database || defaultDatabase

  var rating = {}
  rating.uri = program.args[0]
  rating.rating = program.args[1]
  rating.reviewer = program.args[2]

  // validate
  if (!rating.uri || rating.uri === '') {
    console.error('You must enter a valid uri')
    return
  }

  if (isNaN(rating.rating)) {
    console.error('You must enter a rating')
    return

  }
  if (!rating.reviewer || rating.reviewer === '') {
    console.error('You must enter a valid reviewer')
    return
  }


  // main
  qpm_media.addRating(rating, config).then(function(ret) {
    if (ret.conn) {
      var conn = ret.conn
      conn.close()
    }
    console.log(ret.ret)
  }).catch(function(err){
    if (err.conn) {
      var conn = err.conn
      conn.close()
    }
    console.error(err.err)
  })


}
1227373
public static function connect(ConnectionConfig $connectionConfig, CancellationToken $token = null): Promise
    {
        $connectionString = \str_replace(";", " ", $connectionConfig->getConnectionString());

        try {
            $connection = new pq\Connection($connectionString, pq\Connection::ASYNC);
        } catch (pq\Exception $exception) {
            return new Failure(new ConnectionException("Could not connect to PostgreSQL server", 0, $exception));
        }

        $connection->nonblocking = true;
        $connection->unbuffered = true;

        $deferred = new Deferred;

        $callback = function () use ($connection, $deferred) {
            switch ($connection->poll()) {
                case pq\Connection::POLLING_READING:
                    return; // Connection not ready, poll again.

                case pq\Connection::POLLING_WRITING:
                    return; // Still writing...

                case pq\Connection::POLLING_FAILED:
                    $deferred->fail(new ConnectionException($connection->errorMessage));
                    return;

                case pq\Connection::POLLING_OK:
                    $deferred->resolve(new self($connection));
                    return;
            }
        };

        $poll = Loop::onReadable($connection->socket, $callback);
        $await = Loop::onWritable($connection->socket, $callback);

        $promise = $deferred->promise();

        $token = $token ?? new NullCancellationToken();
        $id = $token->subscribe([$deferred, "fail"]);

        $promise->onResolve(function () use ($poll, $await, $id, $token) {
            $token->unsubscribe($id);
            Loop::cancel($poll);
            Loop::cancel($await);
        });

        return $promise;
    }