Execute query

@param string $query
@param bool $ignore_cache Default false. If true, always return fresh result.
@return false|int False on failure, Affected row count on success.
549293
final protected function execute($query, $ignore_cache = false){
        if( $this->cache_exist($query) && !$ignore_cache ){
            return $this->get_cache($query);
        }else{
            $result = $this->db->query($query);
            $this->clear();
            $this->cache_query($query, $result);
            return $result;
        }
    }
1076278
public function executeAsTransaction($query, $arg_sets, $which_connection='')
    {
        $which_connection = $which_connection === '' ? $this->default_db : $which_connection;
        $ret = true;
        $statement = $this->prepare($query, $which_connection);
        $this->startTransaction($which_connection);
        $this->lockTimeout(5, $which_connection);
        foreach ($arg_sets as $args) {
            if (!$this->execute($statement, $args, $which_connection)) {
                $ret = false;
                break;
            }
        }
        if ($ret === true) {
            $this->commitTransaction($which_connection);
        } else {
            $this->rollbackTransaction($which_connection);
        }

        return $ret;
    }
772817
public function throwErrorIfNoRowsAffected($sqlStatement, $ignoreDuplicate = false)
    {
        if (! $this->hasFetchedRows($sqlStatement)) {
            $error = print_r($sqlStatement->errorInfo(), true);

            if ($ignoreDuplicate and preg_match('/duplicate/i', $error)) {
                return $sqlStatement->errorInfo();
            }

            throw new \Exception(
                sprintf(
                    'No rows were effected!%sSQL: "%s",%sError: %s',
                    PHP_EOL,
                    $sqlStatement->queryString,
                    PHP_EOL,
                    $error
                )
            );
        }

        return false;
    }
1187544
public function executeQuery($query)
    {
        $results = $this->mysqliRef->query($query);
        if (!$results) {
            $mex = "Mysql error ".$this->mysqliRef->error." on '".$query."''";
            $this->log($mex);
            throw new MysqltcsException($mex);
        }else {
            $this->log($query);
            return $results;
        }
    }
79585
public function exec($query, $params=array()) {

		$this->openConnection();
		
		$this->query = $query;
		
		try {

			$stat = $this->handler->prepare($this->query);
			$stat->execute((array)$params);
			$affected = $stat->rowCount();

		} catch (\PDOException $e) {

			// logger
			$this->logParamQuery($this->query, 0, $params);

			switch ($e->getCode()) {
				
				// integrity constraint violation
				/*
				case '23000':
					$message = 'Database integrity constraint violation';
					break;
				*/
				default:
					$message = $e->getMessage();
					break;
			}
			
			$this->addError($message);
				
			$affected = 0;
		
		} catch (\Exception $e) {
			
			// logger
			$this->logParamQuery($this->query, 0, $params);
			$this->addError($e->getMessage());
			$affected = 0;
		
		}
		
		$stat->closeCursor();
		$this->logParamQuery($this->query, $affected, $params);
		
		return $affected;
		
	}
676434
public function exec($query)
    {
        if ($this->isConnected()) {
            try {
                return $this->pdo->exec($query);
            } catch (PDOException $e) {
                throw new \Exception($e->getMessage());
                return false;
            }
        } else {
            return false;
        }
    }
770818
public function execute($query, ...$data)
    {
        if ($data) {
            $query = $this->merge($query, $data);
        }

        try {
            return $this->pdo->exec($query);
        } catch (PDOException $exception) {
            throw new QueryException($exception, $query);
        }
    }
