Executes the query and returns the complete search result including e.g. hits, facets.
@param Connection $db the Sphinx connection used to generate the SQL statement.
@return array the query results.
514549
public function search($db = null)
    {
        if (!empty($this->emulateExecution)) {
            return [
                'hits' => [],
                'facets' => [],
                'meta' => [],
            ];
        }

        $command = $this->createCommand($db);
        $dataReader = $command->query();
        $rawRows = $dataReader->readAll();

        $facets = [];
        foreach ($this->facets as $facetKey => $facetValue) {
            $dataReader->nextResult();
            $rawFacetResults = $dataReader->readAll();

            if (is_numeric($facetKey)) {
                $facet = [
                    'name' => $facetValue,
                    'value' => $facetValue,
                    'count' => 'count(*)',
                ];
            } else {
                $facet = array_merge(
                    [
                        'name' => $facetKey,
                        'value' => $facetKey,
                        'count' => 'count(*)',
                    ],
                    $facetValue
                );
            }

            foreach ($rawFacetResults as $rawFacetResult) {
                $rawFacetResult['value'] = $rawFacetResult[strtolower($facet['value'])];
                $rawFacetResult['count'] = $rawFacetResult[$facet['count']];
                $facets[$facet['name']][] = $rawFacetResult;
            }
        }

        $meta = [];
        if (!empty($this->showMeta)) {
            $dataReader->nextResult();
            $rawMetaResults = $dataReader->readAll();
            foreach ($rawMetaResults as $rawMetaResult) {
                $meta[$rawMetaResult['Variable_name']] = $rawMetaResult['Value'];
            }
        }

        // rows should be populated after all data read from cursor, avoiding possible 'unbuffered query' error
        $rows = $this->populate($this->fillUpSnippets($rawRows));

        return [
            'hits' => $rows,
            'facets' => $facets,
            'meta' => $meta,
        ];
    }
492107
public function getAll()
    {
        $db = new DB();
        $result = $db->db()->select(['db_name'=>__config()->auth->db_name, 'table'=>__config()->auth->db_table]);
        $db->db()->close();

        return $result;
    }
193674
public function getRelations ($db, $table)
	{
		
		// If there are no table constraints
		
		if (!isset ($this->relations[$db][$table]))
		{
			
			// Set blank array
			
			$this->relations[$db][$table]	= array ();
			
			// Query database
			
			$query	= $this->db->query ('SHOW CREATE TABLE ' . $db . '.' . $table);
			
			// get SQL
			
			$sql	= $query->fetchColumn (1);
			
			// For each line
			
			foreach (explode ("\n", $sql) as $line)
			{
				
				// Trim
				
				$line	= trim ($line);
				
				// If the line starts with CONSTRAINT
				
				if (strpos ($line, 'CONSTRAINT') === 0)
				{
					
					// Reset pattern
					
					$pattern	= array ();
					
					// Get necessary information out of the constraint
					
					preg_match ('/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/', 
						$line, $pattern);
					
					// Add to relations array
					
					$this->relations[$db][$table][]	= array (
						'attribute'		=> $pattern[1], 
						'table'			=> $pattern[2], 
						'column'		=> $pattern[3]
					);
					
				}
				
			}
			
		}
		
		// Return relations
		
		return $this->relations[$db][$table];
		
	}
1197921
protected function cols($table, Connection $db)
    {
        $c = array();
        foreach ($db->fetchAll("SHOW COLUMNS FROM `$table`") as $row) {
            $c[$row['Field']] = $row['Type'];
        }
        return $c;
    }
914996
public function getRows($query) {
        try {
            $stmt = $this->db->query($query);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            return [];
        }
    }
290178
public function executeQuery($query = null)
    {
        $connection = $this->getConnection();
        
        $connection->transaction(function (ConnectionInterface $connection) use ($query) {
            $connection->execute($query);
        });
        
        return $connection->affectedRows();
    }
624291
protected function prepare(Connection $connection)
	{
		$connection->setFetchMode($this->app['config']['database.fetch']);

		if ($this->app->bound('events'))
		{
			$connection->setEventDispatcher($this->app['events']);
		}

		// The database connection can also utilize a cache manager instance when cache
		// functionality is used on queries, which provides an expressive interface
		// to caching both fluent queries and FlyORM queries that are executed.
		$app = $this->app;

		$connection->setCacheManager(function() use ($app)
		{
			return $app['cache'];
		});

		// We will setup a Closure to resolve the paginator instance on the connection
		// since the Paginator isn't sued on every request and needs quite a few of
		// our dependencies. It'll be more efficient to lazily resolve instances.
		$connection->setPaginator(function() use ($app)
		{
			return $app['paginator'];
		});

		return $connection;
	}
