Get Doctrine entity manager
@param string $db, default to the 'default' database in the config
@param string
776091
public static function getEntityManager($db = null, $context = 'shared')
    {
        // Get db config info from file
        $dbConfig = \erdiko\core\Helper::getConfig("database", $context);
        if($db == null)
            $db = $dbConfig['default'];
        $dbParams = $dbConfig['connections'][$db];
        $dbParams['dbname'] = $dbParams['database'];
        $dbParams['user'] = $dbParams['username'];

        $paths = array(ERDIKO_ROOT.$dbConfig['entities']);
        $isDevMode = isset($dbConfig['is_dev_mode']) ? (bool)$dbConfig['is_dev_mode'] : false;
        $config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
        
        // Create and return the entity manager
        return \Doctrine\ORM\EntityManager::create($dbParams, $config);
    }
27087
public function database(string $database = null): MongoDatabase
    {
        if (empty($database)) {
            $database = $this->config->defaultDatabase();
        }

        //Spiral support ability to link multiple virtual databases together using aliases
        $database = $this->config->resolveAlias($database);

        if (isset($this->databases[$database])) {
            return $this->databases[$database];
        }

        if (!$this->config->hasDatabase($database)) {
            throw new ODMException(
                "Unable to initiate MongoDatabase, no presets for '{$database}' found"
            );
        }

        $options = $this->config->databaseOptions($database);

        //Initiating database instance
        return $this->createDatabase(
            $database,
            $options['server'],
            $options['database'],
            $options['driverOptions'] ?? [],
            $options['options'] ?? []
        );
    }
216641
public function getAdminForEntity($entity): Admin
    {
        $default = null;
        foreach ($this->adminRegistry->getAdmins() as $admin) {
            if (is_a($entity, $admin->getEntity())) {
                if ($entity instanceof DataInterface) {
                    $default = $default ?: $admin;
                    /** @var array $families */
                    $families = $admin->getOption('families', []);
                    foreach ($families as $family => $config) {
                        if ($entity->getFamilyCode() === $family) {
                            return $admin;
                        }
                    }
                } else {
                    return $admin;
                }
            }
        }

        if ($default) {
            // Or throw exception anyway ?
            return $default;
        }
        $class = \get_class($entity);
        throw new \UnexpectedValueException("No admin matching for entity {$class}");
    }
970764
public function listCollections($db = '')
    {
        $cursor = $this->cmd('listCollections', null, $db);
        $result = [];
        foreach ($cursor as $collection) {
            $result[] = $collection['name'];
        }
        return $result;
    }
906267
public function getFunctions($db = NULL): array
    {
        if (!$db) {
            $db = Configuration::getInstance()->get('db')['name'];
        }

        $res = [];
        foreach (q_assoc_iterator('SHOW FUNCTION STATUS WHERE `Db` = "' . $db . '"') as $v) {
            $res[] = $v['Name'];
        }

        return $res;
    }
843174
public function getConnection($database = null)
    {
        $buildConnection = $this->getBuildConnection($database);

        //Still useful ?
        //$dsn = str_replace("@DB@", $database, $buildConnection['dsn']);
        $dsn = $buildConnection['dsn'];

        // Set user + password to null if they are empty strings or missing
        $username = isset($buildConnection['user']) && $buildConnection['user'] ? $buildConnection['user'] : null;
        $password = isset($buildConnection['password']) && $buildConnection['password'] ? $buildConnection['password'] : null;

        // Get options from and config and default to null
        $options = isset($buildConnection['options']) && is_array($buildConnection['options']) ? $buildConnection['options'] : null;

        $con = ConnectionFactory::create(['dsn' => $dsn, 'user' => $username, 'password' => $password, 'options' => $options], AdapterFactory::create($buildConnection['adapter']));

        return $con;
    }
