Execute the call

@param array  $options      Array of options
@param object $engine       Calling engine
@param bool   $freshConnect Make a fresh connection every call

@return mixed Response
777900
public function execute($options, $engine, $freshConnect = false)
    {
        $options['returntransfer']=true;
        $options = $this->parseCurlOptions(array_merge($options, $this->options));
        $this->makeRequest($engine, $options);
        $this->parseResponseData();
        $this->parseResponseHeader();
        $this->status = $engine->getinfo(CURLINFO_HTTP_CODE);
        $result = $this->getResponseObject();

        return $result;
    }
955313
public function execute()
	{
		$this->connect();

		if (!is_object($this->connection))
		{
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg)
			);
			throw new \RuntimeException($this->errorMsg, $this->errorNum);
		}

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		if ($this->limit > 0 || $this->offset > 0)
		{
			$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
		}

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
		$this->cursor = @mysqli_query($this->connection, $sql);

		// If an error occurred handle it.
		if (!$this->cursor)
		{
			$this->errorNum = (int) mysqli_errno($this->connection);
			$this->errorMsg = (string) mysqli_error($this->connection) . "\n-- SQL --\n" . $sql;

			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (\RuntimeException $e)
				// If connect fails, ignore that exception and throw the normal exception.
				{
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg)
					);
					throw new \RuntimeException($this->errorMsg, $this->errorNum);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}
			else
			// The server was not disconnected.
			{
				$this->log(
					Log\LogLevel::ERROR,
					'Database query failed (error #{code}): {message}',
					array('code' => $this->errorNum, 'message' => $this->errorMsg)
				);
				throw new \RuntimeException($this->errorMsg, $this->errorNum);
			}
		}

		return $this->cursor;
	}
769677
public static function setConnection($con, $env = null) 
    {
        $env = self::selectEnvironment($env);
        self::$_connection[$env] = $con;

        // just send an exception when not on production mode
        if (in_array($env, array("development","test"))) {
            self::setErrorHandling(\PDO::ERRMODE_EXCEPTION);
        }
    }
992718
public function execute()
	{
		$this->connect();

		if (!is_resource($this->connection))
		{
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg)
			);
			throw new \RuntimeException($this->errorMsg, $this->errorNum);
		}

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		if ($this->limit > 0 || $this->offset > 0)
		{
			$sql = $this->limit($sql, $this->limit, $this->offset);
		}

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		// SQLSrv_num_rows requires a static or keyset cursor.
		if (strncmp(ltrim(strtoupper($sql)), 'SELECT', strlen('SELECT')) == 0)
		{
			$array = array('Scrollable' => SQLSRV_CURSOR_KEYSET);
		}
		else
		{
			$array = array();
		}

		// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
		$this->cursor = @sqlsrv_query($this->connection, $sql, array(), $array);

		// If an error occurred handle it.
		if (!$this->cursor)
		{
			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (\RuntimeException $e)
				// If connect fails, ignore that exception and throw the normal exception.
				{
					// Get the error number and message.
					$errors = sqlsrv_errors();
					$this->errorNum = $errors[0]['SQLSTATE'];
					$this->errorMsg = $errors[0]['message'] . 'SQL=' . $sql;

					// Throw the normal query exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg)
					);
					throw new \RuntimeException($this->errorMsg, $this->errorNum);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}
			else
			// The server was not disconnected.
			{
				// Get the error number and message.
				$errors = sqlsrv_errors();
				$this->errorNum = $errors[0]['SQLSTATE'];
				$this->errorMsg = $errors[0]['message'] . 'SQL=' . $sql;

				// Throw the normal query exception.
				$this->log(
					Log\LogLevel::ERROR,
					'Database query failed (error #{code}): {message}',
					array('code' => $this->errorNum, 'message' => $this->errorMsg)
				);
				throw new \RuntimeException($this->errorMsg, $this->errorNum);
			}
		}

		return $this->cursor;
	}
976426
public function execute($entity, $method = 'get', $options = [])
    {

        $this->cleanQueryParams($entity);
        $configuration = $this->_getEntityConfiguration($entity);

        if ($method != 'get'){
            foreach ($configuration->attributes as $key => $attribute) {
                $this->validateAttribute($entity, $key, ['required']);
            } 
        }

        $this->processOptions($options, $configuration);

        $this->_setDefaultHeaders($configuration->query);
        $this->_setCustomHeaders($entity, $configuration->query);
        //$this->_setIdempotencyHeader($configuration->query, $configuration, $method);
        $this->setQueryParams($entity);
        
        return $this->_client->{$method}($configuration->url, $configuration->query);
    }
