连接数据库

@param string $db rlink/wlink
@param bool $reConnect 是否重连--用于某些db如mysql.长连接被服务端断开的情况

@return bool|false|mixed|resource
551306
protected function connectDb($db, $reConnect = false)
    {
        if ($db == 'rlink') {
            //如果没有指定从数据库，则使用 master
            if (empty($this->conf['slaves'])) {
                self::$dbInst[$db] = $this->rlink = $reConnect ? $this->connectDb('wlink', true) : $this->wlink;
                return $this->rlink;
            }

            $n = mt_rand(0, count($this->conf['slaves']) - 1);
            $conf = $this->conf['slaves'][$n];
            empty($conf['engine']) && $conf['engine'] = '';
            self::$dbInst[$db] = $this->rlink = $this->connect(
                $conf['host'],
                $conf['username'],
                $conf['password'],
                $conf['dbname'],
                $conf['charset'],
                $conf['engine'],
                $conf['pconnect']
            );
            return $this->rlink;
        } elseif ($db == 'wlink') {
            $conf = $this->conf['master'];
            empty($conf['engine']) && $conf['engine'] = '';
            self::$dbInst[$db] = $this->wlink = $this->connect(
                $conf['host'],
                $conf['username'],
                $conf['password'],
                $conf['dbname'],
                $conf['charset'],
                $conf['engine'],
                $conf['pconnect']
            );
            return $this->wlink;
        }
        return false;
    }
172928
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$newconnect=false)
	{
		if (!function_exists('mssql_pconnect')) return null;
		$this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword,$newconnect);
		if ($this->_connectionID === false) return false;
		if ($argDatabasename) return $this->SelectDB($argDatabasename);
		return true;
	}
1006100
@Override
	public synchronized boolean reconnect() {
		logger.debug("reconnect() called");
		try {
			callbackRegistry.acceptConnectionStateChange(BitfinexConnectionStateEnum.RECONNECTION_INIT);
			websocketEndpoint.close();

			permissions = BitfinexApiKeyPermissions.NO_PERMISSIONS;
			authenticated = false;
			sequenceNumberAuditor.reset();
			connectionFeatureManager.setActiveConnectionFeatures(0);

			// Invalidate old data
			quoteManager.invalidateTickerHeartbeat();
			orderManager.clear();
			positionManager.clear();

			final CountDownLatch connectionReadyLatch = new CountDownLatch(4);

			final Closeable authSuccessEventCallback = callbackRegistry.onAuthenticationSuccessEvent(c -> {
				permissions = c.getPermissions();
				authenticated = true;
				connectionReadyLatch.countDown();
			});
			final Closeable authFailedCallback = callbackRegistry.onAuthenticationFailedEvent(c -> {
				permissions = c.getPermissions();
				authenticated = false;
				while (connectionReadyLatch.getCount() != 0) {
					connectionReadyLatch.countDown();
				}
			});
			
			final Closeable positionInitCallback = callbackRegistry.onMyPositionEvent((a, p) -> connectionReadyLatch.countDown());
			final Closeable walletsInitCallback = callbackRegistry.onMyWalletEvent((a, w) -> connectionReadyLatch.countDown());
			final Closeable orderInitCallback = callbackRegistry.onMySubmittedOrderEvent((a, o) -> connectionReadyLatch.countDown());

			// Reset account info handler
			setupDefaultAccountInfoHandler();

			websocketEndpoint.connect();

			connectionFeatureManager.applyConnectionFeatures();
			if( configuration.isAuthenticationEnabled()) {
				authenticateAndWait(connectionReadyLatch);
			}
			authSuccessEventCallback.close();
			authFailedCallback.close();
			positionInitCallback.close();
			walletsInitCallback.close();
			orderInitCallback.close();

			resubscribeChannels();

			updateConnectionHeartbeat();
			callbackRegistry.acceptConnectionStateChange(BitfinexConnectionStateEnum.RECONNECTION_SUCCESS);
			return true;
		} catch (final Exception e) {
			logger.error("Got exception while reconnect", e);
			websocketEndpoint.close();
			callbackRegistry.acceptConnectionStateChange(BitfinexConnectionStateEnum.RECONNECTION_FAILED);
			return false;
		}
	}
