Skip to content

Commit 757773f

Browse files
committed
feat: add RawSql class
1 parent ab63c8d commit 757773f

2 files changed

Lines changed: 99 additions & 0 deletions

File tree

system/Database/RawSql.php

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<?php
2+
3+
/**
4+
* This file is part of CodeIgniter 4 framework.
5+
*
6+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
7+
*
8+
* For the full copyright and license information, please view
9+
* the LICENSE file that was distributed with this source code.
10+
*/
11+
12+
namespace CodeIgniter\Database;
13+
14+
class RawSql
15+
{
16+
/**
17+
* @var string Raw SQL string
18+
*/
19+
private string $string;
20+
21+
public function __construct(string $sqlString)
22+
{
23+
$this->string = $sqlString;
24+
}
25+
26+
public function __toString(): string
27+
{
28+
return $this->string;
29+
}
30+
31+
/**
32+
* Create new instance with new SQL string
33+
*/
34+
public function with(string $newSqlString): self
35+
{
36+
$new = clone $this;
37+
$new->string = $newSqlString;
38+
39+
return $new;
40+
}
41+
42+
/**
43+
* Returns unique id for binding key
44+
*/
45+
public function getBindingKey(): string
46+
{
47+
return 'RawSql' . spl_object_id($this);
48+
}
49+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<?php
2+
3+
/**
4+
* This file is part of CodeIgniter 4 framework.
5+
*
6+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
7+
*
8+
* For the full copyright and license information, please view
9+
* the LICENSE file that was distributed with this source code.
10+
*/
11+
12+
namespace CodeIgniter\Database;
13+
14+
use CodeIgniter\Test\CIUnitTestCase;
15+
16+
/**
17+
* @internal
18+
*/
19+
final class RawSqlTest extends CIUnitTestCase
20+
{
21+
public function testCanConvertToString()
22+
{
23+
$expected = 'REGEXP_SUBSTR(ral_anno,"[0-9]{1,2}([,.][0-9]{1,3})([,.][0-9]{1,3})") AS ral';
24+
$rawSql = new RawSql($expected);
25+
26+
$this->assertSame($expected, (string) $rawSql);
27+
}
28+
29+
public function testCanCreateNewObject()
30+
{
31+
$firstSql = 'a = 1 AND b = 2';
32+
$rawSql = new RawSql($firstSql);
33+
34+
$secondSql = 'a = 1 AND b = 2 OR c = 3';
35+
$newRawSQL = $rawSql->with($secondSql);
36+
37+
$this->assertSame($firstSql, (string) $rawSql);
38+
$this->assertSame($secondSql, (string) $newRawSQL);
39+
}
40+
41+
public function testGetBindingKey()
42+
{
43+
$firstSql = 'a = 1 AND b = 2';
44+
$rawSql = new RawSql($firstSql);
45+
46+
$key = $rawSql->getBindingKey();
47+
48+
$this->assertMatchesRegularExpression('/\ARawSql[0-9]+\z/', $key);
49+
}
50+
}

0 commit comments

Comments
 (0)