178205
public function execQuery(Query $query)
    {
        $this->connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, $query->isSingle());
        $resultDataType = $query->getResultDataType();

        foreach ($query as $sql) {
            $sqlResult = $sql->getResult();
            if ($resultDataType instanceof DataInterface) {
                $sqlResult->setDataType($resultDataType);
            }

            try {
                if ($this->error->hasError()) {
                    throw new \PDOException($this->error->getMessage());
                    break;
                }
                $sqlQuery = $sql->toString();
                $totalRows = 0;
                if ($sql->getCommand() == 'SELECT' && !$query->isSingle()) {
                    $template = '{SQL}';
                    $templateCounter = 'SELECT COUNT(*) totalRows FROM (%s) fakeTable';
                    $templateParams = array(
                        'SQL' => $sqlQuery,
                        'LIMIT' => $query->getLimit(),
                        'OFFSET' => $query->getOffset(),
                    );
                    if ($query->getLimit()) {
                        switch ($this->config->getType()) {
                            case 'firebird':
                                $template = 'SELECT FIRST {LIMIT} SKIP {OFFSET} * FROM ({SQL}) fakeTable';
                            break;
                            case 'oci':
                                $templateCounter = 'SELECT COUNT(*) "totalRows" FROM (%s) "fakeTable"';
                                $template = 'SELECT a.* FROM (SELECT b.*, rownum "[]" FROM '.
                                            '({SQL}) b WHERE rownum <= {LIMIT}) a WHERE "[]" > {OFFSET}';
                            break;
                            default:
                                $template = 'SELECT * FROM ({SQL}) fakeTable LIMIT {LIMIT} OFFSET {OFFSET}';
                            break;
                        }
                    }

                    $resultCounter = $this->connection->prepare(sprintf($templateCounter, $sqlQuery));
                    $resultCounter->execute();
                    $totalRows = $resultCounter->fetch();

                    $sqlResult->setTotalRows((int) @$totalRows['totalRows']);
                    foreach ($templateParams as $key => $val) {
                        $template = str_replace('{'.$key.'}', $val, $template);
                    }
                    $sqlQuery = $template;
                }

                $result = $this->connection->prepare($sqlQuery);
                $stmt = $result->execute();
                $sql->execute();

                if ($sql->isRead()) {
                    $columns = $this->_define_column_types($result);

                    $sqlResult->setColumnTypes($columns);
                    $sqlResult->setAffected(0);
                    $sqlResult->setStartRow($query->getOffset());
                    if (!$sqlResult->getTotalRows()) {
                        $sqlResult->setTotalRows($result->rowCount());
                    }

                    $rows = $result->fetchAll(\PDO::FETCH_ASSOC);

                    foreach ($rows as $row) {
                        $data = $this->_merge_values($sql->getResult()->getDataType(), $row, $columns);
                        $sqlResult->add($data);
                    }

                    $sqlResult->setTotalShows($sqlResult->length());
                    $sqlResult->setEnd(microtime(true));
                } elseif ($sql->isWrite() || $sql->isDDL()) {
                    $insertId = $this->connection->lastInsertId();
                    $affected = $result->rowCount();
                    $endTime = microtime(true);
                    $sqlResult->setEnd($endTime);

                    $columns = array(
                        'affected' => 'integer',
                        'seconds' => 'double',
                    );

                    $row = array(
                        'affected' => $affected,
                        'seconds' => $sqlResult->getSeconds(),
                    );

                    $sqlResult->setColumnTypes($columns);
                    $sqlResult->setAffected($affected);

                    $data = new Data();
                    $this->_merge_values($data, $row, $columns);
                    $sqlResult->add($data);
                    $sqlResult->setInsertId($insertId);
                }
            } catch (\PDOException $e) {
                $sql->execute(false);
                $this->error->setMessage($e->getMessage().". \n".$sql->toString());
                $sqlResult->setEnd(microtime(true));
            } catch (\Exception $e) {
                $sql->execute(false);
                $this->error->setMessage($e->getMessage().". \n".$sql->toString());
                $sqlResult->setEnd(microtime(true));
            }
        }
    }
