Establishes the connection to the database using the $config array

@param array $config the config array (Startup::getConfig())
555485
public static function startDatabase(&$config) {
		$db = $config ['database'] ?? [ ];
		if ($db ['dbName'] !== '') {
			self::connect ( $db ['type'], $db ['dbName'], $db ['serverName'] ?? '127.0.0.1', $db ['port'] ?? 3306, $db ['user'] ?? 'root', $db ['password'] ?? '', $db ['options'] ?? [ ], $db ['cache'] ?? false);
		}
	}
10065
public function connect(array $config)
    {
        /** @var CouchbaseConnection $connection */
        $connection = $this->connectionResolver->connection($config['driver']);

        return new CouchbaseQueue(
            $connection,
            $config['bucket'],
            $config['queue'],
            Arr::get($config, 'retry_after', 60)
        );
    }
562804
public function connect(array $config, string $name = 'main'): Connection
    {
        if (isset($this->connections[$name])) {
            throw new InvalidArgumentException("Connection [$name] is already configured.");
        }

        $this->connections[$name] = new Connection($config);

        return $this->connections[$name];
    }
500195
public static function setConfig(array $config)
    {
        if ( ! isset($config['connection'])) {
            throw new DbException('can`t find `connection` parameter in database config');
        }
        $connection = &$config['connection'];
        if ( ! isset($connection['default'])) {
            throw new DbException('can`t find `default` parameter in database config');
        }
        $default = &$connection['default'];
        if ( ! is_string($default) || empty($connection[$default])) {
            throw new DbException('parameter `default` must be string and contain contains name of default connection. So given section `' .
                $default .
                '` must present in database config');
        }

        return self::$config = $config;
    }
970711
private function setConfig(array $config = [])
    {
        // Set Api Credentials
        if (function_exists('config')) {
            $this->setApiCredentials(
                config('paypal')
            );
        } elseif (!empty($config)) {
            $this->setApiCredentials($config);
        }

        $this->setRequestData();
    }
438867
public function connect(Array $config)
    {
        $dsn = $this->getDSN($config);
        $options = $this->getOptions($config);

        $connection = $this->createConnection($dsn, $config, $options);

        if (isset($config['charset'])) {
            $connection->prepare("set names '" . $config['charset'] . "'")->execute();
        }

        if (isset($config['timezone'])) {
            $connection->prepare("set time zone '" . $config['timezone'] . "'")->execute();
        }

        return $connection;
    }
738369
public function init($config)
    {
        $this->_initiated = true;
        if ($this->isNewRecord()) {
            $this->_tableName = static::getTableName();
            $this->_db = $this->_db ? $this->_db : static::getDb();
            $this->_columns = static::getDb()->getTableColumns($this->_tableName);
            $this->_pk = static::getDb()->getTablePk($this->_tableName);
        } else {
            if (is_array($this->_pk)) {
                $this->_originalPk = [];
                foreach ($this->_pk as $k) {
                    $this->_originalPk[$k] = $this->_attributes[$k];
                }
            } else {
                $this->_originalPk = $this->_attributes[$this->_pk];
            }
            $this->afterLoad();
        }
        $this->applyRelationsAttributes();
        return parent::init($config);
    }
671960
public function initialize(array $config = []) {
		if (empty($this->_config['fields'])) {
			$schema = $this->getTable()->getSchema();

			$fields = [];
			foreach ($schema->columns() as $field) {
				$v = $schema->getColumn($field);
				if (!in_array($v['type'], ['string', 'text'])) {
					continue;
				}
				if (!empty($v['key'])) {
					continue;
				}
				if (isset($v['length']) && $v['length'] === 1) { // TODO: also skip UUID (lenght 36)?
					continue;
				}
				$fields[] = $field;
			}
			$this->_config['fields'] = $fields;
		}
		if ($this->_config['mergeQuotes'] === true) {
			$this->_config['mergeQuotes'] = '"';
		}
	}
