Check PostgreSQL connection.
963344
def get_pg_info():
    """"""
    from psycopg2 import connect, OperationalError
    log.debug("entered get_pg_info")
    try:
        conf = settings.DATABASES['default']
        database = conf["NAME"]
        user = conf["USER"]
        host = conf["HOST"]
        port = conf["PORT"]
        password = conf["PASSWORD"]
    except (AttributeError, KeyError):
        log.error("No PostgreSQL connection info found in settings.")
        return {"status": NO_CONFIG}
    except TypeError:
        return {"status": DOWN}
    log.debug("got past getting conf")
    try:
        start = datetime.now()
        connection = connect(
            database=database, user=user, host=host,
            port=port, password=password, connect_timeout=TIMEOUT_SECONDS,
        )
        log.debug("at end of context manager")
        micro = (datetime.now() - start).microseconds
        connection.close()
    except (OperationalError, KeyError) as ex:
        log.error("No PostgreSQL connection info found in settings. %s Error: %s",
                  conf, ex)
        return {"status": DOWN}
    log.debug("got to end of postgres check successfully")
    return {"status": UP, "response_microseconds": micro}
1084340
def does_table_exist(self, connection):
        

        if '.' in self.table:
            query = ("select 1 as table_exists "
                     "from information_schema.tables "
                     "where table_schema = lower(%s) and table_name = lower(%s) limit 1")
        else:
            query = ("select 1 as table_exists "
                     "from pg_table_def "
                     "where tablename = lower(%s) limit 1")
        cursor = connection.cursor()
        try:
            cursor.execute(query, tuple(self.table.split('.')))
            result = cursor.fetchone()
            return bool(result)
        finally:
            cursor.close()
538085
def get_pg_connection(host, user, port, password, database, ssl={}):
    

    return psycopg2.connect(host=host,
                            user=user,
                            port=port,
                            password=password,
                            dbname=database,
                            sslmode=ssl.get('sslmode', None),
                            sslcert=ssl.get('sslcert', None),
                            sslkey=ssl.get('sslkey', None),
                            sslrootcert=ssl.get('sslrootcert', None),
                            )
55739
def get_connection(self, key, host, port, user, password, dbname, ssl, connect_fct, tags, use_cached=True):
        """"""
        if key in self.dbs and use_cached:
            return self.dbs[key]

        elif host != "" and user != "":
            try:
                if host == 'localhost' and password == '':
                    # Use ident method
                    connection = connect_fct("user=%s dbname=%s" % (user, dbname))
                elif port != '':
                    connection = connect_fct(
                        host=host, port=port, user=user, password=password, database=dbname, ssl=ssl
                    )
                elif host.startswith('/'):
                    # If the hostname starts with /, it's probably a path
                    # to a UNIX socket. This is similar behaviour to psql
                    connection = connect_fct(unix_sock=host, user=user, password=password, database=dbname)
                else:
                    connection = connect_fct(host=host, user=user, password=password, database=dbname, ssl=ssl)
                self.dbs[key] = connection
                return connection
            except Exception as e:
                message = u'Error establishing postgres connection: %s' % (str(e))
                service_check_tags = self._get_service_check_tags(host, port, tags)
                self.service_check(
                    self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=message
                )
                raise
        else:
            if not host:
                raise ConfigurationError('Please specify a Postgres host to connect to.')
            elif not user:
                raise ConfigurationError('Please specify a user to connect to Postgres as.')
838417
def connections(self):
        """"""
        self._check_session()
        status, data = self._rest.get_request('connections')
        return data
892327
public function check()
    {
        $pdoResult = extension_loaded('PDO');
        $pdoMySqlResult = extension_loaded('pdo_mysql');

        $result = ($pdoResult === true && $pdoMySqlResult === true);

        if ($pdoResult === true) {
            $this->pdoVersion = phpversion('PDO');
        }

        if ($pdoMySqlResult === true) {
            $this->pdoMySqlVersion = phpversion('pdo_mysql');
        }

        return $result;
    }
1185686
def verify_state(self):
        """"""
        if self.state == CONNECTING:
            self.state = OPEN

            self.conn.on_open(self.conn_info)
343095
def check_connection(func):
    """"""
    @wraps(func)
    def with_exception_handling(*args, **kwargs):
        """Wrap function being decorated."""
        try:
            return func(*args, **kwargs)
        except redis.exceptions.ConnectionError:
            raise ConnectionError("Unable to connect to the Redis "
                                  "Configuration Database. host = {}, "
                                  "port = {}, id = {}."
                                  .format(REDIS_HOST, REDIS_PORT,
                                          REDIS_DB_ID))
    return with_exception_handling
587460
def has_connection(cls, pid, connection):
        
        with cls._lock:
            cls._ensure_pool_exists(pid)
            return connection in cls._pools[pid]
