Skip to content

Commit eba2686

Browse files
elcapotpetry
andcommitted
feat: string concatenation (tpetry#4)
Co-authored-by: tpetry <[email protected]>
1 parent 81efd16 commit eba2686

File tree

3 files changed

+58
-1
lines changed

3 files changed

+58
-1
lines changed

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,8 +255,11 @@ BlogArticle::select([
255255

256256
#### String
257257
```php
258-
use Tpetry\QueryExpressions\Function\String\Uuid4;
258+
use Tpetry\QueryExpressions\Function\String\{
259+
Concat, Uuid4
260+
};
259261

262+
new Concat(array $expressions);
260263
new Uuid4();
261264

262265
Schema::table('users', function (Blueprint $table): void {

src/Function/String/Concat.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tpetry\QueryExpressions\Function\String;
6+
7+
use Illuminate\Database\Grammar;
8+
use Tpetry\QueryExpressions\Concerns\IdentifiesDriver;
9+
use Tpetry\QueryExpressions\Function\Conditional\ManyArgumentsExpression;
10+
11+
class Concat extends ManyArgumentsExpression
12+
{
13+
use IdentifiesDriver;
14+
15+
public function getValue(Grammar $grammar): string
16+
{
17+
$expressions = $this->getExpressions($grammar);
18+
19+
return match ($this->identify($grammar)) {
20+
'mysql', 'sqlsrv' => sprintf('(concat(%s))', implode(',', $expressions)),
21+
'pgsql', 'sqlite' => sprintf('(%s)', implode('||', $expressions)),
22+
};
23+
}
24+
}

tests/Function/String/ConcatTest.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Illuminate\Database\Query\Expression;
6+
use Tpetry\QueryExpressions\Function\String\Concat;
7+
8+
it('can concat multiple columns')
9+
->expect(new Concat(['val1', 'val2', 'val3']))
10+
->toBeExecutable(['val1 varchar(255)', 'val2 varchar(255)', 'val3 varchar(255)'])
11+
->toBeMysql('(concat(`val1`,`val2`,`val3`))')
12+
->toBePgsql('("val1"||"val2"||"val3")')
13+
->toBeSqlite('("val1"||"val2"||"val3")')
14+
->toBeSqlsrv('(concat([val1],[val2],[val3]))');
15+
16+
it('can concat multiple expressions')
17+
->expect(new Concat([new Expression("'a'"), new Expression("'b'"), new Expression("'c'")]))
18+
->toBeExecutable()
19+
->toBeMysql("(concat('a','b','c'))")
20+
->toBePgsql("('a'||'b'||'c')")
21+
->toBeSqlite("('a'||'b'||'c')")
22+
->toBeSqlsrv("(concat('a','b','c'))");
23+
24+
it('can concat multiple columns and expressions')
25+
->expect(new Concat(['val1', 'val2', new Expression("'c'")]))
26+
->toBeExecutable(['val1 varchar(255)', 'val2 varchar(255)'])
27+
->toBeMysql("(concat(`val1`,`val2`,'c'))")
28+
->toBePgsql('("val1"||"val2"||\'c\')')
29+
->toBeSqlite('("val1"||"val2"||\'c\')')
30+
->toBeSqlsrv("(concat([val1],[val2],'c'))");

0 commit comments

Comments
 (0)