123254
private function __buildConfig(array $config)
    {
        foreach ($config as $key => $conf) {
            if ($key == 'driver') {
                $this->rawConfig['type'] = strtolower($conf);
                continue;
            }

            if (!array_key_exists($key, $this->rawConfig)) {
                $this->error->setMessage(sprintf(
                    "invalid config '%s', allowed config are: %s",
                    $key, implode(', ', array_keys($this->rawConfig))
                ));
                break;
            }

            $this->rawConfig[$key] = $conf;
        }

        if (!$this->error->hasError() && !$this->hasDriver($this->getType()) && !$this->preventNoLocalDriver) {
            $this->error->setMessage(sprintf(
                "Driver '%s' not available. Please choose one of: '%s'. ".
                'Or register new ConnectionString class by implements %s.',
                $this->getType(),
                implode("', '", $this->getAvailableDrivers()),
                ConnectionStringInterface::class
            ));
        }
    }
434524
protected function checkConfig(array $config): void
    {
        foreach (['host', 'username', 'password', 'database', 'persistent'] as $key) {
            if (!isset($config[$key])) {
                $class = get_class($this);
                throw new ConfigException("Missing configuration key={$key} in {$class}");
            }
        }
    }
750526
public function init(array $config = [])
    {
        $config = $config ?: $this->config;

        $isDoStart = false;
        if (isset($config['use_trans_sid'])) {
            ini_set('session.use_trans_sid', $config['use_trans_sid'] ? 1 : 0);
        }

        // 启动session
        if (!empty($config['auto_start']) && PHP_SESSION_ACTIVE != session_status()) {
            ini_set('session.auto_start', 0);
            $isDoStart = true;
        }

        if (isset($config['prefix'])) {
            $this->prefix = $config['prefix'];
        }

        if (isset($config['use_lock'])) {
            $this->lock = $config['use_lock'];
        }

        if (isset($config['var_session_id']) && isset($_REQUEST[$config['var_session_id']])) {
            session_id($_REQUEST[$config['var_session_id']]);
        } elseif (isset($config['id']) && !empty($config['id'])) {
            session_id($config['id']);
        } else {
            session_id(WorkerHttp::sessionId());
        }

        if (isset($config['name'])) {
            WorkerHttp::sessionName($config['name']);
        }

        if (isset($config['path'])) {
            WorkerHttp::sessionSavePath($config['path']);
        }

        if (isset($config['domain'])) {
            ini_set('session.cookie_domain', $config['domain']);
        }

        if (isset($config['expire'])) {
            ini_set('session.gc_maxlifetime', $config['expire']);
            ini_set('session.cookie_lifetime', $config['expire']);
        }

        if (isset($config['secure'])) {
            ini_set('session.cookie_secure', $config['secure']);
        }

        if (isset($config['httponly'])) {
            ini_set('session.cookie_httponly', $config['httponly']);
        }

        if (isset($config['use_cookies'])) {
            ini_set('session.use_cookies', $config['use_cookies'] ? 1 : 0);
        }

        if (isset($config['cache_limiter'])) {
            session_cache_limiter($config['cache_limiter']);
        }

        if (isset($config['cache_expire'])) {
            session_cache_expire($config['cache_expire']);
        }

        if (!empty($config['type'])) {
            // 读取session驱动
            $class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\session\\driver\\' . ucwords($config['type']);

            // 检查驱动类
            if (!class_exists($class) || !session_set_save_handler(new $class($config))) {
                throw new ClassNotFoundException('error session handler:' . $class, $class);
            }
        }

        if ($isDoStart) {
            $this->start();
        } else {
            $this->init = false;
        }

        return $this;
    }