364105
protected function connectToServer($retObj)
    {
        $servers = $this->servers;
        //循环连接
        while (count($servers) > 0)
        {
            $svr = $this->getServer($servers);
            if (empty($svr))
            {
                return false;
            }
            $this->validConnection($servers);
            $socket = $this->getConnection($svr['host'], $svr['port']);
            //连接失败，服务器节点不可用
            //TODO 如果连接失败，需要上报机器存活状态
            if ($socket === false)
            {
                foreach($servers as $k => $v)
                {
                    if ($v['host'] == $svr['host'] and $v['port'] == $svr['port'])
                    {
                        //从Server列表中移除
                        unset($servers[$k]);
                    }
                }
                if ($this->keepSocket)
                {
                    //若连接失败，则清除掉该server
                    $this->keepSocketServer = array();
                }
            }
            else
            {
                $retObj->socket = $socket;
                $retObj->server_host = $svr['host'];
                $retObj->server_port = $svr['port'];
                return true;
            }
        }
        return false;
    }
456115
function reconnect()
    {
        // Connect to MySQL
        // $this->db = new \mysqli($this->config['host'], $this->config['user'], $this->config['password'], $this->config['dbname'], $this->config['port']);
        $db = \mysqli_init();
        if ( !$db->options(MYSQLI_OPT_CONNECT_TIMEOUT, $this->config['timeout']) ) {
            \throw_error('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed', $db->errno);
        }

        if ( !$db->real_connect($this->config['host'], $this->config['user'], $this->config['password'], $this->config['dbname'], $this->config['port']) ) {
            \throw_error('Can not real_connect to MySQL server, message: ' . $db->connect_error);
        }

        if ($db->connect_errno) {
            \throw_error('Can not connect to MySQL server, message: ' . $db->connect_error, $db->errno);
        }

        // Set charset
        $db->set_charset(isset($this->config['charset']));

        $this->db = $db;
    }
1118185
public function map($linkTableName, $relation, $fields = '*', $where = []): Row
    {
        // 生成关联表模型对象
        $table = $this->makeTable($linkTableName);

        // 生成本表关联字段与关联表关联字段
        list ($field, $linkField) = $this->relation($relation);

        // 如果本表关联字段不存在
        if (!array_key_exists($field, $this->data)) {
            return $this;
        }

        // 生成本表关联字段的所有值
        $key = $this->data[$field];

        if (is_null($key)) {
            $linkRow = false;
        } else {
            // 生成关联表查询条件
            $where[$linkField] = $key;

            // 关联表查询结果
            $linkRow = $table->row($this->append($fields, $linkField), $where);
        }

        // 如果未能对应
        if (!$linkRow) {
            $fields = $this->table->createFields($fields);
            $this->data = $this->appendNull($this->data, $fields);
            return $this;
        }

        // 这里是对应的数据
        $linkRow = $linkRow->toArray();

        // 处理每一个关联的字段
        foreach ($linkRow as $k => $v) {
            // 如果本表已经有此字段,则不扩展
            if (!array_key_exists($k, $this->data)) {
                $this->data[$k] = $v;
            }
        }

        return $this;
    }
