Welcome Guest, Not a member yet? Register   Sign In
Creating queries with raw sql in CI 4.3.1
#1

(This post was last modified: 01-17-2023, 02:20 AM by tgix.)

Hello,
trying to port some projects over to 4.3 from 4.2 and ran into issues with QueryBuilder and queries that should not be escaped - https://github.com/codeigniter4/CodeIgni...ssues/7117

I thought `RawSql` was the Swiss-army knife but I can not get it to work as expected. The following code demonstrates this:
PHP Code:
class Home extends BaseController
{
    public function 
index()
    {
        
$db db_connect();

        
CLI::write('Working SQL (1):''green');
        
CLI::write($db->table('auth_bearer')
        ->
set([
            
'jti'        => 'jti',
            
'proctorID'  => '12',
            
'token_type' => 'handover',
        ])        
        ->
set('expires''DATE_ADD(NOW(), INTERVAL 2 HOUR)'false)
        ->
getCompiledInsert(true));

        
CLI::write('Working SQL (2):''green');
        
CLI::write($db->table('auth_bearer')
        ->
set([
            
'jti'        => 'jti',
            
'proctorID'  => '12',
            
'token_type' => 'handover',
            
'expires' => new RawSql('DATE_ADD(NOW(), INTERVAL 2 HOUR)')
        ])        
        ->
getCompiledInsert(true));

        
CLI::write('Silently failing SQL:''red');
        
CLI::write($db->table('auth_bearer')
        ->
set([
            
'jti'        => 'jti',
            
'proctorID'  => '12',
            
'token_type' => 'handover',
        ])        
        ->
set(new RawSql('expires = DATE_ADD(NOW(), INTERVAL 2 HOUR)'))
        ->
getCompiledInsert(true));


        try {
            
CLI::write($db->table('auth_bearer')
            ->
set(new RawSql('expires = DATE_ADD(NOW(), INTERVAL 2 HOUR)'))
            ->
getCompiledInsert(true));
        }
        catch (
DatabaseException $e) {
            
CLI::write('Failing with exception: ' $e->getMessage(), 'red');
        }
    }


The output is:
PHP Code:
╭─msa@sindre ~/Tangix_Work/temp/ci-rawsql 
╰─
php public/index.php

Working SQL
:
INSERT INTO `auth_bearer` (`jti`, `proctorID`, `token_type`, `expires`) VALUES ('jti''12''handover'DATE_ADD(NOW(), INTERVAL 2 HOUR))
Silently failing SQL:
INSERT INTO `auth_bearer` (`jti`, `proctorID`, `token_type`) VALUES ('jti''12''handover')
Failing with exceptionYou must use the "set" method to insert an entry

I wonder why the second statement fails silently and the third fails completely.

/Mattias
Reply




Theme © iAndrew 2016 - Forum software by © MyBB