752592
protected function loadConfig(array $config)
    {
        $this->config = $config;
        if (array_key_exists('namespaces', $config)) {
            $this->ns = $config['namespaces'];
        }

        $this->defaultContext = $this->getMandatoryKey('defaultContext', $config);

        foreach ($this->getMandatoryKey('data_sources', $config) as $source => $c) {
            if (!array_key_exists('type', $c)) {
                throw new \Tripod\Exceptions\ConfigException("No 'type' set for data source $source");
            }
            if (!array_key_exists('connection', $c)) {
                throw new \Tripod\Exceptions\ConfigException("No connection information set for data source $source");
            }
            $this->dataSources[$source] = $c;
        }

        $transactionConfig = $this->getMandatoryKey('transaction_log', $config);
        $this->tConfig['data_source'] = $this->getMandatoryKey('data_source', $transactionConfig, 'transaction_log');
        if (!isset($this->dataSources[$this->tConfig['data_source']])) {
            throw new \Tripod\Exceptions\ConfigException("Transaction log data source, " . $this->tConfig['data_source'] . ", was not defined");
        }
        $this->tConfig["database"] = $this->getMandatoryKey("database", $transactionConfig, 'transaction_log');
        $this->tConfig["collection"] = $this->getMandatoryKey("collection", $transactionConfig, 'transaction_log');

        // A 'pod' corresponds to a logical database
        $this->databases = $this->getMandatoryKey("stores", $config);
        $defaultDB = null;
        foreach ($this->databases as $storeName => $storeConfig) {
            $this->dbConfig[$storeName] = ["data_source" => $this->getMandatoryKey("data_source", $storeConfig)];
            if (isset($storeConfig['database']) && !empty($storeConfig['database'])) {
                $this->dbConfig[$storeName]["database"]=$storeConfig['database'];
            } else {
                $this->dbConfig[$storeName]["database"] = $storeName;
            }

            $this->cardinality[$storeName] = [];
            $this->indexes[$storeName] = [];
            $this->podConnections[$storeName] = [];
            if (isset($storeConfig["pods"])) {
                foreach ($storeConfig["pods"] as $podName => $podConfig) {
                    $dataSource = (isset($podConfig['data_source']) ? $podConfig['data_source'] : $storeConfig['data_source']);
                    $this->podConnections[$storeName][$podName] = $dataSource;

                    // Set cardinality, also checking against defined namespaces
                    if (array_key_exists('cardinality', $podConfig)) {
                        // Test that the namespace exists for each cardinality rule defined
                        $cardinality = $podConfig['cardinality'];
                        foreach ($cardinality as $qname => $cardinalityValue) {
                            $namespaces = explode(':', $qname);
                            // just grab the first element
                            $namespace  = array_shift($namespaces);

                            if (array_key_exists($namespace, $this->ns)) {
                                $this->cardinality[$storeName][$podName][] = $cardinality;
                            } else {
                                throw new \Tripod\Exceptions\ConfigException("Cardinality '{$qname}' does not have the namespace defined");
                            }
                        }
                    } else {
                        $this->cardinality[$storeName][$podName] = [];
                    }

                    $this->cardinality[$storeName][$podName] = array_key_exists("cardinality", $podConfig) ? $podConfig['cardinality'] : [];

                    // Ensure indexes are legal
                    if (array_key_exists("indexes", $podConfig)) {
                        $this->indexes[$storeName][$podName] = [];
                        foreach ($podConfig["indexes"] as $indexName => $indexFields) {
                            // check no more than 1 indexField is an array to ensure Mongo will be able to create compound indexes
                            if (count($indexFields) > 1) {
                                $fieldsThatAreArrays = 0;
                                foreach ($indexFields as $field => $fieldVal) {
                                    $cardinalityField = str_replace('.value', '', $field);
                                    if (!array_key_exists($cardinalityField, $this->cardinality[$storeName][$podName]) ||
                                        $this->cardinality[$storeName][$podName][$cardinalityField] != 1) {
                                        $fieldsThatAreArrays++;
                                    }
                                    if ($fieldsThatAreArrays > 1) {
                                        throw new \Tripod\Exceptions\ConfigException("Compound index $indexName has more than one field with cardinality > 1 - mongo will not be able to build this index");
                                    }
                                }
                            } // @codeCoverageIgnoreStart
                            // @codeCoverageIgnoreEnd

                            $this->indexes[$storeName][$podName][$indexName] = $indexFields;
                        }
                    }
                }
            }
            if (isset($storeConfig['batch_sizes'])) {
                foreach ([OP_TABLES, OP_SEARCH, OP_VIEWS] as $op) {
                    if (isset($storeConfig['batch_sizes'][$op]) && is_numeric($storeConfig['batch_sizes'][$op])) {
                        $this->batchSize[$op] = intval($storeConfig['batch_sizes'][$op]);
                    }
                }
            }
            $searchConfig = array_key_exists("search_config", $storeConfig) ? $storeConfig["search_config"] : [];
            $this->searchDocSpecs[$storeName] = [];
            if (!empty($searchConfig)) {
                $this->searchProviderClassName[$storeName] = $this->getMandatoryKey('search_provider', $searchConfig, 'search');
                // Load search doc specs if search_config is set
                $searchDocSpecs = $this->getMandatoryKey('search_specifications', $searchConfig, 'search');
                foreach ($searchDocSpecs as $spec) {
                    if (!isset($spec[_ID_KEY])) {
                        throw new \Tripod\Exceptions\ConfigException("Search document spec does not contain " . _ID_KEY);
                    }
                    if (!isset($spec['from']) || !in_array($spec['from'], $this->getPods($storeName))) {
                        throw new \Tripod\Exceptions\ConfigException("'" . $spec[_ID_KEY] . "[\"from\"]' property not set or references an undefined pod");
                    }
                    if (!isset($spec['filter'])) {
                        throw new \Tripod\Exceptions\ConfigException("'" . $spec[_ID_KEY] . "[\"filter\"]' property not set");
                    }

                    if (!isset($spec['fields']) && !isset($spec['joins'])) {
                        throw new \Tripod\Exceptions\ConfigException("'" . $spec[_ID_KEY] . "' contains no 'fields' or 'joins' properties");
                    }

                    if($this->searchProviderClassName[$storeName] == SEARCH_PROVIDER_MONGO)
                    {
                        if(isset($spec['to_data_source']))
                        {
                            if(!isset($this->dataSources[$spec['to_data_source']]))
                            {
                                throw new \Tripod\Exceptions\ConfigException("'" . $spec[_ID_KEY] . "[\"to_data_source\"]' property references an undefined data source");
                            }
                        }
                        else
                        {
                            $spec['to_data_source'] = $storeConfig['data_source'];
                        }
                    }
                    $this->searchDocSpecs[$storeName][$spec[_ID_KEY]] = $spec;
                }
            }

            // Load view specs
            $viewSpecs = (array_key_exists("view_specifications",$storeConfig)) ? $storeConfig["view_specifications"] : [];
            $this->viewSpecs[$storeName] = [];
            foreach ($viewSpecs as $spec)
            {
                if(!isset($spec[_ID_KEY]))
                {
                    throw new \Tripod\Exceptions\ConfigException("View spec does not contain " . _ID_KEY);
                }
                if(!isset($spec['from']) || !in_array($spec['from'], $this->getPods($storeName)))
                {
                    throw new \Tripod\Exceptions\ConfigException("'" . $spec[_ID_KEY] . "[\"from\"]' property not set or references an undefined pod");
                }
                if(!isset($spec['joins']))
                {
                    throw new \Tripod\Exceptions\ConfigException('Could not find any joins in view specification - usecase better served with select()');
                }
                $this->ifCountExistsWithoutTTLThrowException($spec);
                if(isset($spec['to_data_source']))
                {
                    if(!isset($this->dataSources[$spec['to_data_source']]))
                    {
                        throw new \Tripod\Exceptions\ConfigException("'" . $spec[_ID_KEY] . "[\"to_data_source\"]' property references an undefined data source");
                    }
                }
                else
                {
                    $spec['to_data_source'] = $storeConfig['data_source'];
                }
                $this->viewSpecs[$storeName][$spec[_ID_KEY]] = $spec;
            }

            // Load table specs
            $tableSpecs = (array_key_exists("table_specifications",$storeConfig)) ? $storeConfig["table_specifications"] : [];
            $this->tableSpecs[$storeName] = [];
            foreach ($tableSpecs as $spec)
            {
                $this->validateTableSpec($spec);

                if(isset($spec['to_data_source']))
                {
                    if(!isset($this->dataSources[$spec['to_data_source']]))
                    {
                        throw new \Tripod\Exceptions\ConfigException("'" . $spec[_ID_KEY] . "[\"to_data_source\"]' property references an undefined data source");
                    }
                }
                else
                {
                    $spec['to_data_source'] = $storeConfig['data_source'];
                }

                $this->tableSpecs[$storeName][$spec[_ID_KEY]] = $spec;
            }
        }

    }