712920
public static function decode($recv_buffer, TcpConnection $connection)
    {
        // 初始化
        Base::getLog()->debug(__METHOD__ . ' clean global variables');
        $_POST = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES = [];
        $GLOBALS['HTTP_RAW_POST_DATA'] = '';

        $userInfo = posix_getpwuid(posix_getuid());
        $_SERVER = [
            'USER'                 => Arr::get($userInfo, 'name', ''),
            'HOME'                 => '',
            'QUERY_STRING'         => '',
            'REQUEST_METHOD'       => '',
            'REQUEST_URI'          => '',
            'SERVER_PROTOCOL'      => '',
            'SERVER_SOFTWARE'      => 'tourze/' . Base::VERSION,
            'SERVER_NAME'          => '',
            'SCRIPT_FILENAME'      => '',
            'HTTP_HOST'            => '',
            'HTTP_USER_AGENT'      => '',
            'HTTP_ACCEPT'          => '',
            'HTTP_ACCEPT_LANGUAGE' => '',
            'HTTP_ACCEPT_ENCODING' => '',
            'HTTP_COOKIE'          => '',
            'HTTP_CONNECTION'      => '',
            'REMOTE_ADDR'          => '',
            'REMOTE_PORT'          => '0',
            'REQUEST_TIME'         => time(),
        ];
        $_SERVER['REQUEST_TIME_FLOAT'] = $_SERVER['REQUEST_TIME'] . substr((string) microtime(), 1, 5);

        Base::getLog()->debug(__METHOD__ . ' clean previous headers');
        // 清空上次的数据
        HttpCache::$header = ['Connection: keep-alive'];
        HttpCache::$instance = new HttpCache();

        // 将header分割成数组
        list($httpHeader, $httpBody) = explode("\r\n\r\n", $recv_buffer, 2);
        $headerData = explode("\r\n", $httpHeader);

        // 第一行为比较重要的一行
        $firstLine = array_shift($headerData);
        list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ', $firstLine);
        $_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['DOCUMENT_URI'] = $_SERVER['REQUEST_URI'];
        Base::getLog()->debug(__METHOD__ . ' receive http request', [
            'method'   => $_SERVER['REQUEST_METHOD'],
            'uri'      => $_SERVER['REQUEST_URI'],
            'protocol' => $_SERVER['SERVER_PROTOCOL'],
        ]);

        $httpPostBoundary = '';
        foreach ($headerData as $content)
        {
            // \r\n\r\n
            if (empty($content))
            {
                continue;
            }
            list($key, $value) = explode(':', $content, 2);
            $key = strtolower($key);
            $value = trim($value);
            switch ($key)
            {
                // HTTP_HOST
                case 'host':
                    $_SERVER['HTTP_HOST'] = $value;
                    $tmp = explode(':', $value);
                    $_SERVER['SERVER_NAME'] = $tmp[0];
                    if (isset($tmp[1]))
                    {
                        $_SERVER['SERVER_PORT'] = $tmp[1];
                    }
                    break;
                // cookie
                case 'cookie':
                    $_SERVER['HTTP_COOKIE'] = $value;
                    parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
                    break;
                // user-agent
                case 'user-agent':
                    $_SERVER['HTTP_USER_AGENT'] = $value;
                    break;
                // accept
                case 'accept':
                    $_SERVER['HTTP_ACCEPT'] = $value;
                    break;
                // accept-language
                case 'accept-language':
                    $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $value;
                    break;
                // accept-encoding
                case 'accept-encoding':
                    $_SERVER['HTTP_ACCEPT_ENCODING'] = $value;
                    break;
                // connection
                case 'connection':
                    $_SERVER['HTTP_CONNECTION'] = $value;
                    break;
                case 'referer':
                    $_SERVER['HTTP_REFERER'] = $value;
                    break;
                case 'if-modified-since':
                    $_SERVER['HTTP_IF_MODIFIED_SINCE'] = $value;
                    break;
                case 'if-none-match':
                    $_SERVER['HTTP_IF_NONE_MATCH'] = $value;
                    break;
                case 'content-type':
                    if ( ! preg_match('/boundary="?(\S+)"?/', $value, $match))
                    {
                        $_SERVER['CONTENT_TYPE'] = $value;
                    }
                    else
                    {
                        $_SERVER['CONTENT_TYPE'] = 'multipart/form-data';
                        $httpPostBoundary = '--' . $match[1];
                    }
                    break;
            }
        }

        // 需要解析$_POST
        if ($_SERVER['REQUEST_METHOD'] === 'POST')
        {
            if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] === 'multipart/form-data')
            {
                self::parseUploadFiles($httpBody, $httpPostBoundary);
            }
            else
            {
                parse_str($httpBody, $_POST);
                $GLOBALS['HTTP_RAW_POST_DATA'] = $httpBody;
            }
        }

        // QUERY_STRING
        $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
        if ($_SERVER['QUERY_STRING'])
        {
            // $GET
            parse_str($_SERVER['QUERY_STRING'], $_GET);
        }
        else
        {
            $_SERVER['QUERY_STRING'] = '';
        }

        // REQUEST
        $_REQUEST = array_merge($_GET, $_POST);

        // REMOTE_ADDR REMOTE_PORT
        $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
        $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();

        // 这两处要怎么读取呢？
        $_SERVER['SERVER_ADDR'] = null;
        $_SERVER['SERVER_PORT'] = null;

        $result = [
            'get'    => $_GET,
            'post'   => $_POST,
            'cookie' => $_COOKIE,
            'server' => $_SERVER,
            'files'  => $_FILES,
        ];
        Base::getLog()->debug(__METHOD__ . ' get request data', $result);
        return $result;
    }
