获取数据库连接对象

@param   string  $connection_name    连接名
@return  \Phalcon\Db\Adapter\Pdo\Mysql|\Phalcon\Db\Adapter\Pdo\Oracle|\Phalcon\Db\Adapter\Pdo\Postgresql|\Phalcon\Db\Adapter\Pdo\Sqlite
@throws  \ErrorException
422488
public static function getConnection(string $connection_name = '')
    {
        if (self::$conn_list === null) {
            self::initConnection();
        }

        if (! isset(self::$conn_list[$connection_name])) {
            $debug_msg = "数据库链接 - '$connection_name' 没有定义！" . StackTrace::getCode(3);
            throw new \InvalidArgumentException($debug_msg);
        }

        return self::connect($connection_name);
    }
428579
public static function clear_cache($table_name = null, $connection_name = self::DEFAULT_CONNECTION)
        {
            self::$_query_cache = [];

            if(isset(self::$_config[$connection_name]['clear_cache']) && is_callable(self::$_config[$connection_name]['clear_cache'])){
                return call_user_func_array(self::$_config[$connection_name]['clear_cache'], array($table_name, $connection_name));
            }
        }
380933
public function connectionType($which_connection='')
    {
        if ($which_connection == '') {
            $which_connection=$this->default_db;
        }
        if ($this->isConnected($which_connection)) {
            $reflect = new \ReflectionClass($this->connections[$which_connection]);
            if (substr($reflect->name, 0, 6) == 'ADODB_') {
                return substr($reflect->name, 6);
            }
        }

        return 'unknown';
    }
1204478
final protected function getDbConnector($resource_name = 'db.default', $prefix = '')
    {
        if (!$this->di->exists($resource_name)) {
            Throw new ModelException(sprintf('A database service with name "%s" ist not registered', $resource_name));
        }

        /* @var $db Db */
        $db = $this->di->get($resource_name);

        if ($prefix) {
            $db->setPrefix($prefix);
        }

        if (!empty($this->scheme)) {
            $db->setScheme($this->scheme);
        }

        return $db;
    }
859934
public function getConnection($name = null, $writeable = false)
    {
        $name = $name ? : $this->default;

        if ($writeable) {
            $config = $this->getDbConfig($name, true);
        } else {
            $config = $this->getDbConfig($name);
        }

        if (!isset($this->pools[$config['id']])) {
            $this->pools[$config['id']] = new \SplQueue;
        }
        $connection = $this->pools[$config['id']]->isEmpty() ? null : $this->pools[$config['id']]->shift();
        if (!$connection) {
            if (!$this->isTaskWorker) {
                $connection = new Connection\CoroutineMySQL();
                $connection->connect([
                    'host' => $config['host'],
                    'port' => $config['port'],
                    'user' => $config['user'],
                    'password' => $config['password'],
                    'database' => $config['database'],
                ]);

                if (!$connection->connected) {
                    throw new Exception("数据库连接失败:{$config['user']}@{$config['host']}:{$config['port']}/{$config['database']} " . $connection->error, $connection->errno);
                }
            } else {

                $connection = new Connection\MySQL();
                $connection->connect([
                    'host' => $config['host'],
                    'port' => $config['port'],
                    'user' => $config['user'],
                    'password' => $config['password'],
                    'database' => $config['database'],
                ]);

                if (!$connection->connected) {
                    throw new Exception("数据库连接失败:{$config['user']}@{$config['host']}:{$config['port']}/{$config['database']} " . $connection->error, $connection->errno);
                }
            }

            $connection->setId($config['id']);
            $connection->setName($name);
            $connection->setWriteable($writeable);

        }

        return new Connection($this, $connection, $this->getStructure($name));
    }
56681
public function getConnection($connection, $server = null)
    {
        $connectionKey = $this->credentials->sanitizeConnection($connection, $server);
        $handle = $connectionKey->toHandle();

        $connections = $this->getConnections();
        if (!$connections->has($handle)) {
            throw new ConnectionException('Invalid connection: '.$handle);
        }

        return $connections[$handle];
    }
