Opens a connection
@param {{Hostname: string, Port: number, Username: string, Password: string, Database: string}} connection
@returns {PostgreSQL}
188512
function OpenConnection(connection) {
    let base = new pg.Client({
        host: connection.Hostname || 'localhost',
        port: parseInt(connection.Port) || 5432,
        user: connection.Username,
        password: connection.Password,
        database: connection.Database
    });
    base.connect();
    return new PostgreSQL(base);
}
1251911
function connect() {
  log('debug', `Connecting to Postgres at ${POSTGRES_HOST}:${POSTGRES_PORT}`);

  knex = knexLib({
    client: 'pg',
    connection: {
      host: POSTGRES_HOST,
      user: POSTGRES_USER,
      password: POSTGRES_PASSWORD,
      database: POSTGRES_DB,
      port: POSTGRES_PORT
    },
    pool: { min: CONNECTION_POOL_MIN, max: CONNECTION_POOL_MAX }
  });

  // TODO: improve error catch! https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a
  return knex.table('information_schema.tables').first()
    .catch(createDBIfNotExists);
}
1034367
function (queryKey, params, fn) {
    this.connection.query(templates[queryKey], params, function (err, result) {
      if (err) {
        fn(err, null);
      } else {
        fn(null, result.length ? result[0] : null);
      }
    });
  }
1082343
private Connection getConn() {
        Connection connection = localConnection.get();
        return ifNotNullReturn(connection, connection, this.getSql2o().open());
    }
373033
async function createMysqlConnection (connectionParams) {
    // set required defaults 
    connectionParams = _.merge(connectionParams, {
        bigNumberStrings: true,
        dateStrings: true,
        namedPlaceholders: true,
        rowsAsArray: false,
        supportBigNumbers: true,
    })

    return defined(connectionParams.connectionLimit)
        ? MySQL2.createPool(connectionParams)
        : MySQL2.createConnection(connectionParams)
}
905515
function connect() {
      var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var callback = arguments[1];

      this.host = props.host || '127.0.0.1';
      this.port = props.port || 21000;
      this.resultType = props.resultType || null;
      this.timeout = props.timeout || 1000;
      this.transport = props.transport || _thrift2.default.TBufferedTransport;
      this.protocol = props.protocol || _thrift2.default.TBinaryProtocol;
      this.options = {
        transport: this.transport,
        protocol: this.protocol,
        timeout: this.timeout
      };

      var deferred = _thrift.Q.defer();

      var connection = _thrift2.default.createConnection(this.host, this.port, this.options);
      var client = _thrift2.default.createClient(_ImpalaService2.default, connection);

      connection.on('error', ImpalaClient.onErrorDeferred(deferred));

      connection.on('connect', function () {
        deferred.resolve('Connection is established.');
      });

      this.client = client;
      this.connection = connection;

      deferred.promise.nodeify(callback);
      return deferred.promise;
    }
1207383
function open()
    {
        if (!$this->_opened) {
            /* Use the DSN and options to create a database connection. */
            $this->_db = &DB::connect($this->_dsn, $this->_options);
            if (DB::isError($this->_db)) {
                return false;
            }

            /* Create a prepared statement for repeated use in log(). */
            if (!$this->_prepareStatement()) {
                return false;
            }

            /* We now consider out connection open. */
            $this->_opened = true;
        }

        return $this->_opened;
    }
137600
function() {
        if (!this._disconnected) {
            console.log(
                `LocalIndexedDBStoreBackend.connect: already connected or connecting`,
            );
            return Promise.resolve();
        }

        this._disconnected = false;

        console.log(
            `LocalIndexedDBStoreBackend.connect: connecting...`,
        );
        const req = this.indexedDB.open(this._dbName, VERSION);
        req.onupgradeneeded = (ev) => {
            const db = ev.target.result;
            const oldVersion = ev.oldVersion;
            console.log(
                `LocalIndexedDBStoreBackend.connect: upgrading from ${oldVersion}`,
            );
            if (oldVersion < 1) { // The database did not previously exist.
                this._isNewlyCreated = true;
                createDatabase(db);
            }
            if (oldVersion < 2) {
                upgradeSchemaV2(db);
            }
            if (oldVersion < 3) {
                upgradeSchemaV3(db);
            }
            // Expand as needed.
        };

        req.onblocked = () => {
            console.log(
                `can't yet open LocalIndexedDBStoreBackend because it is open elsewhere`,
            );
        };

        console.log(
            `LocalIndexedDBStoreBackend.connect: awaiting connection...`,
        );
        return reqAsEventPromise(req).then((ev) => {
            console.log(
                `LocalIndexedDBStoreBackend.connect: connected`,
            );
            this.db = ev.target.result;

            // add a poorly-named listener for when deleteDatabase is called
            // so we can close our db connections.
            this.db.onversionchange = () => {
                this.db.close();
            };

            return this._init();
        });
    }
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();
          });
        });
    });
  });
}
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);
    }
}
283611
def open_connection(request)
      connection = ConnectionAdapters.establish_connection(request, dispatcher)

      assign_connection_id connection
      register_user_connection connection

      connections[connection.id] = connection

      info "Connection opened: #{connection}"
      connection.rack_response
    end