166397
private function ExecuteScripts($engineFolder)
    {
        $files = $this->SortFilesByVersion(Folder::GetFiles($engineFolder));
        
        $completeSql = '';
        foreach ($files as $file)
        {
            $sqlFile = Path::Combine($engineFolder, $file);
            $completeSql .= "\r\n" . File::GetContents($sqlFile);
        }
        try
        {
            $this->CleanAllForeignKeys();
            //$this->connection->StartTransaction();
            $this->connection->ExecuteMultiQuery($completeSql);
        }
        catch (\Exception $exc)
        {
            //$this->connection->RollBack();
            throw $exc;
            //throw new \Exception("Error executing SQL in folder $engineFolder: " . $completeSql, null, $exc);
        }
        //$this->connection->Commit();
    }
1081644
private function executeMigration(
        array $migrationsToExecute,
        string $direction,
        MigratorConfiguration $migratorConfiguration
    ) : array {
        $dryRun = $migratorConfiguration->isDryRun();

        $connection = $this->configuration->getConnection();

        $allOrNothing = $migratorConfiguration->isAllOrNothing();

        if ($allOrNothing) {
            $connection->beginTransaction();
        }

        try {
            $this->configuration->dispatchMigrationEvent(Events::onMigrationsMigrating, $direction, $dryRun);

            $sql  = [];
            $time = 0;

            foreach ($migrationsToExecute as $version) {
                $versionExecutionResult = $version->execute($direction, $migratorConfiguration);

                // capture the to Schema for the migration so we have the ability to use
                // it as the from Schema for the next migration when we are running a dry run
                // $toSchema may be null in the case of skipped migrations
                if (! $versionExecutionResult->isSkipped()) {
                    $migratorConfiguration->setFromSchema($versionExecutionResult->getToSchema());
                }

                $sql[$version->getVersion()] = $versionExecutionResult->getSql();
                $time                       += $versionExecutionResult->getTime();
            }

            $this->configuration->dispatchMigrationEvent(Events::onMigrationsMigrated, $direction, $dryRun);
        } catch (Throwable $e) {
            if ($allOrNothing) {
                $connection->rollBack();
            }

            throw $e;
        }

        if ($allOrNothing) {
            $connection->commit();
        }

        return $sql;
    }
412086
function connectionSet(array $params)
    {
        $this->connection = new Redis();
        if ($this->connection == false) {
            throw new common_exception_Error("Redis php module not found");
        }
        if (!isset($params['host'])) {
            throw new common_exception_Error('Missing host information for Redis driver');
        }
        $host    = $params['host'];
        $port    = isset($params['port']) ? $params['port'] : self::DEFAULT_PORT;
        $timeout = isset($params['timeout']) ? $params['timeout'] : self::DEFAULT_TIMEOUT;
        $persist = isset($params['pconnect']) ? $params['pconnect'] : true;
        $this->params['attempt'] = isset($params['attempt']) ? $params['attempt'] : self::DEFAULT_ATTEMPT;

        if ($persist) {
            $this->connection->pconnect($host , $port , $timeout);
        } else {
            $this->connection->connect($host , $port , $timeout);
        }
    }
470697
private static function createWithArgs($engine, $args)
    {
        $engineName = ucfirst($engine);
        $className = self::FETCHER_CLASS_PREFIX . $engineName . self::FETCHER_CLASS_SUFFIX;
        return call_user_func_array(array(new \ReflectionClass($className), 'newInstance'),
                                    $args);
    }
997785
private function send(callable $method, ...$args): \Generator
    {
        while ($this->busy) {
            try {
                yield $this->busy->promise();
            } catch (\Throwable $exception) {
                // Ignore failure from another operation.
            }
        }

        if (!$this->handle) {
            throw new ConnectionException("The connection to the database has been closed");
        }

        try {
            $this->deferred = $this->busy = new Deferred;

            $handle = $method(...$args);

            Loop::enable($this->poll);
            if (!$this->handle->flush()) {
                Loop::enable($this->await);
            }

            $result = yield $this->deferred->promise();
        } catch (pq\Exception $exception) {
            throw new FailureException($this->handle->errorMessage, 0, $exception);
        } finally {
            $this->deferred = $this->busy = null;
        }

        if (!$result instanceof pq\Result) {
            throw new FailureException("Unknown query result");
        }

        switch ($result->status) {
            case pq\Result::EMPTY_QUERY:
                throw new QueryError("Empty query string");

            case pq\Result::COMMAND_OK:
                if ($handle instanceof pq\Statement) {
                    return $handle; // Will be wrapped into a PqStatement object.
                }

                return new PqCommandResult($result);

            case pq\Result::TUPLES_OK:
                return new PqBufferedResultSet($result);

            case pq\Result::SINGLE_TUPLE:
                $this->busy = new Deferred;
                $result = new PqUnbufferedResultSet($this->fetch, $result, $this->release);
                return $result;

            case pq\Result::NONFATAL_ERROR:
            case pq\Result::FATAL_ERROR:
                throw new QueryExecutionError($result->errorMessage, $result->diag);

            case pq\Result::BAD_RESPONSE:
                throw new FailureException($result->errorMessage);

            default:
                throw new FailureException("Unknown result status");
        }
    }