270608
public static function get(IDb $db, string $sql)
    {
        $hashCode = $db->hashCode();
        $result = static::$statements[$hashCode][$sql] ?? null;
        if(null === $result)
        {
            return $result;
        }
        if($result['using'])
        {
            return false;
        }
        static::$statements[$hashCode][$sql]['using'] = true;
        $statement = static::$statements[$hashCode][$sql];
        if(RequestContext::exsits())
        {
            $statementCaches = RequestContext::get('statementCaches', []);
            $statementCaches[] = $statement['statement'];
            RequestContext::set('statementCaches', $statementCaches);
        }
        return $statement;
    }
1072711
public static function getConnections($connection, $table)
    {
        $connections = DB::connection($connection)->table($table)->get();

        if(!empty($connections)) {
            /**
             * Create an empty array which will get populated with the data from
             * $connections in the correct format within the foreach statement
             * below file generation.
             */
            $config = array();
            /**
             * Generate a random string for the filename as it is temporary
             * and more secure.
             */
            $random_string = ConnectionLoader::random_string(35);
            /**
             * Append the .php extension to the file name and store here
             * storage_path/app/$tempFile with some starting content.
             */
            $tempFileName = $random_string . '.php';
            $tempFile = Storage::disk('local')->put($tempFileName, '<?php return ');

            if ($tempFile === true) {
                /**
                 * Loops through the connections checking the driver and pushes
                 * correctly formatted array into the $config array.
                 */
                foreach ($connections as $connection) {
                    $name = $connection->name;
                    $driver = $connection->driver;

                    if ($driver == 'sqlite') {

                        $connection_config = array(
                            'driver' => $driver,
                            'database' => database_path($connection->database),
                            'prefix' => $connection->prefix,
                        );

                        $config[$name] = $connection_config;

                    } elseif ($driver == 'mysql') {

                        $strict = $connection->strict;
                        if ($strict == 1) {
                            $strict = true;
                        } else {
                            $strict = false;
                        }
                        $password = $connection->password;

                        if(empty($password)) {
                            $connection_config = array(
                                'driver' => $driver,
                                'host' => $connection->host,
                                'database' => $connection->database,
                                'username' => $connection->username,
                                'password' => $password,
                                'charset' => $connection->charset,
                                'collation' => $connection->collation,
                                'prefix' => $connection->prefix,
                                'strict' => $strict,
                            );
                        }
                        else {
                            $connection_config = array(
                                'driver' => $driver,
                                'host' => $connection->host,
                                'database' => $connection->database,
                                'username' => $connection->username,
                                'password' => Crypt::decrypt($password),
                                'charset' => $connection->charset,
                                'collation' => $connection->collation,
                                'prefix' => $connection->prefix,
                                'strict' => $strict,
                            );
                        }

                        $config[$name] = $connection_config;

                    } elseif ($driver == 'pgsql') {

                        $password = $connection->password;

                        if(empty($password)) {
                            $connection_config = array(
                                'driver' => $driver,
                                'host' => $connection->host,
                                'port' => $connection->port,
                                'database' => $connection->database,
                                'username' => $connection->username,
                                'password' => $password,
                                'charset' => $connection->charset,
                                'prefix' => $connection->prefix,
                                'schema' => $connection->schema,
                            );
                        }
                        else {
                            $connection_config = array(
                                'driver' => $driver,
                                'host' => $connection->host,
                                'port' => $connection->port,
                                'database' => $connection->database,
                                'username' => $connection->username,
                                'password' => Crypt::decrypt($password),
                                'charset' => $connection->charset,
                                'prefix' => $connection->prefix,
                                'schema' => $connection->schema,
                            );
                        }

                        $config[$name] = $connection_config;
                    }
                }

                /**
                 * Append a var_export of $config to the temporary file and
                 * append the semicolon.
                 *
                 * Returns the temporary filename.
                 */
                $endFile = ';';
                Storage::append($tempFileName, var_export($config, true));
                Storage::append($tempFileName, $endFile);

                return $tempFileName;

            } else {
                \error_log('Unable to create temporary file');
            }
        } else {
            \error_log('Configuration File Connection Invalid.');
            return null;
        }
    }