723907
def reconnect(self, exc=None):
        """"""
        # Reset protocol binding before starting reconnect
        self.protocol = None

        if not self.closing:
            log.warning('disconnected from Rflink, reconnecting')
            self.loop.create_task(self.connect())
240988
public void reconnect() throws SQLException {
    SearchFilter filter;
    boolean inTransaction = false;
    if (currentReadOnlyAsked) {
      filter = new SearchFilter(true, true);
    } else {
      inTransaction = masterProtocol != null && masterProtocol.inTransaction();
      filter = new SearchFilter(true, urlParser.getOptions().failOnReadOnly);
    }
    reconnectFailedConnection(filter);
    handleFailLoop();
    if (inTransaction) {
      throw new ReconnectDuringTransactionException(
          "Connection reconnect automatically during an active transaction", 1401, "25S03");
    }
  }
1232292
public function db_connect($persistent = FALSE)
	{
		return ($persistent === TRUE)
			? odbc_pconnect($this->dsn, $this->username, $this->password)
			: odbc_connect($this->dsn, $this->username, $this->password);
	}
1159020
public function db_connect($persistent = FALSE)
	{
		$error = NULL;
		$conn_id = ($persistent === TRUE)
			? sqlite_popen($this->database, 0666, $error)
			: sqlite_open($this->database, 0666, $error);

		isset($error);

		return $conn_id;
	}
695077
public function connect($host, $username, $password, $dbName, $charset = 'utf8', $engine = '', $pConnect = false)
    {
        $link = '';
        try {
            $host = explode(':', $host);
            if (substr($host[0], 0, 11) === 'unix_socket') {
                $dsn = "mysql:dbname={$dbName};unix_socket=" . substr($host[0], 12);
            } else {
                $dsn = "mysql:host={$host[0]};" . (isset($host[1]) ? "port={$host[1]};" : '') . "dbname={$dbName}";
            }

            if ($pConnect) {
                $link = new \PDO($dsn, $username, $password, [
                    \PDO::ATTR_PERSISTENT => true,
                    \PDO::ATTR_EMULATE_PREPARES => false,
                    \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset"
                ]);
            } else {
                $link = new \PDO($dsn, $username, $password, [
                    \PDO::ATTR_EMULATE_PREPARES => false,
                    \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset"
                ]);
            }
        } catch (\PDOException $e) {
            throw new PdoConnectException(
                'Pdo Connect Error! ｛' .
                $host[0] . (isset($host[1]) ? ':' . $host[1] : '') . ', ' . $dbName .
                '} Code:' . $e->getCode() . ', ErrorInfo!:' . $e->getMessage(),
                0,
                $e
            );
        }
        //$link->exec("SET names $charset");
        isset($this->conf['sql_mode']) && $link->exec('set sql_mode="' . $this->conf['sql_mode'] . '";'); //放数据库配 特殊情况才开
        if (!empty($engine) && $engine == 'InnoDB') {
            $link->exec('SET innodb_flush_log_at_trx_commit=2');
        }
        return $link;
    }
