CodeIgniter Forums
Core: Database raw sql - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Feature Requests (https://forum.codeigniter.com/forumdisplay.php?fid=29)
+--- Thread: Core: Database raw sql (/showthread.php?tid=80720)



Core: Database raw sql - iRedds - 12-08-2021

Sometimes it is necessary to use a raw sql query as part of the main query.
I already suggested this, but as part of other changes. And now I would like to know your opinion on the implementation of this as an independent tool.

This solution will help bypass the unwanted raw sql processing and use it as is.

PHP Code:
class SQLExpression
{
    protected $query '';

    /**
    * @param string $query
    */
    public function __construct(string $query)
    {
        $this->query $query;
    }

    public function __toString(): string
    
{
        return $this->query;
    }
}

function 
sql(string $query): SQLExpression
{
    return new SQLExpression($query);


Usage
PHP Code:
$db->select(sql('a + b AS c'));
$db->from(sql('SELECT * FROM ....'));    
// etc 


// Raw sql detection
PHP Code:
public function from($frombool $overwrite false)
{
    if ($overwrite === true) {
        $this->QBFrom = [];
        $this->db->setAliasedTables([]);
    }

    // here detection

    if ($from instanceof SQLExpression)
    {
        $this->QBFrom[] = $from;
        
        
return $this;
    }
    
    
// ....




RE: Core: Database raw sql - includebeer - 12-09-2021

I think that would add a lot a flexibility for more complex queries. Good idea! Smile


RE: Core: Database raw sql - kenjis - 04-07-2022

I sent a PR.
https://github.com/codeigniter4/CodeIgniter4/pull/5817

Any comments?


RE: Core: Database raw sql - iRedds - 04-13-2022

@kenjis Thank you for your work


RE: Core: Database raw sql - InsiteFX - 04-14-2022

Thank you.


RE: Core: Database raw sql - kenjis - 04-14-2022

I have not yet created a helper function.
Do you need it?


RE: Core: Database raw sql - kenjis - 05-24-2022

Since v4.2.0,
QueryBuilder select(), where(), like(), join() and
DBForge::addField() default value accept the RawSql instance.

See https://codeigniter4.github.io/CodeIgniter4/changelogs/v4.2.0.html#database


RE: Core: Database raw sql - iRedds - 05-24-2022

Thank you