31526
protected function getMySQLDatabaseByName($databases, $database_name)
    {
        $database_found = collect($databases)->filter(function ($database) use ($database_name) {
            return $database['name'] === $database_name;
        })->first();

        if ($database_found) {
            return $database_found;
        }
        return null;
    }
62637
private static function connect($connection_name) {
		if (array_key_exists($connection_name, self::$connections)) {
			return self::$connections[$connection_name];
		}

		if (!array_key_exists($connection_name, self::$parameters)) {
			throw new RuntimeException('Connection "' . $connection_name . '" has not been set');
		}

		$conn = DABLPDO::connect(self::$parameters[$connection_name]);
		return (self::$connections[$connection_name] = $conn);
	}
197197
public function temporaryTable($name, $source_table, $which_connection='')
    {
        $which_connection = $which_connection === '' ? $this->default_db : $which_connection;
        $adapter = $this->getAdapter($this->connectionType($which_connection));
        $query = $adapter->temporaryTable($name, $source_table);
        $created = $this->query($query, $which_connection);
        return $created ? $name : false;
    }
443726
public static function connection($name = 'default')
    {
        $databaseConfig = self::getConnectionConfiguration($name);

        /** @var Driver $driver */
        $driver = self::driver($name);

        $username = isset($databaseConfig['username']) ? $databaseConfig['username'] : null;
        $password = isset($databaseConfig['password']) ? $databaseConfig['password'] : null;
        $options = isset($databaseConfig['options']) ? $databaseConfig['options'] : array();

        // Create connection if we don't have it already
        if (! isset(self::$connections[$name])) {
            $connection = $driver->connect($databaseConfig, $username, $password, $options);

            self::$connections[$name] = $connection;
        }

        return self::$connections[$name];
    }
1251032
public function getConnection($name = ''): QueryBuilderInterface
	{
		// If the parameter is a string, use it as an array index
		if (is_scalar($name) && isset($this->connections[$name]))
		{
			return $this->connections[$name];
		}
		else if (empty($name) && ! empty($this->connections)) // Otherwise, return the last one
		{
			return end($this->connections);
		}

		// You should actually connect before trying to get a connection...
		throw new InvalidArgumentException('The specified connection does not exist');
	}
757706
public function getConnection($name = null) {
        if (is_null($name)) {
            $name = $this->defaultConnectionName;
        }

        if (isset($this->connectionMap[$name])) {
            return $this->connectionMap[$name];
        }

        if (!isset($this->connectionConfigs[$name])) {
            throw new SqlException("未定义的数据库连接，连接名称：{$name}");
        }

        $connConfig = $this->connectionConfigs[$name];
        $conn = $this->buildConnection($connConfig);

        $this->connectionMap[$name] = $conn;
        return $conn;
    }
1011449
public static function connection($name)
    {
        if (self::$conn_list === null) {
            self::init();
        }

        $name = strval($name);

        if (! isset(self::$conn_list[$name])) {
            throw new \InvalidArgumentException("找不到连接名为'{$name}'的Redis配置！请检查配置项'database.redis'");
        }

        return self::getConnection($name);
    }
924834
public function acquire( $name = 'db' )
	{
		try
		{
			$adapter = $this->_config->get( 'resource/' . $name . '/adapter', 'mysql' );

			if( !isset( $this->_connections[$name] ) || empty( $this->_connections[$name] ) )
			{
				if( !isset( $this->_count[$name] ) ) {
					$this->_count[$name] = 0;
				}

				$limit = $this->_config->get( 'resource/' . $name . '/limit', -1 );

				if( $limit >= 0 && $this->_count[$name] >= $limit ) {
					throw new MW_DB_Exception( sprintf( 'Maximum number of connections (%1$d) exceeded', $limit ) );
				}

				$this->_connections[$name] = array( $this->_createConnection( $name, $adapter ) );
				$this->_count[$name]++;
			}

			switch( $adapter )
			{
				case 'sqlite':
				case 'sqlite3':
					// SQLite uses page locking which prevents a second connection from
					// reading from tables which are already in use. Fortunately, it is
					// possible withing the same connection to do the update.
					return $this->_connections[$name][0];
			}

			return array_pop( $this->_connections[$name] );

		}
		catch( PDOException $e ) {
			throw new MW_DB_Exception( $e->getMessage(), $e->getCode(), $e->errorInfo );
		}
	}
