AbstractConnection::execute

Execute Sql statement against database.

@param QueryBuilderCache $queryBuilderCache

@return mixed
@throws \O2System\Spl\Exceptions\RuntimeException
484091
public function execute(QueryBuilderCache $queryBuilderCache, array $options = [])
    {
        // Reconnect the connection in case isn't connected yet.
        $this->reconnect();

        $queryStatement = new QueryStatement($queryBuilderCache);

        if ($queryStatement->getCollection()) {
            $startTime = microtime(true);
            $result = $this->platformExecuteHandler($queryStatement, $options);

            $queryStatement->setDuration($startTime);
            $queryStatement->setAffectedDocuments($this->getAffectedDocuments());
            $queryStatement->setLastInsertId($this->getLastInsertId());

            $this->queriesCache[] = $queryStatement;

            if ($queryStatement->hasErrors()) {
                if ($this->debugEnabled) {
                    throw new RuntimeException($queryStatement->getLatestErrorMessage(),
                        $queryStatement->getLatestErrorCode());
                }
            }

            return (bool)$result;
        }

        return false;
    }
600717
public function run(Query $query)
    {
        return $this->getDisconnectRetry()->run(function () use ($query) {
            $statement = $this->prepare($query);
            $query->getValueBinder()->attachTo($statement);
            $statement->execute();

            return $statement;
        });
    }
649055
public function subquery( QueryBuilder $queryBuilder ) {
		$this->subqueries[] = $queryBuilder->getSPARQL( false );
		$this->usageValidator->trackDefinedVariables( implode( ' ', $queryBuilder->getSelects() ) );

		// @todo temp hack to add AS definitions to defined variables
		$regexHelper = new RegexHelper();
		$matches = $regexHelper->getMatches( 'AS \{variable}', implode( ' ', $queryBuilder->getSelects() ) );
		$this->usageValidator->trackDefinedVariables( $matches );

		return $this;
	}
329723
public function execute()
    {
        try {
            $opts = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
            $pdo = new PDO('sqlite:' . $this->path, $opts);

            foreach ($this->queries as $query) {
                $pdo->query($this->phpci->interpolate($query));
            }
        } catch (\Exception $ex) {
            $this->phpci->logFailure($ex->getMessage());
            return false;
        }
        return true;
    }
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;
	}
256683
public function getQueryBuilderWithoutSecurity(QueryBuilder $queryBuilder)
    {
        $queryBuilder->addSelect('fileVersion')
            ->addSelect('file')
            ->addSelect('media')
            ->addSelect('collection')
            ->leftJoin('d.fileVersion', 'fileVersion')
            ->leftJoin('fileVersion.file', 'file')
            ->leftJoin('file.media', 'media')
            ->leftJoin('media.collection', 'collection')
            ->leftJoin(
                AccessControl::class,
                'accessControl',
                'WITH',
                'accessControl.entityClass = :entityClass AND accessControl.entityId = collection.id'
            )
            ->where('file.version = fileVersion.version')
            ->andWhere('accessControl.id is null')
            ->setParameter('entityClass', Collection::class);

        return $queryBuilder;
    }
847246
public function execute()
    {
        if (!$this->sessionSet && $this->platform instanceof MySqlPlatform) {
            $this->connection->exec("SET @@SESSION.sql_mode = '';");
            $this->sessionSet = true;
        }

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

        if (!($this->sql instanceof \JDatabaseQuery) && ($this->limit > 0 || $this->offset > 0)) {
            // @TODO
            if ($this->offset > 0) {
                $query .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
            } else {
                $query .= ' LIMIT ' . $this->limit;
            }
        }

        $this->prepared = $this->connection->prepare($query);

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

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

        // If debugging is enabled then let's log the query.
        if ($this->debug) {
            // Add the query to the object queue.
            $this->log[] = $query;

            \JLog::add($query, \JLog::DEBUG, 'databasequery');

            $this->timings[] = microtime(true);
        }

        // Execute the query.
        $this->executed = false;
        $previous = null;

        if ($this->prepared instanceof Statement) {
            // Bind the variables:
            if ($this->sql instanceof JDatabaseQueryPreparable) {
                $bounded = $this->sql->getBounded();

                foreach ($bounded as $key => $obj) {
                    $this->prepared->bindParam($key, $obj->value, $obj->dataType, $obj->length, $obj->driverOptions);
                }
            }

            try {
                $this->executed = $this->prepared->execute();
            } catch (\Exception $previous) {
            }
        }

        if ($this->debug) {
            $this->timings[] = microtime(true);

            if (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) {
                $this->callStacks[] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
            } else {
                $this->callStacks[] = debug_backtrace();
            }
        }

        // If an error occurred handle it.
        if (!$this->executed) {
            // Get the error number and message before we execute any more queries.
            $errorNum = (int) $this->connection->errorCode();
            $errorMsg = (string) 'SQL: ' . implode(", ", $this->connection->errorInfo());

            // Get the error number and message from before we tried to reconnect.
            $this->errorNum = $errorNum;
            $this->errorMsg = $errorMsg;

            // Throw the normal query exception.
            \JLog::add(
                \JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg),
                \JLog::ERROR,
                'databasequery'
            );
            throw new RuntimeException($this->errorMsg, $this->errorNum, $previous);
        }

        return $this->prepared;
    }
