Run an SQL query

@param string $sql
@param string[] $binders
@param string $suggestedClass

@return \Slab\Components\Database\ResponseInterface
761052
public function query($sql, $binders = array(), $suggestedClass = null, $debug = false)
    {
        //By keeping track of the last binding location, we can skip
        //binders that are within bound data
        $minBinderLocation = 0;

        if (!is_array($binders)) $binders = array($binders);

        if (!empty($binders)) {
            foreach ($binders as &$bound) {
                $bound = $this->provider->escapeItem($bound);

                $bindingLocation = strpos($sql, static::DATABASE_BINDING_TOKEN, $minBinderLocation);

                if ($bindingLocation !== false) {
                    $sql = substr_replace($sql, $bound, $bindingLocation, 1);

                    $minBinderLocation = $bindingLocation + mb_strlen($bound) + 1;
                }
            }
        }

        $data = $this->provider->query($sql, $suggestedClass);

        if (!empty($debug)) {
            $output = new \stdClass();
            $output->sql = $sql;
            $output->response = $data;
            $output->inputs = $binders;

            if (!empty($this->log))
            {
                $this->log->notice('Debug Output', [$output]);
            }
        }

        return $data;
    }
996562
public function query(string $sql, $data = null) {
		$connection = $this->pool->getConnection();
		$result = null;
		$tryAgain = true;
SQL_START_EXECUTE:
		if (is_array($data) && count($data) > 0) {
			if (strpos($sql, ':') !== false) {
				$bind = [];
				$sql = preg_replace_callback('/:(\w+)\b/', function ($matches) use (&$data, &$bind) {
					$bind[] = $data[$matches[1]];
					return '?';
				}, $sql);
				$data = &$bind;
			}
			try {
				$st = $connection->prepare($sql);
				if ($st === false) {
					goto SQL_TRY_AGAIN;
				}
				if (is_object($st)) {
					$result = $st->execute($data);
				} else {
					$result = $connection->execute($data);
				}
			} catch (\Throwable $e) {
				goto SQL_TRY_AGAIN;
			}
			if ($result === false) {
				goto SQL_TRY_AGAIN;
			}
			goto SQL_SUCCESS_RETURN;
		} else {
			try {
				$result = $connection->query($sql);
			} catch (\Throwable $e) {
				goto SQL_TRY_AGAIN;
			}
			if ($result === false) {
				goto SQL_TRY_AGAIN;
			}
			goto SQL_SUCCESS_RETURN;
		}
SQL_TRY_AGAIN:
		if (($connection->errno === 2006 || $connection->errno === 2013) && $tryAgain) {
			$tryAgain = false;
			$connection = $this->pool->reconnect($connection);
			goto SQL_START_EXECUTE;
		} else {
			$error = $connection->error;
			$errno = $connection->errno;
			$this->pool->freeConnection($connection);
			throw new DBException($error, $errno);
		}
SQL_SUCCESS_RETURN:
		if ($result === true) {
			$result = [
				'_affected_rows' => $connection->affected_rows
			];
			if (stripos($sql, 'insert') === 0) {
				$result['_insert_id'] = $connection->insert_id;
			}
		}
		$this->pool->freeConnection($connection);
		return $result;
	}
288558
function query($sql)
    {
        $res = false;

        for ($i = 0; $i < 2; $i++)
        {
            $res = mysql_query($sql, $this->conn);
            if ($res === false)
            {
                if (mysql_errno($this->conn) == 2006 or mysql_errno($this->conn) == 2013 or (mysql_errno($this->conn) == 0 and !$this->ping()))
                {
                    $r = $this->checkConnection();
                    if ($r === true)
                    {
                        continue;
                    }
                }
                \Swoole\Error::info(__CLASS__." SQL Error", $this->errorMessage($sql));
                return false;
            }
            break;
        }

        if (!$res)
        {
            Swoole\Error::info(__CLASS__." SQL Error", $this->errorMessage($sql));
            return false;
        }
        if (is_bool($res))
        {
            return $res;
        }
        return new MySQLRecord($res);
    }
