@inheritdoc

@throws DBALException

@SuppressWarnings(PHPMD.ElseExpression)
770145
public function fetchRow(QueryBuilder $builder, string $modelClass): ?array
    {
        $model = null;

        $statement = $builder->execute();
        $statement->setFetchMode(PDOConnection::FETCH_ASSOC);

        if (($attributes = $statement->fetch()) !== false) {
            if ($this->isFetchTyped() === true) {
                $platform  = $builder->getConnection()->getDatabasePlatform();
                $typeNames = $this->getModelSchemas()->getAttributeTypes($modelClass);
                $model     = $this->readRowFromAssoc($attributes, $typeNames, $platform);
            } else {
                $model = $attributes;
            }
        }

        $this->clearFetchParameters();

        return $model;
    }
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;
	}
413638
public function withSqlRuleAction($sqlExpression)
    {
        $action = new SqlRuleAction();
        $action->setCompatibilityLevel(20);
        $action->setSqlExpression($sqlExpression);
        $this->_ruleDescription->setAction($action);
    }
138665
public function execute()
    {
        try
        {
            $stmt = $this->prepare();
            if (LOG_DEBUG == Eresus_Kernel::$logLevel)
            {
                $insider = new DBQueryInsider;
                $this->doBind($insider);
                $s = $insider->subst($this);
                Eresus_Kernel::log(__METHOD__, LOG_DEBUG, '("%s")', $s);
            }
            $stmt->execute();

        }
        catch (PDOException $e)
        {
            throw Eresus_DB_Exception_QueryFailed::create($this, $e);
        }

        return $stmt;
    }
448764
static function massinsert(\fenrir\system\MysqlDatabaseSignature $db, $table, array $values, $map = null) {
		$db->begin();
		try {
			foreach ($values as $value) {
				static::insert($db, $table, $value, $map);
			}
			$db->commit();
		}
		catch (\Exception $e) {
			$db->rollback();
			throw $e;
		}
	}
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());
        }
    }
667650
function execute() {
		try {

			// we need to bind in order
			if (empty($this->refactored_stmt)) {
				$index = [];

				$this->refactored_stmt = $this->query;

				# 
				# We need to sort by length to avoid replacing keys that are
				# prefixes of other keys, thereby invaliding the bigger keys
				#

				$keylengths = [];
				foreach (\array_keys($this->params) as $key) {
					$keylengths[$key] = strlen($key);
				}

				\asort($keylengths, SORT_NUMERIC);

				$keys = \array_keys(\array_reverse($keylengths, true));

				foreach ($keys as $key) {
					$position = \strpos($this->query, $key);
					if ($position == false) {
						throw new Panic("Tried to bind parameter $key but it's not present in statement.");
					}

					$this->refactored_stmt = \str_replace($key, '?', $this->refactored_stmt);

					$index[$key] = $position;
				}

				\asort($index, SORT_NUMERIC);

				$this->stmt = \mysqli_prepare($this->dbh, $this->refactored_stmt);

				if ( ! $this->stmt) {
					throw new Panic('Failed to prepare statement');
				}

				$bindings = '';
				$args = [ $this->stmt, null ];
				foreach (array_keys($index) as $key) {
					$bindings .= $this->params[$key][1];
					$args[] = & $this->params[$key][0];
				}

				$args[1] = $bindings;

				if ( ! empty($args[1])) {
					\call_user_func_array('mysqli_stmt_bind_param', $args);
				}
			}
			
			if ( ! \mysqli_stmt_execute($this->stmt)) {
				throw new Panic('Failed to execute statement');
			}

			#
			# to avoid complications with statements not getting closed before
			# new ones are executed we fetch the result set imediatly
			#

			$this->resultset = [];
			$result = \mysqli_stmt_get_result($this->stmt);
			while ($data = mysqli_fetch_assoc($result)) {
				$this->resultset[] = $data;
			}
		}
		catch (\Exception $exception) {
			$message = $exception->getMessage();
			$message .= "\n".$this->formatQuery($this->query);
			throw new Panic($message, 500, $exception);
		}

		return $this;
	}
500872
public function select( $query, $bindings = [] )
	{
		$query = $this->bind_params( $query, $bindings );

		$result = $this->db->get_results( $query );

		if ( $result === false || $this->db->last_error ) {
			throw new QueryException( $query, $bindings, new \Exception( $this->db->last_error ) );
		}

		return $result;
	}