477197
public static function connectDatabase(array $connectInfo): \PDO
    {
        // 连接句柄,会话内缓存
        static $connects = [];

        // 连接句柄的最后使用时间(用来控制过期)
        static $lastTime = [];

        //如果切换了进程,则清除全部连接缓存
        if (!isWindows() and function_exists('posix_getpid') and self::$processId != posix_getpid()) {
            $connects = [];
            $lastTime = [];
            self::$processId = posix_getpid();
        }

        // 数据库服务器的IP或域名
        $host = $connectInfo['host'];

        // 数据库服务器的端口号
        if (isset($connectInfo['port'])) {
            $port = $connectInfo['port'];
        } else {
            $port = '3306';
        }

        // 数据库用户的账号
        $user = $connectInfo['user'];

        // 数据库用户的密码
        $pass = $connectInfo['password'];

        // 数据库名称
        $database = $connectInfo['database'];

        // 数组的键
        $key = serialize([
            'host' => $host,
            'port' => $port,
            'name' => $database
        ]);

        // 取连接句柄的过期时间(秒)
        $timeout = configDefault(10, 'system', 'database_timeout');

//        // 如果 过期,则删除,否则 会出错误
//        if (isset($lastTime[$key]) and time() - $lastTime[$key] > $timeout) {
//            unset($lastTime[$key]);
//            unset($connects[$key]);
//        }
//
//        // 如果此连接已经存在,直接返回句柄
//        if (isset($connects[$key])) {
//            // 记录此句柄的最后使用时间
//            $lastTime[$key] = time();
//            return $connects[$key];
//        }

        // 记录开始时间
        $start = timeLog();

        try {
            // 连接指定数据库
            $connect = new \PDO("mysql:host=$host;dbname=$database;port=$port", $user, $pass, [
                // 使用缓存
                \PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,

                // 大小写有区别
                \PDO::ATTR_CASE => \PDO::CASE_NATURAL,

                // 有错抛出异常,而不是返回错误码
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,

                // 数值不要自动 转换成字符串
                \PDO::ATTR_STRINGIFY_FETCHES => false,

                // 不要在本地模拟Prepare
                \PDO::ATTR_EMULATE_PREPARES => false,

                // 自动提交,必须自动提交,否则 就需要显式Commit,否则 必然会丢失数据
                \PDO::ATTR_AUTOCOMMIT => true,

                // 超时,30秒
                \PDO::ATTR_TIMEOUT => $timeout
            ]);
        } catch (\PDOException $e) {
            trigger_error('数据库连接失败:' . $database . '@' . $host . ':' . $port, E_USER_ERROR);
        }

        // 设置一些必要的连接属性
        // 禁用preparedStatements的仿真效果
        $connect->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);

        $connect->exec("SET NAMES 'utf8mb4'");

        // 写调试信息
        Debug::setSql("Connect", '', timeLog($start) * 1000, '', "$database at $host:$port");

        // 记录此句柄的最后使用时间
        $lastTime[$key] = time();

        // 保存连接句柄
        $connects[$key] = $connect;

        return $connect;
    }
158186
public function db_connect($persistent = FALSE)
	{
		$this->options[PDO::ATTR_PERSISTENT] = $persistent;

		try
		{
			return new PDO($this->dsn, $this->username, $this->password, $this->options);
		}
		catch (PDOException $e)
		{
			if ($this->db_debug && empty($this->failover))
			{
				$this->display_error($e->getMessage(), '', TRUE);
			}

			return FALSE;
		}
	}
1021223
public function read ($pkValue = FALSE, &$db = FALSE)
	{
		
		try
		{
			
			// If there is a key value passed set it

			if ($pkValue !== FALSE)
			{
				$this->iset (static::$pk, $pkValue);
			}
			
			// Get database slave for read

			if ($db === FALSE)
			{
				$db	=& $this->getDbSlave ();
			}

			// Prepare query

			$query = $db->prepare ('
			SELECT * FROM `' . static::$dbTable . '`
			WHERE ' . static::$pk . ' = :pk
			');

			// Bind paramater

			$query->bindValue (':pk',	$this->iget (static::$pk));

			// Execute

			$query->execute ();

			// Set row

			$row	= $query->fetch (\PDO::FETCH_ASSOC);

			// If no data was returned return FALSE

			if (!$row)
			{
				return FALSE;
			}

			// Set each attribute value

			foreach ($row as $name => $val)
			{

				if ($this->attributeExists ($name))
				{
					$this->iset ($name, $val, FALSE, TRUE);
				}

			}
			
		}
		
		// Set errors as framework messages

		catch (Resource\Parser\Exception $e)
		{
			new Message ('error', $e->getMessage ());
			return FALSE;
		}
		
		// Return TRUE

		return TRUE;
		
	}
1335845
function autoReconnect(options, connectionListener)
{
	var reconnectInterval = getOption(options, 'reconnectInterval', 5000);

	var reconnector = new events.EventEmitter();

	function reconnect()
	{
		var client = connect(options);
		var isReconnecting = false;
		
		function tryReconnecting()
		{
			if ( !isReconnecting )
			{
				isReconnecting = true;
				reconnector.emit('close');
			}
		}

		client.on('connect', () => {
			connectionListener(client);
		});

		client.on('close', () => {
			tryReconnecting();
		});

		client.on('error', (e) => {
			tryReconnecting();
		});
	}

	reconnector.on('close', () => {
		setTimeout(() => reconnector.emit('reconnect'), reconnectInterval);
	});

	reconnector.on('reconnect', () => {
		reconnect();
	});
	
	reconnect();
}
1331975
public function reconnect() {
        $this->dialect = $this->dialect->reset();
        if (!$this->dialect instanceof DatabaseDialect) {
            throw new \Exception('cannot reconnect to the database.');
        }
    }