584428
protected function db($db = '')
    {
        $db = $db ? $db : $this->use_db;

        return Connection::getInstance($db);
    }
538091
public function findByConnection($connection)
    {
        return $this->first(function ($client, $key) use ($connection) {
            return $client->connection === $connection;
        });
    }
980872
public final function fetchAll($sql, array $bind = [])
    {
        return $this->query($sql, $bind)->fetchAll(\PDO::FETCH_NAMED);
    }
576037
private function getDatabasePlatform(Connection $connection)
    {
        try {
            return $connection->getDatabasePlatform();
        } catch (DriverException $driverException) {
            throw new DBALException(
                'An exception occured while establishing a connection to figure out your platform version.' . PHP_EOL .
                "You can circumvent this by setting a 'server_version' configuration value" . PHP_EOL . PHP_EOL .
                'For further information have a look at:' . PHP_EOL .
                'https://github.com/doctrine/DoctrineBundle/issues/673',
                0,
                $driverException
            );
        }
    }
236660
public function getList($db=true) {
		if(!file_exists($this->dir.'/migrations.json'))
			return [];
		$migrations = json_decode(file_get_contents($this->dir.'/migrations.json'), true);

		if($db) {
			$tracking = [];

			$this->createTable();
			foreach($this->db->dal()->from('_migrations')->get() as $r)
				$tracking[$r['name']] = ['migrated' => strtotime($r['migrated'])];

			foreach($migrations as $migration=>$params) {
				if(isset($tracking[$migration]))
					$migrations[$migration] = array_merge($migrations[$migration], $tracking[$migration]);
			}
		}

		uasort($migrations, function($a, $b) {
			if(isset($a['migrated']) && !isset($b['migrated']))
				return -1;
			elseif(!isset($a['migrated']) && isset($b['migrated']))
				return 1;
			elseif(isset($a['migrated']) && isset($b['migrated'])) {
				if($a['migrated'] !== $b['migrated'])
					return $a['migrated'] > $b['migrated'];
			}
			return $a['added'] > $b['added'];
		});
		
		return $migrations;
	}
1294087
private function query($sql) {
		if ($sth = $this->DB->query($sql)) {
			$res = $sth->fetchAll(PDO::FETCH_COLUMN);
		} else {
			$res = false;
		}
		return $res;
	}
926690
public function getDatabase(string $connection = 'default'): Database
    {
        if (!isset($this->database[$connection])) {
            $this->database[$connection] = new Database($this->getConnection($connection));
        }

        return $this->database[$connection];
    }
1306659
public function connection($connection = null)
    {
        $type = $connection ?? $this->defaultConnection;

        if (!isset($this->connection[$type]))
        {
            $slice = $this->slice->getSlice($type);

            $key     = $slice->getRequired('adapter');
            $adapter = $this->adapters[$key];

            $this->adapterProviders[$type] = new $adapter();

            $this->adapterProviders[$type]->setHost($slice->getData('host'));
            $this->adapterProviders[$type]->setPort($slice->getData('port'));

            if (method_exists($this->adapterProviders[$type], 'setPath'))
            {
                $this->adapterProviders[$type]->setPath($slice->getData('path'));
            }

            $this->adapterProviders[$type]->setDbName($slice->getData('database'));

            $this->adapterProviders[$type]->setConnection($this);

            $this->adapterProviders[$type]->setPDOClass(Connection::class);

            $options = [
                Connection::ATTR_DEFAULT_FETCH_MODE => Connection::FETCH_ASSOC,
                //Connection::ATTR_EMULATE_PREPARES   => true,
                //Connection::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
                //Connection::ATTR_PERSISTENT         => false,
                //Connection::MYSQL_ATTR_INIT_COMMAND       => 'SET NAMES utf8mb4'
            ];

            if ($this->adapterProviders[$type]->name() !== 'sqlite')
            {
                $options[Connection::ATTR_ERRMODE] = Connection::ERRMODE_EXCEPTION;
            }

            $this->connection[$type] = $this->adapterProviders[$type]->connection(
                $slice->getData('username'),
                $slice->getData('password'),
                $slice->getData('options', $options)
            );
        }

        return $this->connection[$type];
    }