678177
private boolean checkConnection() {
		if (connection == null) {
			if (System.currentTimeMillis() >= reconnectTimestamp) {
				long start = System.currentTimeMillis();
				try {
					connection = connect(url, user, password);
					statement = connection.prepareStatement(sql);
					InternalLogger.log(Level.ERROR, "Lost log entries due to broken database connection: " + lostCount);
					lostCount = 0;
					return true;
				} catch (NamingException ex) {
					long now = System.currentTimeMillis();
					reconnectTimestamp = now + Math.max(MIN_RETRY_INTERVAL, (now - start) * 2);
					closeConnectionSilently();
					return false;
				} catch (SQLException ex) {
					long now = System.currentTimeMillis();
					reconnectTimestamp = now + Math.max(MIN_RETRY_INTERVAL, (now - start) * 2);
					closeConnectionSilently();
					return false;
				}
			} else {
				return false;
			}
		} else {
			return true;
		}
	}
772904
def is_connected(self):
        """"""
        self._connected = self._connected and self._conn.is_connected()
        return self._connected
1192032
def ping(self) -> None:
        """"""
        if self.db is None or self.db_pythonlib not in [PYTHONLIB_MYSQLDB,
                                                        PYTHONLIB_PYMYSQL]:
            return
        try:
            self.db.ping(True)  # test connection; reconnect upon failure
            # ... should auto-reconnect; however, it seems to fail the first
            # time, then work the next time.
            # Exception (the first time) is:
            # <class '_mysql_exceptions.OperationalError'>:
            #   (2006, 'MySQL server has gone away')
            # http://mail.python.org/pipermail/python-list/2008-February/
            #        474598.html
        except mysql.OperationalError:  # loss of connection
            self.db = None
            self.connect_to_database_mysql(
                self._database, self._user, self._password, self._server,
                self._port, self._charset, self._use_unicode)
115941
public void checkWaitingConnection() throws SQLException {
    if (isSecondaryHostFail()) {
      proxy.lock.lock();
      try {
        Protocol waitingProtocol = waitNewSecondaryProtocol.getAndSet(null);
        if (waitingProtocol != null && pingSecondaryProtocol(waitingProtocol)) {
          lockAndSwitchSecondary(waitingProtocol);
        }
      } finally {
        proxy.lock.unlock();
      }
    }

    if (isMasterHostFail()) {
      proxy.lock.lock();
      try {
        Protocol waitingProtocol = waitNewMasterProtocol.getAndSet(null);
        if (waitingProtocol != null && pingMasterProtocol(waitingProtocol)) {
          lockAndSwitchMaster(waitingProtocol);
        }
      } finally {
        proxy.lock.unlock();
      }
    }
  }
592937
def is_running(self, port):
        """"""
        try:
            con = self.client('localhost:%s' % port)
            con.admin.command('ping')
            return True
        except (AutoReconnect, ConnectionFailure, OperationFailure):
            # Catch OperationFailure to work around SERVER-31916.
            return False
23877
def _CheckConnectionEncoding(cursor):
  """"""
  cur_character_set = _ReadVariable("character_set_connection", cursor)
  if cur_character_set != CHARACTER_SET:
    raise EncodingEnforcementError(
        "Require MySQL character_set_connection of {}, got {}.".format(
            CHARACTER_SET, cur_character_set))
559940
function runQuery(query, connection) {
  const pgConfig = {
    user: connection.username,
    password: connection.password,
    database: connection.database,
    host: connection.host,
    ssl: connection.postgresSsl,
    stream: createSocksConnection(connection)
  };
  // TODO cache key/cert values
  if (connection.postgresKey && connection.postgresCert) {
    pgConfig.ssl = {
      key: fs.readFileSync(connection.postgresKey),
      cert: fs.readFileSync(connection.postgresCert)
    };
    if (connection.postgresCA) {
      pgConfig.ssl['ca'] = fs.readFileSync(connection.postgresCA);
    }
  }
  if (connection.port) pgConfig.port = connection.port;

  return new Promise((resolve, reject) => {
    const client = new pg.Client(pgConfig);
    client.connect(err => {
      if (err) {
        client.end();
        return reject(err);
      }
      const cursor = client.query(new PgCursor(query));
      return cursor.read(connection.maxRows + 1, (err, rows) => {
        if (err) {
          // pg_cursor can't handle multi-statements at the moment
          // as a work around we'll retry the query the old way, but we lose the maxRows protection
          return client.query(query, (err, result) => {
            client.end();
            if (err) {
              return reject(err);
            }
            return resolve({ rows: result.rows });
          });
        }
        let incomplete = false;
        if (rows.length === connection.maxRows + 1) {
          incomplete = true;
          rows.pop(); // get rid of that extra record. we only get 1 more than the max to see if there would have been more...
        }
        if (err) {
          reject(err);
        } else {
          resolve({ rows, incomplete });
        }
        cursor.close(err => {
          if (err) {
            console.log('error closing pg-cursor:');
            console.log(err);
          }
          // Calling end() without setImmediate causes error within node-pg
          setImmediate(() => {
            client.end(error => {
              if (error) {
                console.error(error);
              }
            });
          });
        });
      });
    });
  });
}
823021
def _database_exists(self):
        
        con = psycopg2.connect(host=self.host, database="postgres",
            user=self.user, password=self.password, port=self.port)
        query_check = "select datname from pg_catalog.pg_database"
        query_check += " where datname = '{0}';".format(self.dbname)
        c = con.cursor()
        c.execute(query_check)
        result = c.fetchall()
        if len(result) > 0:
            return True
        return False