918827
public function execute()
	{
		$this->connect();

		if (!is_resource($this->connection))
		{
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg)
			);
			throw new \RuntimeException($this->errorMsg, $this->errorNum);
		}

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		if ($this->limit > 0 || $this->offset > 0)
		{
			$sql .= ' LIMIT ' . $this->limit . ' OFFSET ' . $this->offset;
		}

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
		$this->cursor = @pg_query($this->connection, $sql);

		// If an error occurred handle it.
		if (!$this->cursor)
		{
			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (\RuntimeException $e)
				// If connect fails, ignore that exception and throw the normal exception.
				{
					// Get the error number and message.
					$this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' ';
					$this->errorMsg = pg_last_error($this->connection) . "\nSQL=$sql";

					// Throw the normal query exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg)
					);
					throw new \RuntimeException($this->errorMsg);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}
			else
			// The server was not disconnected.
			{
				// Get the error number and message.
				$this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' ';
				$this->errorMsg = pg_last_error($this->connection) . "\nSQL=$sql";

				// Throw the normal query exception.
				$this->log(
					Log\LogLevel::ERROR,
					'Database query failed (error #{code}): {message}',
					array('code' => $this->errorNum, 'message' => $this->errorMsg)
				);
				throw new \RuntimeException($this->errorMsg);
			}
		}

		return $this->cursor;
	}
1319639
private function connect($selectDb = true)
    {
        if (!$this->isPhpEnvironmentSupported()) {
            throw new ConnectionException("Function pg_connect doesn't exist");
        }

        //Can throw warning, if have incorrect connection params
        //So we need '@'
        $this
            ->getLogger()
            ->startConnection('Pgsql connection');
        $connectString  = $this->generateConnectionString($selectDb);
        $this->resource = @\pg_connect($connectString);
        $this
            ->getLogger()
            ->stopConnection();

        if (!$this->resource) {
            $error = \error_get_last();
            throw new ConnectionException('Error ' . $error['message']);
        }
    }
918162
protected function runJob($workCommand, $job, $connectionName, WorkerOptions $options)
    {
        try {
            return $this->process($workCommand, $connectionName, $job, $options);
        } catch (Exception $e) {
            $this->report($e);

            $this->stopWorkerIfLostConnection($e);
        } catch (Throwable $e) {
            $e = new FatalThrowableError($e);
            $this->report($e);

            $this->stopWorkerIfLostConnection($e);
        }
    }
1372069
public function ExecuteProgram($inputXml, $disconnect = false)
    {
        $this->execStartTime = '';
        $this->error = '';

        $this->VerifyPLUGName(); // calculates value of option 'plug'
        $this->VerifyInternalKey();

        // @todo create driver-specific SQL in driver classes (db2, odbc)
        $internalKey = $this->getInternalKey();
        $controlKeyString = $this->getControlKey($disconnect);

        $plugSize = $this->getOption('plugSize');

        // @todo have one transport class that includes db as well.

        // If a database transport
        if (isset($this->db) && $this->db) {
            $result = $this->makeDbCall($internalKey, $plugSize, $controlKeyString, $inputXml, $disconnect);
        } else {
            // Not a DB transport. At this time, assume HTTP transport (which doesn't use a plug, by the way. uses outbytesize)
            $transport = $this->getTransport();
            $transport->setIpc($internalKey);
            $transport->setCtl($controlKeyString);
            $url = $this->getOption('httpTransportUrl');
            $transport->setUrl($url);

            // convert plugSize to bytes
            $outByteSize = $this->plugSizeToBytes($plugSize);

            // if debug mode, log control key, and input XML.
            if ($this->isDebug()) {
                $this->debugLog("\nExec start: " . date("Y-m-d H:i:s") . "\nVersion of toolkit front end: " . self::getFrontEndVersion() ."\nToolkit class: '" . __FILE__ . "'\nIPC: '" . $this->getInternalKey() . "'. Control key: $controlKeyString\nHost URL: $url\nExpected output size (plugSize): $plugSize or $outByteSize bytes\nInput XML: $inputXml\n");
                $this->execStartTime = microtime(true);
            }

            $result = $transport->send($inputXml, $outByteSize);

            // workaround: XMLSERVICE as of 1.7.4 returns a single space instead of empty string when no content was requested.
            if ($result == ' ') {
                $result = '';
            }
        }

        if ($this->isDebug() && $result) {
            $end = microtime(true);
            $elapsed = $end - $this->execStartTime;
            $this->debugLog("Output XML: $result\nExec end: " . date("Y-m-d H:i:s") . ". Seconds to execute: $elapsed.\n\n");
        }

        return $result;
    }
