Run an SQL statement and get the number of rows affected.

@param string $query
@param array  $bindings

@return int
6107
public function affectingStatement($query, $bindings = [])
    {
        return $this->run($query, $bindings, function ($query, $bindings) {
            if ($this->pretending()) {
                return 0;
            }

            // For update or delete statements, we want to get the number of rows affected
            // by the statement and return that back to the developer. We'll first need
            // to execute the statement and then we'll use PDO to fetch the affected.
            $statement = $this->getPdo()->prepare($query);

            $this->bindValues($statement, $this->prepareBindings($bindings));

            $statement->execute();

            return $statement->rowCount();
        });
    }
20212
public function cursor($query, $bindings = [], $useReadPdo = true)
    {
        $statement = $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {
            if ($this->pretending()) {
                return [];
            }

            // First we will create a statement for the query. Then, we will set the fetch
            // mode and prepare the bindings for the query. Once that's done we will be
            // ready to execute the query against the database and return the cursor.
            $statement = $this->prepared($this->getPdoForSelect($useReadPdo)
                              ->prepare($query));

            $this->bindValues(
                $statement, $this->prepareBindings($bindings)
            );

            // Next, we'll execute the query against the database and return the statement
            // so we can return the cursor. The cursor will use a PHP generator to give
            // back one row at a time without using a bunch of memory to render them.
            $statement->execute();

            return $statement;
        });

        while ($record = $statement->fetch()) {
            yield $record;
        }
    }
802758
public final function count(string $query = null, array $queryParams = null): ?int
    {
        $queryBuilder = new QueryBuilder($this->db->getLink());
        $queryBuilder->setTable($this->table);

        if ($query || $queryParams) {
            $queryBuilder->where($query, $queryParams);
        }

        return $queryBuilder->count();
    }
820822
public function fromQuery($query, $bindings = [])
    {
        $instance = $this->model->newInstance();

        return $this->hydrate(
            $instance->getConnection()->select($query, $bindings)
        );
    }