728615
public function exec()
    {
        $args = func_get_args();

        if (count($args) > 1) {
            $template = array_shift($args);
            $this->currentQuery = vsprintf($template, $args);
        } else {
            $this->currentQuery = $args[0];
        }

        return $this->dbExec();
    }
290178
public function executeQuery($query = null)
    {
        $connection = $this->getConnection();
        
        $connection->transaction(function (ConnectionInterface $connection) use ($query) {
            $connection->execute($query);
        });
        
        return $connection->affectedRows();
    }
6382
public function execute($sql)
    {
        try{
            if(null === $this->queryType)
            {
                $this->queryType = QueryType::WRITE;
            }
            if(!$this->isInitDb)
            {
                $this->db = Db::getInstance($this->poolName, $this->queryType);
            }
            if(!$this->db)
            {
                return new Result(false);
            }
            $stmt = $this->db->prepare($sql);
            if($stmt)
            {
                if($this->defer)
                {
                    $defer = $stmt->deferExecute($this->binds);
                }
                else
                {
                    $stmt->execute($this->binds) ? $stmt : false;
                }
            }
            return new Result($stmt, $this->modelClass, $defer ?? null);
        } finally {
            $this->__init();
        }
    }
931568
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)
		{
			// @TODO
			$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.
		$this->executed = false;

		if ($this->prepared instanceof \PDOStatement)
		{
			// Bind the variables:
			if ($this->sql instanceof PreparableInterface)
			{
				$bounded =& $this->sql->getBounded();

				foreach ($bounded as $key => $obj)
				{
					$this->prepared->bindParam($key, $obj->value, $obj->dataType, $obj->length, $obj->driverOptions);
				}
			}

			$this->executed = $this->prepared->execute();
		}

		// If an error occurred handle it.
		if (!$this->executed)
		{
			// Get the error number and message before we execute any more queries.
			$errorNum = (int) $this->connection->errorCode();
			$errorMsg = (string) 'SQL: ' . implode(", ", $this->connection->errorInfo());

			// 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) $this->connection->errorCode();
					$this->errorMsg = (string) 'SQL: ' . implode(", ", $this->connection->errorInfo());

					// 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 from before we tried to reconnect.
				$this->errorNum = $errorNum;
				$this->errorMsg = $errorMsg;

				// 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->prepared;
	}
921789
protected function isFilterAppliable(QueryBuilder $queryBuilder, string $field): bool
    {
        $qbClone = clone $queryBuilder;

        try {
            $qbClone->andWhere($field.' IS NULL');

            // Generating SQL throws a QueryException if using wrong field/association
            $qbClone->getQuery()->getSQL();
        } catch (QueryException $e) {
            return false;
        }

        return true;
    }
649292
public function execute( $query, $debug = 1 )
	{
		if( !$this->dbc )
			$this->openConnection();
		return parent::execute( $query, $debug );
	}
141281
protected function runQuery($method = 'getData', $sql = null, $standard_criteria = 1)
    {
        if ($sql === null && (int)$standard_criteria === 1) {
            $this->setModelRegistryCriteria();
        }

        $this->executed_sql = $this->query->setSql($sql);

        try {
            return $this->query->$method();

        } catch (Exception $e) {
            throw new RuntimeException($e->getMessage());
        }
    }
58820
public static function ExecuteEach()
	{
		$arguments = func_get_args();
		$executeQueryBuilders = is_array($arguments[0])? $arguments[0] : $arguments;

		$db = self::connect();
		$db->beginTransaction();
		
		try
		{
			$results = null;

			foreach($executeQueryBuilders as $executeQueryBuilder)
			{				
				$executeQuery = $executeQueryBuilder($results);
				$query = $db->prepare($executeQuery["statement"]);
			
				foreach($executeQuery["parameters"] as $key => $parameter)
				{
					if(!isset($parameter["type"]))
						$parameter["type"] = PDO::PARAM_STR;
						
					$query->bindParam($key,$parameter["value"],$parameter["type"]);
				}
					
				$query->execute();
				$rowsAffected = $query->rowCount();
				$lastID = $db->lastInsertId();

				$results = (object) array(
					DatabaseReturn::RowsAffected => $rowsAffected,
					DatabaseReturn::LastInsertID => $lastID
				);
			}
		}
		catch (PDOException $e)
		{
			$db->rollBack();
			$exception = "Sorry, there was a problem with query execution. ({$e->getMessage()})";
		}

		if($exception) throw new \Exception($exception);
		
		$db->commit();
		return $results;
	}
652337
protected function executeQuery()
    {
        if (empty($this->queryString)) {
            return $this->builder->execute();
        }

        return $this->connection->executeQuery($this->queryString, $this->queryParams);
    }
715599
private function executeQueryIn(QueryBuilder $query, $field, array $values)
    {
        array_walk(
                $values,
                function(&$value, $key, $query) {
                    $value = $query->expr()->literal($value);
                },
                $query
        );

        return $query->where($query->expr()->in($field, $values))
                        ->execute()
                        ->fetchAll(\PDO::FETCH_COLUMN);
    }