605696
public function query($query, $parameters = [])
    {
        try {
            $statement = $this->handle->prepare($query, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
            $statement->execute($parameters);
            return new DatabaseStatement($statement);
        } catch (\PDOException $e) {
            throw new DatabaseException('Error while preparing query « ' . $query . ' » (' .
                $e->getMessage() . ')', $query);
        }
    }
1057024
public function exec(string $statement): int
    {
        if (null === $this->pdo) {
            $this->connect();
        }

        try {
            return $this->pdo->exec($statement);
        } catch (PDOException $pdoe) {
            throw new DatabaseException($pdoe->getMessage(), $pdoe);
        }
    }
1266440
public function execute(array $inputParameters = null): bool
    {
        if(null !== $inputParameters)
        {
            foreach($inputParameters as $k => $v)
            {
                if(is_numeric($k))
                {
                    $this->statement->bindValue($k + 1, $v, $this->getDataTypeByValue($v));
                }
                else
                {
                    $this->statement->bindValue($k, $v, $this->getDataTypeByValue($v));
                }
            }
        }
        $result = $this->statement->execute();
        if(!$result)
        {
            throw new DbException('sql query error: [' . $this->errorCode() . '] ' . $this->errorInfo() . ' sql: ' . $this->getSql());
        }
        return $result;
    }
1281420
protected function prepareMysqlException(\Exception $databaseException, string $query, array $criteria = []): MysqlException {
		$code = $databaseException->getCode();
		
		$mysqlException = new MysqlException(
			$databaseException->getMessage(),
			is_numeric($code) ? $code : 0,
			$databaseException
		);
		
		$mysqlException->setQuery($this->getStatement($query, $criteria));
		return $mysqlException;
	}
18440
public function getDSQLExpression($expression)
    {
        $expr = $this->expr;
        if (is_callable($expr)) {
            $c = $this->expr;
            $expr = $c($this->owner, $expression);
        }

        if (is_string($expr)) {
            // If our Model has expr() method (inherited from Persistence\SQL) then use it
            if ($this->owner->hasMethod('expr')) {
                return $this->owner->expr('([])', [$this->owner->expr($expr)]);
            }

            // Otherwise call it from expression itself
            return $expression->expr('([])', [$expression->expr($expr)]);
        }

        return $expr;
    }
267231
function select($fields,$filter=NULL,array $options=NULL,$ttl=0) {
		list($sql,$args)=$this->stringify($fields,$filter,$options);
		$result=$this->db->exec($sql,$args,$ttl);
		$out=[];
		foreach ($result as &$row) {
			foreach ($row as $field=>&$val) {
				if (array_key_exists($field,$this->fields)) {
					if (!is_null($val) || !$this->fields[$field]['nullable'])
						$val=$this->db->value(
							$this->fields[$field]['pdo_type'],$val);
				}
				unset($val);
			}
			$out[]=$this->factory($row);
			unset($row);
		}
		return $out;
	}
842128
public function execute()
    {
        try {
            $sql = $this->prepared_sql;

            foreach ($this->param_list as $placeholder => $param) {
                if (strpos($this->prepared_sql, $placeholder) === false) {
                    throw new DatabaseException(__METHOD__ . " missing bound placeholder: $placeholder in sql $this->prepared_sql", MySQL::ERR_CONN, MySQL::SEVERITY_LOG, __FILE__, __LINE__);
                }


                $t = (isset($this->type_list[$placeholder]) ? $this->type_list[$placeholder] : 999999);

                switch ($t) {
                    case self::TYPE_BLOB:
                    case self::TYPE_STRING:
                        $val = "'" . mysql_real_escape_string($param, $this->_db->db) . "'";
                        break;
                    case self::TYPE_INT:
                    case self::TYPE_BOOL:
                        $val = (int)$param;
                        break;
                    case self::TYPE_FLOAT:
                        $val = (float)$param;
                        break;
                    case self::TYPE_NULL:
                        $val = 'NULL';
                        break;
                    default:
                        $val = "'" . (mysql_real_escape_string($param, $this->_db->db)) . "'";
                        break;
                }
                $sql = str_replace($placeholder, $val, $sql);
            }
        } catch (DatabaseException $e) {
            throw $e;
        }

        unset($t, $val, $param);

        /**
         * set the sql for debugging purposes
         */
        $this->sql = $sql;

        /**
         * query the database
         */
        $this->res = $this->_db->query($sql);

        if (!$this->res) return false;

        return $this;
    }
1062748
public static function select($sqlstatement, array $data = [])
    {
        static::verifyConnection();

        if (!preg_match(
            "/^(select\s.+?\sfrom\s.+;?|desc\s.+;?)$/i",
            $sqlstatement
        )) {
            throw new DatabaseException(
                'Syntax Error on the Request',
                E_USER_ERROR
            );
        }

        $pdostatement = static::$adapter
            ->getConnection()
            ->prepare($sqlstatement);

        static::$adapter->bind(
            $pdostatement,
            Sanitize::make($data, true)
        );

        $pdostatement->execute();

        return Sanitize::make($pdostatement->fetchAll());
    }
1024042
protected function exceptionIfNotQuery()
    {
        if (!$this->isQuery()) {
            throw new RuntimeException(
                Message::get(Message::DB_SQL_NOT_QUERY),
                Message::DB_SQL_NOT_QUERY
            );
        }
    }