{@inheritdoc}

@throws \Bluz\Db\Exception\DbException
546223
public static function delete(array $where): int
    {
        $self = static::getInstance();

        if (!\count($where)) {
            throw new DbException(
                "Method `Table::delete()` can't delete all records in the table `{$self->name}`,\n" .
                "please use `Db::query()` instead (of cause if you know what are you doing)"
            );
        }


        $where = static::filterColumns($where);

        if (!\count($where)) {
            throw new DbException(
                "Invalid field names of table `{$self->name}`. Please check use of `delete()` method"
            );
        }

        $table = DbProxy::quoteIdentifier($self->name);

        $sql = "DELETE FROM $table WHERE " . implode(' AND ', self::prepareStatement($where));
        return DbProxy::query($sql, array_values($where));
    }
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;
    }
254272
private function execute()
    {
        // Let the generator do his work now,
        if ($this->queryType !== self::QUERY_INSERT && $this->queryType !== self::QUERY_UPDATE && $this->queryType !== self::QUERY_DELETE) {
            throw new QueryException("Can only do apply() on INSERT and UPDATE mode!", 0, $this->exception); // @codeCoverageIgnore
        }

        // Validate all variables
        if ($this->queryType === self::QUERY_INSERT) {
            // We should have the table, all required data.
            if (count($this->changeData) === 0 || empty($this->table)) {
                throw new QueryException("When inserting you should at least give a table and the inserting data!", 0, $this->exception); // @codeCoverageIgnore
            }
        }
        if ($this->queryType === self::QUERY_UPDATE) {
            // We should have a where with at least one condition, data, and a table
            if (count($this->whereConditions) === 0 || count($this->changeData) === 0 || empty($this->table)) {
                throw new QueryException("When updating you should at least give a table, at least one where condition and the updating data!", 0, $this->exception); // @codeCoverageIgnore
            }
        }
        if ($this->queryType === self::QUERY_DELETE) {
            // We should have a where and table
            if (count($this->whereConditions) === 0 || empty($this->table)) {
                throw new QueryException("When deleting you should at least give a table and at least one where condition!", 0, $this->exception); // @codeCoverageIgnore
            }
        }

        $this->bindValues = array();
        $this->bindTypes = array();

        // Generate parts
        if ($this->queryType === self::QUERY_INSERT) {
            $this->generator->generateInsert($this->columnOrder, $this->changeData, $this->start, $this->data, $this->bindValues, $this->bindTypes);
        }

        if ($this->queryType === self::QUERY_UPDATE) {
            $this->generator->generateJoin($this->joinTables, $this->join);
            $this->generator->generateUpdate($this->changeData, $this->data, $this->bindValues, $this->bindTypes);
            $this->generator->generateWhere($this->whereConditions, $this->where, $this->bindValues, $this->bindTypes);
        }

        if ($this->queryType === self::QUERY_DELETE) {
            $this->generator->generateJoin($this->joinTables, $this->join);
            $this->generator->generateWhere($this->whereConditions, $this->where, $this->bindValues, $this->bindTypes);
        }

        $this->query = "";
        $this->combineQuery();

        // Verify if bind has same number as the number of question marks in the query
        // TODO: Implement this when stable
        //$this->verifyQuery();

        $connection = ConnectionManager::getConnection();
        $query = $connection->prepare($this->query);

        // Bind all values
        $idx = 1;
        foreach ($this->bindValues as $key => $value) {
            $query->bindValue($idx, $value, $this->bindTypes[$key]);
            $idx++;
        }

        // Execute
        $status = $query->execute();

        if ($status && $this->queryType === self::QUERY_INSERT) {
            return $connection->lastInsertId();
        }
        return $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;
	}
962074
protected function checkQuery($query=null)
    {
        if ($query) {
            $this->getQuery()->set($query);
            unset($query);
        }
        
        $query = $this->getQuery();
        
        if (!isset($query['database'])) {
            $query['database'] = $this->options['database'];
        }
        
        if (!isset($query['table_prefix'])) {
            $query['table_prefix'] = $this->options['table_prefix'];
        }
        
        // update, delete 不允许空条件执行，为避免误操作
        if (isset($query['type']) && ($query['type'] == 'update' || $query['type'] == 'delete')) {
            if (!isset($query['where']) || empty($query['where']) ) {
                $query['where'] = '1=0';
            }
        }
        
        if (!isset($query['table'])) {
            throw new DbException('query is not set table');
        }
        
        $query = static::formatQuery($query);
        
        return $query;
    }
