Welcome Guest, Not a member yet? Register   Sign In
Core: Database raw sql
#1

(This post was last modified: 01-22-2022, 09:56 AM by iRedds.)

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;
    }
    
    
// ....

Reply
#2

I think that would add a lot a flexibility for more complex queries. Good idea! Smile
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#3

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

Any comments?
Reply
#4

@kenjis Thank you for your work
Reply
#5

Thank you.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#6

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

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

See https://codeigniter4.github.io/CodeIgnit...l#database
Reply
#8

Thank you
Reply




Theme © iAndrew 2016 - Forum software by © MyBB