832341
public function configure( DbAdapter $db )
    {
        $sm         = $this->getServiceLocator();
        $platform   = $db->getPlatform();
        $driver     = $db->getDriver();
        $matches    = array();
        $fulldomain = strtolower( $this->getDomain() );
        $config     = $driver->getConnection()
                             ->getConnectionParameters();

        /// TODO: remove this
        if ( isset( $_SERVER['GRIDGUYZ_DOMAIN'] ) )
        {
            $domain     = $_SERVER['GRIDGUYZ_DOMAIN'];
            $subdomain  = isset( $_SERVER['GRIDGUYZ_SUBDOMAIN'] )
                        ? $_SERVER['GRIDGUYZ_SUBDOMAIN']
                        : '';
        }
        elseif ( preg_match( '/^[\da-fA-F:]+/', $fulldomain ) ||    // probably ipv6
                 preg_match( '/^\d+(\.\d+){3}$/', $fulldomain ) )   // ipv4
        {
            $subdomain  = '';
            $domain     = $fulldomain;
        }
        else
        {
            $fullLength = strlen( $fulldomain );

            if ( empty( $config['validDomains'] ) )
            {
                $validDomains = array( 'localhost' );
            }
            else
            {
                $validDomains = array_map(
                    'strtolower',
                    (array) $config['validDomains']
                );
            }

            if ( ! empty( $config['defaultDomain'] ) )
            {
                $defaultDomain = strtolower( $config['defaultDomain'] );

                if ( ! in_array( $defaultDomain, $validDomains ) )
                {
                    array_unshift( $validDomains, $defaultDomain );
                }
            }

            foreach ( $validDomains as $validDomain )
            {
                if ( $fulldomain == $validDomain )
                {
                    $subdomain  = '';
                    $domain     = $fulldomain;
                    break;
                }

                $length = $fullLength - strlen( $validDomain ) - 1;

                if ( $length > 0 &&
                     ( '.' . $validDomain ) == substr( $fulldomain, $length ) )
                {
                    $subdomain  = substr( $fulldomain, 0, $length );
                    $domain     = $validDomain;
                    break;
                }
            }
        }

        if ( ! isset( $subdomain ) || ! isset( $domain ) )
        {
            if ( preg_match( '/^(.+)\.([a-z0-9-]+\.[a-z]+)$/', $fulldomain, $matches ) )
            {
                $subdomain  = $matches[1];
                $domain     = $matches[2];
            }
            else
            {
                $subdomain  = '';
                $domain     = $fulldomain;
            }
        }

        $query = $db->query( '
            SELECT *
              FROM ' . $platform->quoteIdentifier( 'subdomain' ) . '
             WHERE LOWER( ' . $platform->quoteIdentifier( 'subdomain' ) . ' )
                 = LOWER( ' . $driver->formatParameterName( 'subdomain' ) . ' )
        ' );

        $result = $query->execute( array(
            'subdomain' => $subdomain
        ) );

        if ( $result->getAffectedRows() > 0 )
        {
            $schema = $db->getCurrentSchema();

            foreach ( $result as $data )
            {
                $info = new SiteInfo( array(
                    'schema'        => $schema,
                    'domain'        => $domain,
                    'subdomain'     => $subdomain,
                    'subdomainId'   => $data['id'],
                    'fulldomain'    => $fulldomain,
                    'scheme'        => $this->getScheme(),
                    'port'          => $this->getPort(),
                ) );

                $sm->setService( 'SiteInfo', $info );
                return $db;
            }
        }
        else if ( $domain )
        {
            $sm->setService(
                'RedirectToDomain',
                new RedirectionService(
                    $this->getScheme(),
                    $domain,
                    $this->getPort(),
                    'sub-domain not found',
                    false
                )
            );
        }
        else
        {
            if ( empty( $config['defaultDomain'] ) )
            {
                throw new Exception\InvalidArgumentException(
                    'Domain not found, and default domain not set'
                );
            }
            else
            {
                $sm->setService(
                    'RedirectToDomain',
                    new RedirectionService(
                        $this->getScheme(),
                        $config['defaultDomain'],
                        $this->getPort(),
                        'sub-domain not found',
                        false
                    )
                );
            }
        }

        return $db;
    }
231562
public function getCollection($db = null)
    {
        /* @var $modelClass ActiveRecord */
        $modelClass = $this->modelClass;
        if ($db === null) {
            $db = $modelClass::getDb();
        }
        if ($this->from === null) {
            $this->from = $modelClass::collectionName();
        }

        return $db->getFileCollection($this->from);
    }
100469
public function createCommand($db = null)
    {
        if ($this->primaryModel !== null) {
            // lazy loading
            if (is_array($this->via)) {
                // via relation
                /* @var $viaQuery ActiveQuery */
                list($viaName, $viaQuery) = $this->via;
                if ($viaQuery->multiple) {
                    $viaModels = $viaQuery->all();
                    $this->primaryModel->populateRelation($viaName, $viaModels);
                } else {
                    $model = $viaQuery->one();
                    $this->primaryModel->populateRelation($viaName, $model);
                    $viaModels = $model === null ? [] : [$model];
                }
                $this->filterByModels($viaModels);
            } else {
                $this->filterByModels([$this->primaryModel]);
            }
        }

        /* @var $modelClass ActiveRecord */
        $modelClass = $this->modelClass;
        if ($db === null) {
            $db = $modelClass::getDb();
        }

        if ($this->type === null) {
            $this->type = $modelClass::type();
        }
        if ($this->index === null) {
            $this->index = $modelClass::index();
            $this->type = $modelClass::type();
        }
        $commandConfig = $db->getQueryBuilder()->build($this);

        return $db->createCommand($commandConfig);
    }
322101
public function get_manager() {
        global $CFG;

        if (!$this->database_manager) {
            require_once($CFG->libdir.'/ddllib.php');

            $classname = $this->get_dbfamily().'_sql_generator';
            require_once("$CFG->libdir/ddl/$classname.php");
            $generator = new $classname($this, $this->temptables);

            $this->database_manager = new database_manager($this, $generator);
        }
        return $this->database_manager;
    }
267863
public function setEntityManager(EntityManager $entityManager)
	{
		$this->entityManager = $entityManager;
		$this->connection = $entityManager->getConnection();
		$bar = Debugger::getBar();
		$bar->addPanel($this);

		$config = $this->connection->getConfiguration();
		$logger = $config->getSQLLogger();

		if ($logger instanceof Doctrine\DBAL\Logging\LoggerChain) {
			$logger->addLogger($this);
		} else {
			$config->setSQLLogger($this);
		}
	}
584428
protected function db($db = '')
    {
        $db = $db ? $db : $this->use_db;

        return Connection::getInstance($db);
    }
475576
public static function &_getDbMaster ()
	{
		
		// Get the default master
		
		$obj	=& self::_getResource ('db-master');
		
		// Failing that try to get a random master
		
		if (!$obj)
		{
			
			$obj	=& self::_getRandomDbResource ('db-master');
			
			// Default to database resource if no valid master
		
			if (!$obj)
			{
				$obj =& self::_getResource ('db');
			}
			
		}
		
		// Return database connection
		
		return $obj;
		
	}
668947
public static function getDatabaseConfig($dbConfig = null)
    {
        $config = Config::getInstance();

        if (is_null($dbConfig)) {
            $dbConfig = $config->database;
        }

        /**
         * Triggered before a database connection is established.
         *
         * This event can be used to change the settings used to establish a connection.
         *
         * @param array *$dbInfos Reference to an array containing database connection info,
         *                        including:
         *
         *                        - **host**: The host name or IP address to the MySQL database.
         *                        - **username**: The username to use when connecting to the
         *                                        database.
         *                        - **password**: The password to use when connecting to the
         *                                       database.
         *                        - **dbname**: The name of the Piwik MySQL database.
         *                        - **port**: The MySQL database port to use.
         *                        - **adapter**: either `'PDO\MYSQL'` or `'MYSQLI'`
         *                        - **type**: The MySQL engine to use, for instance 'InnoDB'
         */
        Piwik::postEvent('Db.getDatabaseConfig', array(&$dbConfig));

        $dbConfig['profiler'] = @$config->Debug['enable_sql_profiler'];

        return $dbConfig;
    }
396290
public function exec(Db $db) {
        $options = [
            'limit' => $this->limit,
            'offset' => $this->offset
        ];

        $r = $db->get($this->from, $this->where, $options);
        return $r;
    }
638880
public function db($db = null)
    {
        if ($db === null)
        {
            return $this->_db;
        }
        $this->_db = $db;

        return $this;
    }
1309636
public function db()
    {
        if (!$this->cabalDB) {
            $this->cabalDB = new Manager($this->configure('db'), $this->taskworker);
        }
        return $this->cabalDB;
    }