636286
public function execute()
        {
            $values = ($this->getQuery() instanceof QueryInterface) ? $this->getQuery()->getValues() : array();
            if (Core::isDebugMode()) {
                if (Core::isDebugLoggingEnabled() && class_exists('\\caspar\\core\\Logging')) {
                    \caspar\core\Logging::log('executing PDO query (' . Core::getSQLCount() . ') - ' . (($this->getQuery() instanceof Criteria) ? $this->getQuery()->getAction() : 'unknown'), 'B2DB');
                }

                $previous_time = Core::getDebugTime();
            }

            $res = $this->statement->execute($values);

            if (!$res) {
                $error = $this->statement->errorInfo();
                if (Core::isDebugMode()) {
                    Core::sqlHit($this, $previous_time);
                }
                throw new Exception($error[2], $this->printSQL());
            }
            if (Core::isDebugLoggingEnabled() && class_exists('\\caspar\\core\\Logging')) {
                \caspar\core\Logging::log('done', 'B2DB');
            }

            if ($this->getQuery() instanceof Query && $this->getQuery()->isInsert()) {
                if (Core::getDriver() == Core::DRIVER_MYSQL) {
                    $this->insert_id = Core::getDBLink()->lastInsertId();
                } elseif (Core::getDriver() == Core::DRIVER_POSTGRES) {
                    $this->insert_id = Core::getDBLink()->lastInsertId(Core::getTablePrefix() . $this->getQuery()->getTable()->getB2DBName() . '_id_seq');
                    if (Core::isDebugLoggingEnabled() && class_exists('\\caspar\\core\\Logging')) {
                        \caspar\core\Logging::log('sequence: ' . Core::getTablePrefix() . $this->getQuery()->getTable()->getB2DBName() . '_id_seq', 'b2db');
                        \caspar\core\Logging::log('id is: ' . $this->insert_id, 'b2db');
                    }
                }
            }

            $return_value = new Resultset($this);

            if (Core::isDebugMode()) {
                Core::sqlHit($this, $previous_time);
            }

            if (!$this->getQuery() || $this->getQuery()->isSelect()) {
                $this->statement->closeCursor();
            }

            return $return_value;
        }
841465
public function executeModelChanges($db)
    {
        $count = 0;
        $models = Bootstrap::getSingleton()->getModels();
        $instanceModels = [];
        foreach ($models as $model) {
            if (class_exists($model)) {
                $instance = new $model(null);
                $instance->db = $db;
                if ($instance instanceof Model) {
                    $instanceModels[] = $instance;
                }
            }
        }
        $this->checkForDuplicatedTables($instanceModels);
        foreach ($instanceModels as $model) {
            $this->executeModel($db, $model);
        }
        $this->setDatabaseUpdate();
        return $count;
    }
986565
public function execute()
	{
		$pdoStatement = $this->pdo->prepare((string) $this);

		foreach ($this->bindings as $clause => $predicate) {
			foreach ($predicate as $key => $value) {
				$pdoStatement->bindValue(sprintf(':%s%d', $clause, $key + 1), $value, $this->getPdoDataType($value));
			}
		}

		$pdoStatement->execute();

		return new QueryResult($pdoStatement);
	}