381487
protected function executeQuery($query)
    {
        $query   = null !== $this->getLocale() ? sprintf('%s&language=%s', $query, $this->getLocale()) : $query;
        $content = $this->getAdapter()->get($query)->getBody();

        if (!$data = json_decode($content, true)) {
            throw new NoResult(sprintf('Could not execute query: %s', $query));
        }

        if (!isset($data['Response']) && 'InvalidCredentials' === $data['subtype']) {
            throw new InvalidCredentials(sprintf('Invalid credentials: %s', $data['details']));
        } elseif (!isset($data['Response'])) {
            throw new NoResult(
                sprintf('Error type `%s` returned from api `%s`', $data['subtype'], $data['Details'])
            );
        }

        if (empty($data['Response']['View'])) {
            throw new NoResult(sprintf('Could not find results for given query: %s', $query));
        }

        $locations = $data['Response']['View'][0]['Result'];

        $results = array();
        foreach ($locations as $location) {
            $location       = $location['Location'];
            $coordinates    = isset($location['NavigationPosition'][0]) ? $location['NavigationPosition'][0] : $location['DisplayPosition'];
            $bounds         = $location['MapView'];
            $address        = $location['Address'];
            $additionalData = $location['Address']['AdditionalData'];

            $results[] = array_merge($this->getDefaults(), array(
                'latitude'     => $coordinates['Latitude']  ?: null,
                'longitude'    => $coordinates['Longitude'] ?: null,
                'bounds'       => array(
                    'south' => $bounds['BottomRight']['Latitude']  ?: null,
                    'west'  => $bounds['TopLeft']['Longitude']     ?: null,
                    'north' => $bounds['TopLeft']['Latitude']      ?: null,
                    'east'  => $bounds['BottomRight']['Longitude'] ?: null,
                ),
                'streetNumber' => isset($address['HouseNumber']) ? $address['HouseNumber'] : null,
                'streetName'   => isset($address['Street'])      ? $address['Street']      : null,
                'city'         => isset($address['City'])        ? $address['City']        : null,
                'cityDistrict' => isset($address['District'])    ? $address['District']    : null,
                'zipcode'      => isset($address['PostalCode'])  ? $address['PostalCode']  : null,
                'county'       => isset($address['County'])      ? $address['County']      : null,
                'regionCode'   => isset($address['State'])       ? $address['State']       : null,
                'countryCode'  => isset($address['Country'])     ? $address['Country']     : null,
                'region'       => $this->findByKey('StateName', $additionalData),
                'country'      => $this->findByKey('CountryName', $additionalData),
                'countyCode'   => null,
            ));
        }

        return $results;
    }
586055
public function execute( $query, $rawData = false ) {

    if ( strlen( $query ) > self::MAX_GET_SIZE ) {
      // big requests go to POST
      $this->method = 'POST';
    }

    $client = new Client();

    $response = $client->request( $this->method, self::SPARQL_ENDPOINT, [
        'query' => [ 
          "query" => $query, 
          "format" => "json",
          "maxQueryTimeMillis" => $this->timeout * 1000
        ]
    ]);

    $status = $response->getStatusCode();

    if ( $status != '200' ) {
      throw new Exception( 'HTTP Error' );
    }

    $result = $response->getBody();

    $data = json_decode( $result, true );
    
    if ( $data === null || $data === false ) {
      throw new Exception( "HTTP request failed, response:\n" .
        substr( $result, 1024 ) );
    }

    return $this->extractData( $data, $rawData );
  }
1277561
public function exec($query)
    {
        $stmt = $this->getWye()->makeStatement($query, []);

        $stmt->execute();

        return $stmt->rowCount() !== null ? $stmt->rowCount() : 0;
    }
998605
public function execute($cache = true) {
        // @todo Execute sql here
        if (strlen($this->_sql_query)) {
            // Get cache key
            $cache_key = sha1($this->_sql_query);
            
            // If cache exists and cache is enable
            $config = Config::get('db');
            $cache_enable = isset($config->cache) ? $config->cache : false;
            $cache_time = isset($config->cache_time) ? $config->cache_time : 1440;
            
            if ($cache_enable) {
                if (Cache::exists($cache_key) && $cache) {
                    return Cache::get($cache_key);
                }
            }
            
            // Return contents
            $results = [];

            // Open connection
            if (is_null($this->db) ||
                ($this->db instanceof \mysqli && !$this->db->ping())) {
                $this->__connect();
            }

            // Execute command
            $return = $this->db->query($this->_sql_query);
            
            // Close connection
            $thread = $this->db->thread_id;
            $this->db->close();
            $this->db->kill($thread);
            
            // Log executed query
            array_push(self::$_last_commands, $this->_sql_query);
        
            
            if (is_object($return) && isset($return->num_rows)) {
                while ($row = $return->fetch_array()) {
                    array_push($results, $row);
                }
                
                // Save cache (overwrites existing)
                if ($cache) {
                    Cache::save($cache_key, $results, true, $cache_time);
                }
                
                return $results;
            }
            
            return $return;
        }
    }
541394
public function select($query, $args = array(), $cache = null, $duration = null)
    {
        if ($this->connection) {
            if ($this->pre_cache($result, $cache)) {
                return $result;
            }

            Profiler::start('query', 'database');
            $result = $this->connection->select($query, $args, true);
            Profiler::stop('query');
            return $this->cache($result, $cache, $duration);
        }
        throw new \Exception('Database connection is not open!');
    }