906162
protected function executeOperation(LdapOperationInterface $operation, LogOperation $log = null)
    {
        $lastServer = $this->connection->getServer();
        try {
            $this->connectIfNotBound($operation);
            $lastServer = $this->connection->getServer();
            $handler = $this->getOperationHandler($operation);
            $handler->setOperationDefaults($operation);
            $this->logStart($log);
            $this->invalidateCacheIfNeeded($operation);
            list($result, $usedCache, $cacheKey) = $this->getCacheOrHandlerResult($operation, $handler, $log);
            $this->cacheResultIfNeeded($operation, $result, $usedCache, $cacheKey);

            return $result;
        } catch (\Throwable $e) {
            $this->logExceptionAndThrow($e, $log);
        } catch (\Exception $e) {
            $this->logExceptionAndThrow($e, $log);
        } finally {
            $this->logEnd($log);
            // It would not have set controls or switched servers if the cache was used...
            if (isset($usedCache) && $usedCache === false) {
                $this->resetLdapControls($operation);
                $this->switchServerIfNeeded($this->connection->getServer(), $lastServer, $operation);
            }
            $this->dispatcher->dispatch(new LdapOperationEvent(Event::LDAP_OPERATION_EXECUTE_AFTER, $operation, $this->connection));
        }
    }
1070883
public function prepareOptions($options, $engine, $db) {
		if (empty($options) || !is_array($options))
			return null;
		switch ($engine) {
			case 'jig':
				if (array_key_exists('order', $options))
					$options['order'] = preg_replace(
						['/(?<=\h)(ASC)(?=\W|$)/i','/(?<=\h)(DESC)(?=\W|$)/i'],
						['SORT_ASC','SORT_DESC'],$options['order']);
				break;
			case 'mongo':
				if (array_key_exists('order', $options)) {
					$sorts = explode(',', $options['order']);
					$sorting = array();
					foreach ($sorts as $sort) {
						$sp = explode(' ', trim($sort));
						$sorting[$sp[0]] = (array_key_exists(1, $sp) &&
							strtoupper($sp[1]) == 'DESC') ? -1 : 1;
					}
					$options['order'] = $sorting;
				}
				if (array_key_exists('group', $options) && is_string($options['group'])) {
					$keys = explode(',',$options['group']);
					$options['group']=array('keys'=>array(),'initial'=>array(),
						'reduce'=>'function (obj, prev) {}','finalize'=>'');
					$keys = array_combine($keys,array_fill(0,count($keys),1));
					$options['group']['keys']=$keys;
					$options['group']['initial']=$keys;
				}
				break;
			case 'sql':
				$char=substr($db->quotekey(''),0,1);
				if (array_key_exists('order', $options) &&
					FALSE===strpos($options['order'],$char))
					$options['order']=preg_replace_callback(
						'/(\w+\h?\(|'. // skip function names
						'\b(?!\w+)(?:\s+\w+)+|' . // skip field args
						'\)\s+\w+)|'. // skip function args
						'(\b\d?[a-zA-Z_](?:[\w\-.])*)/i', // match table/field keys
						function($match) use($db) {
							if (!isset($match[2]))
								return $match[1];
							return $db->quotekey($match[2]);
						}, $options['order']);
				break;
		}
		return $options;
	}
478560
public function Connect( $Address, $Port, $Timeout = 3, $Engine = self::SOURCE )
		{
			$this->Disconnect( );
			
			if( !is_int( $Timeout ) || $Timeout < 0 )
			{
				throw new InvalidArgumentException( 'Timeout must be an integer.', InvalidArgumentException::TIMEOUT_NOT_INTEGER );
			}
			
			$this->Socket->Open( $Address, (int)$Port, $Timeout, (int)$Engine );
			
			$this->Connected = true;
		}