1309079
function open(method, url, async, username, password) {
    this.method = method;
    this.url = url;
    this.async = typeof async == "boolean" ? async : true;
    this.username = username;
    this.password = password;
    this.responseText = null;
    this.responseXML = null;
    this.responseURL = url;
    this.requestHeaders = {};
    this.sendFlag = false;
    this._readyStateChange(FakeXMLHttpRequest.OPENED);
  }
455615
function connectApp(token) {
  const CONNECTION = new Connection();

  return new Promise((resolve, reject) => {
    CONNECTION.connect(token)
      .then(() => resolve(new ConnectionHandler(CONNECTION)))
      .catch((error) => reject(error));
  });
}
550114
function initConnectionPool() {

  const setting = {
    host            : process.env.LIGHTMYSQL_HOST,
    port            : process.env.LIGHTMYSQL_PORT,
    user            : process.env.LIGHTMYSQL_USER,
    password        : process.env.LIGHTMYSQL_PASS,
    database        : process.env.APPNAME,
    connectionLimit : 10
  };

  console.log('MySQL name: ' + setting.database);
  console.log('MySQL host: ' + setting.host);
  console.log('MySQL port: ' + setting.port);
  console.log('MySQL user: ' + setting.user);
  console.log('MySQL pool: ' + setting.connectionLimit);

  return mysql.createPool(setting);
}
958470
def get_connection(engine, host, user, port, password, database, ssl={}):
    

    if engine == 'mysql':
        # Connection
        return get_mysql_connection(host, user, port, password, database, ssl)
    elif engine == 'postgresql':
        # Connection
        return get_pg_connection(host, user, port, password, database, ssl)
    else:
        raise RuntimeError('`%s` is not a valid engine.' % engine)
417089
function _openClientConnection() {
  _openClientConnection = _asyncToGenerator(
  /*#__PURE__*/
  _regeneratorRuntime.mark(function _callee12(channelName, readerUuid) {
    var pathToSocket, client;
    return _regeneratorRuntime.wrap(function _callee12$(_context12) {
      while (1) {
        switch (_context12.prev = _context12.next) {
          case 0:
            pathToSocket = socketPath(channelName, readerUuid);
            client = new net.Socket();
            return _context12.abrupt("return", new Promise(function (res, rej) {
              client.connect(pathToSocket, function () {
                return res(client);
              });
              client.on('error', function (err) {
                return rej(err);
              });
            }));

          case 3:
          case "end":
            return _context12.stop();
        }
      }
    }, _callee12);
  }));
  return _openClientConnection.apply(this, arguments);
}
1239575
function connect(obj, cb) {
    if (obj.db) {
        return cb();
    }
    if (obj.pending) {
        return setImmediate(function () {
            connect(obj, cb);
        });
    }
    obj.pending = true;

    var url = constructMongoLink(obj.config.name, obj.config.prefix, obj.config.servers, obj.config.URLParam, obj.config.credentials);
    if (!url) {
        return cb(generateError(190));
    }

    mongoSkin.connect(url, obj.config.extraParam, function (err, db) {
        if (err) {
            obj.pending = false;
            return cb(err);
        } else {
            db.on('timeout', function () {
                console.log("Connection To Mongo has timed out!");
                obj.flushDb();
            });
            db.on('close', function () {
                console.log("Connection To Mongo has been closed!");
                obj.flushDb();
            });
            if (obj.db)
                obj.db.close();

            obj.db = db;
            obj.pending = false;
            return cb();
        }
    });

    /**
     *constructMongoLink: is a function that takes the below param and return the URL need to by mongoskin.connect
     *
     * @param dbName
     * @param prefix
     * @param servers
     * @param params
     * @param credentials
     * @returns {*}
     */
    function constructMongoLink(dbName, prefix, servers, params, credentials) {
        if (dbName && Array.isArray(servers)) {
            var url = "mongodb://";
            if (credentials && Object.hasOwnProperty.call(credentials, 'username') && credentials.hasOwnProperty.call(credentials, 'password')) {
                url = url.concat(credentials.username, ':', credentials.password, '@');
            }

            servers.forEach(function (element, index, array) {
                url = url.concat(element.host, ':', element.port, (index === array.length - 1 ? '' : ','));
            });

            url = url.concat('/');
            if (prefix) url = url.concat(prefix);
            url = url.concat(dbName);

            if (params && 'object' === typeof params && Object.keys(params).length) {
                url = url.concat('?');
                for (var i = 0; i < Object.keys(params).length; i++) {
                    url = url.concat(Object.keys(params)[i], '=', params[Object.keys(params)[i]], i === Object.keys(params).length - 1 ? '' : "&");
                }
            }
            return url;
        }
        return null;
    }
}