919274
public function query($query, array $binds = array())
    {
        //Argument 1 must be a string or null
        Argument::i()->test(1, 'string', self::QUERY);
        
        $request = new \stdClass();
        
        $request->query = $query;
        $request->binds = $binds;
        
        //event trigger
        $this->trigger('sql-query-before', $request);
        
        $connection = $this->getConnection();
        $query      = (string) $request->query;
        $stmt       = $connection->prepare($query);
        
        //bind some more values
        foreach ($request->binds as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        
        //PDO Execute
        if (!$stmt->execute()) {
            $error = $stmt->errorInfo();
            
            //unpack binds for the report
            foreach ($binds as $key => $value) {
                $query = str_replace($key, "'$value'", $query);
            }
            
            //throw Exception
            Exception::i()
                ->setMessage(Exception::QUERY_ERROR)
                ->addVariable($query)
                ->addVariable($error[2])
                ->trigger();
        }
        
        $results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        if($this->queryCache) {
            //log query
            $this->queries[] = array(
                'query'     => $query,
                'binds'     => $binds,
                'results'   => $results);
        }

        //clear binds
        $this->binds = array();
        
        //event trigger
        $this->trigger('sql-query-after', $query, $binds, $results);
        
        return $results;
    }
542784
public function select( $query, $bindings = [ ], $useReadPdo = true, $resultClass = null )
	{
		$fetchCustomClass = ! is_null($resultClass) && class_exists($resultClass);

		return $this->run( $query, $bindings, function ( $query, $bindings ) use ( $useReadPdo, $fetchCustomClass, $resultClass ) {
			if( $this->pretending() )
			{
				return [];
			}

			// For select statements, we'll simply execute the query and return an array
			// of the database result set. Each element in the array will be a single
			// row from the database table, and will either be an array or objects.
			$statement = $this->prepared( $this->getPdoForSelect( $useReadPdo )->prepare( $query ), ! $fetchCustomClass );
			$this->bindValues( $statement, $this->prepareBindings( $bindings ) );
			$statement->execute();

			return $fetchCustomClass ? $statement->fetchAll(\PDO::FETCH_CLASS, $resultClass) : $statement->fetchAll();
		});
	}
766146
protected function statement($query, $bindings = array())
    {
        $statement  = $this->getActivePdo()->prepare($query);

        return $statement->execute($bindings);
    }
650221
public function select( $query, $bindings = [], $useReadPdo = true )
	{
		return $this->run( $query, $bindings, function ( $me, $query, $bindings ) use ( $useReadPdo )
		{
			if ( $me->pretending() )
			{
				return [];
			}

			// For select statements, we'll simply execute the query and return an array
			// of the database result set. Each element in the array will be a single
			// row from the database table, and will either be an array or objects.
			$statement = $this->getPdoForSelect( $useReadPdo )->prepare( $query );

			$statement->execute( $me->prepareBindings( $bindings ) );

			$fetchMode = $me->getFetchMode();
			$fetchArgument = $me->getFetchArgument();

			if ( $fetchMode === PDO::FETCH_CLASS && !isset( $fetchArgument ) )
			{
				$fetchArgument = 'StdClass';
			}

			return isset( $fetchArgument ) ? $statement->fetchAll( $fetchMode, $fetchArgument, $me->getFetchConstructorArgument() ) : $statement->fetchAll( $fetchMode );
		} );
	}
988567
protected function run($query, $bindings, Closure $callback)
    {
        $this->reconnectIfMissingConnection();

        $start = microtime(true);

        // Here we will run this query. If an exception occurs we'll determine if it was
        // caused by a connection that has been lost. If that is the cause, we'll try
        // to re-establish connection and re-run the query with a fresh connection.
        try {
            $result = $this->runQueryCallback($query, $bindings, $callback);
        } catch (QueryException $e) {
            $result = $this->handleQueryException(
                $e, $query, $bindings, $callback
            );
            logger()->error('SQL Error', [$query, $bindings]);
            mstat()->set(1, 'BUG错误', 'SQL执行错误', $query, $e->getMessage(), 100);
        }

        $execute_time = $this->getElapsedTime($start);
        //监控SQL执行效率
        if ($execute_time) {
            mstat()->set(1, 'SQL执行效率', mstat()->formatTime($execute_time), $query);
        }

        // Once we have run the query we will calculate the time that it took to run and
        // then log the query, bindings, and execution time so we will report them on
        // the event that the developer needs them. We'll log time in milliseconds.
        $this->logQuery(
            $query, $bindings, $execute_time
        );

        return $result;
    }
889306
protected function compileJoinPart(Query $query, array &$bindings): string
    {
        $joinsSQL = [];

        foreach ($query->join as $join) {
            $joinsSQL[] = $this->compileOneJoin($join, $bindings);
        }

        return $this->implodeSQL($joinsSQL);
    }
418332
public function cursor( $query, $bindings = [], $useReadPdo = true )
	{
		$statement = $this->run( $query, $bindings, function ( $me, $query, $bindings ) use ( $useReadPdo )
		{
			if ( $me->pretending() )
			{
				return [];
			}

			$statement = $this->getPdoForSelect( $useReadPdo )->prepare( $query );

			$fetchMode = $me->getFetchMode();
			$fetchArgument = $me->getFetchArgument();

			if ( $fetchMode === PDO::FETCH_CLASS && !isset( $fetchArgument ) )
			{
				$fetchArgument = 'StdClass';
			}

			if ( isset( $fetchArgument ) )
			{
				$statement->setFetchMode( $fetchMode, $fetchArgument, $me->getFetchConstructorArgument() );
			}
			else
			{
				$statement->setFetchMode( $fetchMode );
			}

			$statement->execute( $me->prepareBindings( $bindings ) );

			return $statement;
		} );

		while ( $record = $statement->fetch() )
		{
			yield $record;
		}
	}
1160007
public function bind(string $query, array $bindings): string
    {
        $this->checkBindings($query, $bindings);
        $escapedBindings = $this->escapeBindings($bindings);

        $query = str_replace('%', '%%', $query);
        $query = str_replace('?', '%s', $query);

        $query = call_user_func_array('sprintf', array_merge([$query], $escapedBindings));

        return $query;
    }
1264898
public function selectOne($query, $bindings = array())
    {
        $query .= " LIMIT 1;";
        $result = $this->select($query, $bindings);
        return (isset($result[0]) ? $result[0] : []);
    }
774553
public function cursor( $query, $bindings = [ ], $useReadPdo = true, $resultClass = null )
	{
		$fetchCustomClass = ! is_null($resultClass) && class_exists($resultClass);

		$statement = $this->run( $query, $bindings, function ( $query, $bindings ) use ( $useReadPdo, $fetchCustomClass ) {
			if( $this->pretending() )
			{
				return [ ];
			}

			// First we will create a statement for the query. Then, we will set the fetch
			// mode and prepare the bindings for the query. Once that's done we will be
			// ready to execute the query against the database and return the cursor.
			$statement = $this->prepared( $this->getPdoForSelect( $useReadPdo )->prepare( $query ), ! $fetchCustomClass );
			$this->bindValues(
				$statement, $this->prepareBindings( $bindings )
			);

			// Next, we'll execute the query against the database and return the statement
			// so we can return the cursor. The cursor will use a PHP generator to give
			// back one row at a time without using a bunch of memory to render them.

			$statement->execute();
			return $statement;
		});

		if( $fetchCustomClass )
		{
			while( $record = $statement->fetchObject( $resultClass ) )
			{
				yield $record;
			}
		}
		else
		{
			while( $record = $statement->fetch() )
			{
				yield $record;
			}
		}
	}
563387
public function statement($query, $bindings = [])
    {
        $new_query = $this->bindParams($query, $bindings, true);

        return $this->unprepared($new_query);
    }
1138914
public function selectOne($query, $bindings = [])
    {
        $start = $this->getLogTime();

        try {

            $result = $this->wpdb->get_row($this->bindParams($query, $bindings));

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

            return $result;

        } catch (QueryException $e) {
            throw $e;
        } finally {
            $this->logQuery($query, $bindings, $this->getElapsedTime($start));
        }
    }
981
public function count(string $table, $wheres)
    {
        list($where, $bindings) = $this->handleWheres($wheres);
        $sql = "SELECT COUNT(*) AS total FROM {$table} WHERE {$where}";

        $result = $this->fetchObject($sql, $bindings);

        return $result ? (int)$result->total : 0;
    }