930668
public function query($sql)
    {
        try {
            $result = $this->getConnect()->query($sql);
        } catch (mysqli_sql_exception $exception) {
            $reflect = new ReflectionClass($exception);
            $property = $reflect->getProperty('sqlstate');
            $property->setAccessible(true);
            throw (new Exceptions\QueryException($exception->getMessage(), $property->getValue($exception)))
                ->setQuery($sql);
        }

        return $result;
    }
811619
public static function preparedQuery($sql) {
        self::init();
        if(!empty($exclusions = self::$_ops->getExclusions())) {
            $prepared = self::prepareStmt($sql);
            $inserts = [];
            $types = '';
            foreach($exclusions as $i => $substitute) {
                $types .= $substitute['type'];
                $inserts[] = $substitute['value'];
            }
            return self::executeStmt($prepared, $types, $inserts);
        } else {
            return self::query($sql);
        }
    }
1359238
public function prepareAndExecuteSql($sql, $binds = [])
    {
        $prepare = $this->prepareSQL($sql, $binds);

        return $this->executePrepared($prepare);
    }
1250373
protected function query ( $sql )
	{
		$sql = $this->sql_printf(func_get_args());
		if (!($res = mysqli_query( $this->conn, $sql)))
		{
			$this->sql_errcheck($sql);
		}
		if (!is_bool($res))
		{
			((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false);
		}
	}
226221
public function query(string $sql, array $params = []) {
        X::logger()->trace("$sql with params " . $this->serializeArray($params));
        try {
            $st = $this->pdo->prepare($sql);
            if ($st === false) {
                $e = $this->pdo->errorInfo();
                throw new DataBaseException($e[2], $e[1]);
            }
            if ($st->execute($params)) {
                $this->_affectedRows = $st->rowCount();
                $this->_lastInsertId = $this->pdo->lastInsertId();
                return $st->fetchAll(PDO::FETCH_ASSOC);
            }

            $e = $st->errorInfo();
            throw new DataBaseException($e[2], $e[1]);
        } catch (PDOException $ex) {
            X::logger()->trace($ex);
            throw new DataBaseException($ex->getMessage(), $ex->getCode());
        }
    }
87271
public function custom($sql, $bind = array())
    {
        // Prepare query
        $query = ConnectionManager::getConnection()->prepare($sql);

        // Bind when needed
        if (count($bind) > 0) {
            $numericBinding = true;

            // Check if we are going to use the numeric binding
            foreach($bind as $key => $value) {
                if (is_int($key)) {
                    continue;
                }else{
                    $numericBinding = false; // @codeCoverageIgnore
                    if (substr($key, 0, 1) !== ':') { // @codeCoverageIgnore
                        throw new QueryException("When binding, you should use numeric keys or keys with : before each key to identify the binding place in the query!"); // @codeCoverageIgnore
                    } // @codeCoverageIgnore
                }
            }

            // Bind it!
            $idx = 1;
            foreach($bind as $key => $value) {
                if ($numericBinding) {
                    if (is_int($value)) {
                        $type = \PDO::PARAM_INT; // @codeCoverageIgnore
                    } elseif(is_bool($value)) {
                        $type = \PDO::PARAM_BOOL; // @codeCoverageIgnore
                    } else {
                        $type = \PDO::PARAM_STR;
                    }
                    $query->bindValue($idx, $value, $type);
                } else {
                    $query->bindValue($key, $value);
                }
            }
        }

        // Set fetch mode
        $query->setFetchMode(\PDO::FETCH_CLASS, $this->class);

        // Execute
        $query->execute();

        // Fetch and return
        return $this->injectState($query->fetchAll());
    }
894618
final public function query (string $sql)
	{
		static::$lastQuery 	= $sql;
		$result 			= mysqli_query($this->connection, $sql);
		$this->confirmQuery($result);
		return $result;
	}
854553
public function query($sql, $bind = array())
    {
        $this->prepare($sql, $bind);

        return $this->db->query($sql, $bind);
    }
17563
public function run($sql, $bind = "")
    {
        $this->_sql = trim($sql);
        $this->_bind = $this->cleanup($bind);
        $this->_error = "";

        try {
            $start = microtime(true);
            $pdostmt = $this->prepare($this->_sql);
            if ($pdostmt->execute($this->_bind) !== false) {
                if (preg_match("/^(" . implode("|", array("select", "describe", "pragma")) . ") /i", $this->_sql))
                {
                    $return = ($this->limit == 1)? $pdostmt->fetch(\PDO::FETCH_ASSOC) : $pdostmt->fetchAll(\PDO::FETCH_ASSOC);
                }
                elseif (preg_match("/^(" . implode("|", array("delete", "update")) . ") /i", $this->_sql))
                {
                    $return = $pdostmt->rowCount();
                }
                elseif (preg_match("/^(" . implode("|", array("insert")) . ") /i", $this->_sql))
                {
                    $return = $this->lastInsertId();
                }
            }


            if ($this->print) {
                $time = microtime(true) - $start;
                $queryPreview = $this->interpolateQuery($this->_sql, $this->_bind);
                print_r($queryPreview);
            }

            return $return;

        } catch (PDOException $e) {
            $this->_error = $e->getMessage();
            if($this->print) {
                $queryPreview = $this->interpolateQuery($this->_sql, $this->_bind);
                print_r($queryPreview);
            }
            $this->debug();
            return false;
        }
    }
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();
		});
	}