1087612
public final function open() : Connection
   {

      if ( $this->isOpen() )
      {
         return $this;
      }

      $attrSupport       = $this->_driver->getAttributeSupport();
      $definedAttributes = $this->_driver->getDefinedAttributes();


      $dsn  = $this->_driver->getType() . ':';
      $dsnC = 0;
      $user = null;
      $pass = null;
      $sql  = [];
      $opts = [];

      foreach( $definedAttributes as $attrName => $attrValue )
      {

         $attrDesc = $attrSupport->get( $attrName );

         if ( null === $attrDesc ) { continue; }

         switch ( $attrDesc->getType() )
         {

            case Type::DSN_PART:
               if ( $dsnC < 1 )
               {
                  $dsnC++;
               }
               else
               {
                  $dsn .= $attrSupport->getDSNAttributeSeparator();
               }
               if ( $attrDesc->useNameInDSN() )
               {
                  $dsn .= $attrName . $attrSupport->getDSNKeyValueSeparator();
               }
               $dsn .= $attrValue;
               break;

            case Type::USERNAME_PARAM:
               $user = $attrValue;
               break;

            case Type::PASSWORD_PARAM:
               $pass = $attrValue;
               break;

            case Type::OPTION_PARAM:
               $opts[ $attrName ] = $attrValue;
               break;

            #case Type::INIT_SQL:
            default:
               if ( 'charset' === $attrName )
               {
                  $sql[] = 'SET NAMES ' . $attrValue;
                  break;
               }
               $sql[] = $attrValue;
               break;

         }

      }

      try
      {
         if ( ! isset( $opts[ \PDO::ATTR_ERRMODE ] ) )
         {
            $opts[ \PDO::ATTR_ERRMODE ] = \PDO::ERRMODE_EXCEPTION;
         }
         if ( $this->_driver->getType() === 'sqlite' || ( null === $user && null === $pass ) )
         {
            $this->_pdo = new \PDO( $dsn, null, null, $opts );
         }
         else
         {
            $this->_pdo = new \PDO( $dsn, $user, $pass, $opts );
         }
      }
      catch ( \Throwable $ex )
      {
         throw new ConnectionException( $this->_driver, 'Connection init fails!', 256, $ex );
      }

      if ( 0 < \count( $sql ) )
      {

         foreach ( $sql as $sqlString )
         {
            try { $this->_pdo->exec( $sqlString ); }
            catch ( \Throwable $ex )
            {
               throw new QueryException(
                  $this->_driver, $sqlString, [], 'Can not call the initial query!', 256, $ex
               );
            }
         }

      }

      return $this;

   }
1191307
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
	{
		if (!function_exists('sybase_connect')) return null;

		// Sybase connection on custom port
		if ($this->port) {
			$argHostname .= ':' . $this->port;
		}

		if ($this->charSet) {
			$this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword, $this->charSet);
		} else {
			$this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword);
		}

		if ($this->_connectionID === false) return false;
		if ($argDatabasename) return $this->SelectDB($argDatabasename);
		return true;
	}
1082667
private function realColumnAttribute($column_name)
	{
		if($this->pdo->options[LikePDO::ATTR_CASE] == LikePDO::CASE_LOWER)
			return strtolower($column_name);
		elseif($this->pdo->options[LikePDO::ATTR_CASE] == LikePDO::CASE_UPPER)
			return strtoupper($column_name);
		else
			return $column_name;
	}