Skip to content

Commit e8687c7

Browse files
committed
feat: select() supports RawSql
1 parent 757773f commit e8687c7

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

system/Database/BaseBuilder.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,12 @@ public function select($select = '*', ?bool $escape = null)
371371
$escape = $this->db->protectIdentifiers;
372372
}
373373

374+
if ($select instanceof RawSql) {
375+
$this->QBSelect[] = $select;
376+
377+
return $this;
378+
}
379+
374380
foreach ($select as $val) {
375381
$val = trim($val);
376382

@@ -2339,6 +2345,8 @@ protected function compileSelect($selectOverride = false): string
23392345

23402346
if (empty($this->QBSelect)) {
23412347
$sql .= '*';
2348+
} elseif ($this->QBSelect[0] instanceof RawSql) {
2349+
$sql .= (string) $this->QBSelect[0];
23422350
} else {
23432351
// Cycle through the "select" portion of the query and prep each column name.
23442352
// The reason we protect identifiers here rather than in the select() function

tests/system/Database/Builder/SelectTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
use CodeIgniter\Database\BaseBuilder;
1515
use CodeIgniter\Database\Exceptions\DataException;
16+
use CodeIgniter\Database\RawSql;
1617
use CodeIgniter\Database\SQLSRV\Builder as SQLSRVBuilder;
1718
use CodeIgniter\Test\CIUnitTestCase;
1819
use CodeIgniter\Test\Mock\MockConnection;
@@ -95,6 +96,20 @@ public function testSelectWorksWithComplexSelects()
9596
$this->assertSame($expected, str_replace("\n", ' ', $builder->getCompiledSelect()));
9697
}
9798

99+
/**
100+
* @see https://github.com/codeigniter4/CodeIgniter4/issues/4355
101+
*/
102+
public function testSelectWorksWithRawSql()
103+
{
104+
$builder = new BaseBuilder('users', $this->db);
105+
106+
$sql = 'REGEXP_SUBSTR(ral_anno,"[0-9]{1,2}([,.][0-9]{1,3})([,.][0-9]{1,3})") AS ral';
107+
$builder->select(new RawSql($sql));
108+
109+
$expected = 'SELECT ' . $sql . ' FROM "users"';
110+
$this->assertSame($expected, str_replace("\n", ' ', $builder->getCompiledSelect()));
111+
}
112+
98113
public function testSelectMinWithNoAlias()
99114
{
100115
$builder = new BaseBuilder('invoices', $this->db);

0 commit comments

Comments
 (0)