1321020
public function connect(array $config)
    {
        if (isset($config[ 'path' ])) {
            $config[ 'path' ] = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $config[ 'path' ]);

            if (is_dir($config[ 'path' ])) {
                $this->path = $config[ 'path' ];
            } elseif (defined('PATH_CACHE')) {
                if (is_dir($config[ 'path' ])) {
                    $this->path = $config[ 'path' ];
                } else {
                    $this->path = PATH_CACHE . str_replace(PATH_CACHE, '', $config[ 'path' ]);
                }
            } else {
                $this->path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $config[ 'path' ];
            }
        } elseif (defined('PATH_CACHE')) {
            $this->path = PATH_CACHE;
        } else {
            $this->path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . implode(
                    DIRECTORY_SEPARATOR,
                    ['o2system', 'cache']
                );
        }

        $this->path = rtrim($this->path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

        if ($this->isSupported() === false) {
            throw new OverflowException('CACHE_FILE_E_UNABLE_TO_WRITE', 0, [$this->path]);
        }
    }
1049412
public function addConnection(array $config, $name = 'default')
	{
		$connections = $this->prop['database.connections'];
		$connections[$name] = $config;
		$this->prop['database.connections'] = $connections;
	}
824166
public function initialize(array $config)
    {
        if (!$this->_config['key']) {
            $this->setConfig('key', Security::getSalt());
        }

        $controller = $this->_registry->getController();

        if ($controller === null) {
            $this->request = ServerRequestFactory::fromGlobals();
        }

        if (empty($this->_config['path'])) {
            $this->setConfig('path', $this->getController()->getRequest()->getAttribute('webroot'));
        }
    }