1366029
public function startQuery($sql, array $params = NULL, array $types = NULL)
	{
		Debugger::timer('doctrine');

		$source = NULL;
		foreach (debug_backtrace() as $row) {
			if (isset($row['file']) && $this->filterTracePaths(realpath($row['file']))) {
				if (isset($row['class']) && stripos($row['class'], '\\' . Proxy::MARKER) !== FALSE) {
					if (!in_array(Proxy::class, class_implements($row['class']))) {
						continue;
					} elseif (isset($row['function']) && $row['function'] === '__load') {
						continue;
					}
				} elseif (stripos($row['file'], DIRECTORY_SEPARATOR . Proxy::MARKER) !== FALSE) {
					continue;
				}
				$source = [$row['file'], (int) $row['line']];
				break;
			}
		}

		$this->queries[] = [$sql, (array) $params, NULL, (array) $types, $source];
	}
408585
public function bind_and_run( $query, $bindings = [] )
	{
		$new_query = $this->bind_params( $query, $bindings );

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

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

		return (array) $result;
	}
915575
public function exec($sql = "", $bindingValues = array(), $insert = true)
    {
        //Check if the query is a SELECT|INSERT|UPDATE and :variation is available
        if (preg_match("/.*(SELECT|INSERT|UPDATE|SHOW|DELETE).*/", $sql)) {
            
            $this->sql = $sql;

            //Always prepare the SQL statement first
            $query = $this->connection->prepare($sql);

            if (preg_match('/\s*:(.+?)\s/', $sql)) {
                if (is_array($bindingValues) && !empty($bindingValues)) {
                    foreach ($bindingValues as $key => $val) {
                        //Clean the bindingValues. Check if they start with :
                        if (!preg_match('/:.*/', $key)) {
                            $bindingValues[":" . $key] = $val;
                            unset($bindingValues[$key]);
                        }
                    }
                }


                //Add the binding variables to the query
                if ($query->execute($bindingValues)) {
                    return $this->getLastInsertID();
                } else {
                    //@ToDo:When the save or update fails make sure we handle the error gracefully!
                    throw new \Exception(implode("\n", $query->errorInfo()));
                }

            } else {
                $result = $query->execute();
            }

            if (preg_match('/.*(SELECT|SHOW).*/', $sql)) {
                $query->setFetchMode(\PDO::FETCH_ASSOC);
                return $query->fetchAll();
            }

            return $result;
        }


        return false;
    }
1208083
public function update($sql, $bindings = array())
		{
			list($statement, $result) = $this->execute($sql, $bindings);
			return $statement->rowCount();
		}