471715
public function executeSQL($key, $query, $disable_foreign_key_checks = true, $entity=null)
    {
        if ($entity !== null && $entity != $this->last_entity) {
            $this->log("------------------------------------------------------");
            $this->log("Entity: '$entity'");
            $this->log("------------------------------------------------------");
            $this->last_entity = $entity;
        }

        $this->log(" * Sync::executeSQL '$key'...");

        $total_time_start = microtime(true);

        if ($disable_foreign_key_checks) {
            $this->adapter->query('set foreign_key_checks=0');
            $this->log("  * FK : Foreign key check disabled");
        }

        try {
            $time_start = microtime(true);
            $result = $this->adapter->query($query, ZendDb::QUERY_MODE_EXECUTE);
            $affected_rows = $result->getAffectedRows();

            // Log stuffs
            $time_stop = microtime(true);
            $time = number_format(($time_stop - $time_start), 2);
            $formatted_query = preg_replace('/(\n)|(\r)|(\t)/', ' ', $query);
            $formatted_query = preg_replace('/(\ )+/', ' ', $formatted_query);
            $this->log("  * SQL: " . substr(trim($formatted_query), 0, 70) . '...') ;
            $this->log("  * SQL: Query time $time sec(s))");
        } catch (\Exception $e) {
            $err = $e->getMessage();
            $msg = "Error running query ({$err}) : \n--------------------\n$query\n------------------\n";
            $this->log("[+] $msg\n");
            if ($disable_foreign_key_checks) {
                $this->log("[Error] Error restoring foreign key checks");
                $this->adapter->query('set foreign_key_checks=1');
            }
            throw new \Exception($msg);
        }

        if ($disable_foreign_key_checks) {
            $time_start = microtime(true);
            $this->adapter->query('set foreign_key_checks=1');
            $time_stop = microtime(true);
            $time = number_format(($time_stop - $time_start), 2);
            $this->log("  * FK : Foreign keys restored");
        }
        $time_stop = microtime(true);
        $time = number_format(($time_stop - $total_time_start), 2);
        $this->log(" * Time: $time secs, affected rows $affected_rows.");
    }
355055
public function query ($query, $data = array(), $entity = null)
		{
			if ($this->cache->isCached($query)) {
				return $this->cache->getCachedResult($query);
			} else {
				try {
					$statement = $this->database->prepare((string) $query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
					$result = $statement->execute($data);
					$this->lastQuery = $statement->queryString;
					$this->lastStatement = $statement;

					if (! $result) {
						throw new DatabaseException(implode(': ', $statement->errorInfo()) . PHP_EOL . PHP_EOL . $query);
					}

				} catch (PDOException $e) {
					throw new DatabaseException($e->getMessage() . PHP_EOL . PHP_EOL . $query);
				}

				$databaseResult = $this->createResult($statement, $entity);

				if ($query instanceof DatabaseQuery && $databaseResult instanceof DatabaseResult) {
					$this->cache->cacheQuery($query, $databaseResult);
				}

				if ($query instanceof DatabaseQuery) {
					$this->cache->refreshCache($query);
				}

				if ($databaseResult instanceof DatabaseResult) {
					return $databaseResult;

				} else if ($query instanceof DatabaseQuery && $query->getType() == DatabaseQuery::QUERY_TYPE_INSERT) {
					return $this->insertId($query->getTable());

				} else {
					return $databaseResult;
				}
			}
		}
443640
public function command(array $query)
    {
        // Create command from query
        $command = $this->getCommand($query);

        try {
            $cursor = $this->getInstance()->executeCommand(
                $this->getParam('database'),
                $command
            );
            $response = $cursor->toArray();

        } catch (MongoException $e) {
            new Exception('Unable to execute command');
        }

        return $response ?? false;
    }
90901
public function insert($ignore = false)
    {
        $this->validate();

        // Optional ignore string
        if ($ignore) {
            $insertString = "INSERT IGNORE INTO `%s` (%s) VALUES %s";
        } else {
            $insertString = "INSERT INTO `%s` (%s) VALUES %s";
        }

        $query = sprintf(
            $insertString,
            $this->table,
            $this->rowsString,
            $this->bindString
        );

        try {
            $this->db->execute($query, $this->valuesFlattened);
            return $this->db->affectedRows() > 0;
        } catch (PDOException $ex) {
            Di::getDefault()->get(Services::LOGGER)->error(
                'Could not perform bulk insert ' . $ex->getMessage() . '    TRACE: ' . $ex->getTraceAsString()
            );
            throw new BatchInsertException($ex->getMessage());
        }
    }