641110
public function exec($sql)
    {
        if ($sql instanceof Zend_Db_Select) {
            $sql = $sql->assemble();
        }

        try {
            $affected = $this->getConnection()->exec($sql);

            if ($affected === false) {
                $errorInfo = $this->getConnection()->errorInfo();
                /**
                 * @see Zend_Db_Adapter_Exception
                 */
                // require_once 'Zend/Db/Adapter/Exception.php';
                throw new Zend_Db_Adapter_Exception($errorInfo[2]);
            }

            return $affected;
        } catch (PDOException $e) {
            /**
             * @see Zend_Db_Adapter_Exception
             */
            // require_once 'Zend/Db/Adapter/Exception.php';
            throw new Zend_Db_Adapter_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }
818678
public function execute() {
		
		// build the query
		$this->buildQuery();

		// prepare the statement
		$this->Prepared = \Polyfony\Database::handle()->prepare($this->Query);
		
		// marker start (after preparation, otherwise we would not be able to read the query, it wouldn't exist yet!)
		$id_marker = Profiler::setMarker(null, 'database', ['Query'=>$this]);

		// if prepare failed
		if(!$this->Prepared) {
			// throw an exception
			$this->throwExceptionOn('prepare');
		}
		
		// execute the statement
		$this->Success = $this->Prepared->execute($this->Values);
		
		// if execution failed
		if($this->Success === false) {
			// throw an exception
			$this->throwExceptionOn('execute');
		}

		// if a forced type of object has been defined
		$this->Object = $this->Object && $this->Object != 'Record' ? 
			'\Models\\'.$this->Object : 
			'\Models\\'.$this->Table;

		// temporary fix, if we don't have an object class at all
		if($this->Object == '\Models\\') {
			$this->Object = '\Polyfony\\Record';
		}

		// tweak for Microsoft SQL Server and MySQL
		$this->Object = str_replace('"','', $this->Object);
		
		// fetch all results as objects
		$this->Result = $this->Prepared->fetchAll(PDO::FETCH_CLASS, $this->Object);

		// format the result
		$this->formatSelectResult();
		$this->formatUpdateOrDeleteResult();
		$this->formatInsertResult();

		// marker end, release after all manipulation has been done
		Profiler::releaseMarker($id_marker);

		// return whatever result we got
		return $this->Result;
	}
733184
public function execute()
    {
        $databaseName = $this->databaseName === null ? $this->db->defaultDatabaseName : $this->databaseName;

        $token = $this->log([$databaseName, 'command'], $this->document, __METHOD__);

        try {
            $this->beginProfile($token, __METHOD__);

            $this->db->open();
            $mongoCommand = new \MongoDB\Driver\Command($this->document);
            $cursor = $this->db->manager->executeCommand($databaseName, $mongoCommand, $this->getReadPreference());
            $cursor->setTypeMap($this->db->typeMap);

            $this->endProfile($token, __METHOD__);
        } catch (RuntimeException $e) {
            $this->endProfile($token, __METHOD__);
            throw new Exception($e->getMessage(), $e->getCode(), $e);
        }

        return $cursor;
    }
838078
final public function execute()
	{
		if ($this->hadException()) {
			$this->setExceptionResponse($this->exception);
			return null;
		}

		$pageExtension = $this->container->getTemplating()->getExtension('supraPage');
		/* @var $pageExtension PageExtension */
		$pageExtension->setBlockExecutionContext(new BlockExecutionContext($this, $this->request));

		try {
			$this->doExecute();
		} catch (\Exception $e) {
			$this->exception = $e;
			$this->setExceptionResponse($e);
		}
	}
682570
public function setDriver(): void
    {
        switch ($this->config('driver')) {
            case 'PDO':
                $this->setPDO();
                break;
            case 'Eloquent':
                $this->setEloquentORM();
                break;
            case 'mysqli':
                $this->setMysqli();
                break;
            case 'Doctrine':
                $this->setDoctrine();
                break;
            default:
                throw new DBException($this->container(), 'Выбран неверный способ работы с данными БД');
        }
    }
586495
public function execute()
	{
		$query  = $this->factory->builder($this->insert)->process();
		$result = $this->pdo->query($query);
		if(!$result)
		{
			throw new \Exception('An error is while the insertion occurred! (query: "' . $query . '")');
		}

		return $this->pdo->lastInsertId();
	}
69579
public function with(string $relation) : self
    {
        $this->qiterator = null;
        $parts = explode('.', $relation);
        $table = $this->definition;
        array_reduce(
            $parts,
            function ($carry, $item) use (&$table) {
                $relation = $table->getRelation($item);
                if (!$relation) {
                    throw new DBException('Invalid relation name');
                }
                $name = $carry ? $carry . static::SEP . $item : $item;
                $this->withr[$name] = [ $relation, $carry ?? $table->getName() ];
                $table = $relation->table;
                return $name;
            }
        );
        return $this;
    }
651316
public function execute()
    {
        $aggregate = $this->aggregate;
        $entity = $aggregate->getEntityObject();
        $mapper = $aggregate->getMapper();
        $entityMap = $mapper->getEntityMap();

        if ($mapper->fireEvent('restoring', $entity) === false) {
            return false;
        }

        $keyName = $entityMap->getKeyName();

        $query = $this->query->where($keyName, '=', $aggregate->getEntityAttribute($keyName));

        $deletedAtColumn = $entityMap->getQualifiedDeletedAtColumn();

        $query->update([$deletedAtColumn => null]);

        $aggregate->setEntityAttribute($deletedAtColumn, null);

        $mapper->fireEvent('restored', $entity, false);

        $mapper->getEntityCache()->refresh($aggregate);

        return $entity;
    }
1011485
public function fields(array $fields)
    {
        $fields = self::filter($fields);
        $diff   = array_diff($fields, Config::table($this->name)->fields());

        if (empty($diff))
        {
            return true;
        }
        throw new dbException('Field(s) "' . implode(', ', $diff) . '" does not exists in table "' . $this->name . '"');
    }