898316
public function initialize(array $config = [])
    {
        $this->config = $config;
        if (is_array($this->config)) {
            if (array_keys($this->config) !== range(0, count($this->config) - 1)) {
                if (isset($this->config['db']) && is_array($this->config['db'])) {
                    foreach ($this->config['db'] as $key => &$value) {
                        if (!isset($value['port'])) {
                            $value['port'] = 3306;
                        }

                        if (!isset($value['charset'])) {
                            $value['charset'] = 'utf8';
                        }
                    }
                }

                $this->config = array_merge($this->defaults, $this->config);
                if (is_array($this->get('app_name'))) {
                    $hostName = Container::get('request')->getHostName();
                    if (array_key_exists($hostName, $this->get('app_name'))) {
                        $appName = $this->get('app_name')[$hostName];
                    } else {
                        throw new ConfigException('Cannot find any app paths.');
                    }
                } else {
                    $appName = $this->get('app_name');
                }

                if (Container::get('request')->isCli()) {
                    $stack = debug_backtrace();
                    $firstFrame = $stack[count($stack) - 1];
                    $initialFile = $firstFrame['file'];
                    $appFullPath = realpath(dirname($initialFile) . '/../' . rtrim($appName, '/'));
                } else {
                    $appFullPath = realpath(realpath('.') . '/../' . rtrim($appName, '/'));
                }

                if (!$appFullPath && !defined('KOTORI_PHP_TEST_ENV')) {
                    throw new ConfigException('Cannot find your app directory (' . $appName . ').');
                }

                $this->config = array_merge([
                    'app_full_path' => $appFullPath,
                ], $this->config);
                $this->set('namespace_prefix', basename($this->get('app_full_path')) . '\\');
            }
        } else {
            throw new ConfigException('config is not an array');
        }

        return $this;
    }
562757
private function createConnection($config): Connection
    {
        if (is_string($config)) {
            $config = ['url' => $config];
        }

        return DriverManager::getConnection($config, $this->configuration, $this->eventManager);
    }