forked from tempestphp/tempest-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonStatement.php
More file actions
47 lines (40 loc) · 1.4 KB
/
JsonStatement.php
File metadata and controls
47 lines (40 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
declare(strict_types=1);
namespace Tempest\Database\QueryStatements;
use Tempest\Database\Config\DatabaseDialect;
use Tempest\Database\Exceptions\DefaultValueWasInvalid;
use Tempest\Database\QueryStatement;
final readonly class JsonStatement implements QueryStatement
{
public function __construct(
private string $name,
private bool $nullable = false,
private ?string $default = null,
) {}
public function compile(DatabaseDialect $dialect): string
{
if ($this->default && json_validate($this->default) === false) {
throw new DefaultValueWasInvalid($this->name, $this->default);
}
$name = $dialect->quoteIdentifier($this->name);
return match ($dialect) {
DatabaseDialect::MYSQL => sprintf(
'%s JSON %s',
$name,
$this->nullable ? '' : 'NOT NULL',
),
DatabaseDialect::SQLITE => sprintf(
'%s TEXT %s %s',
$name,
$this->default !== null ? "DEFAULT '{$this->default}'" : '',
$this->nullable ? '' : 'NOT NULL',
),
DatabaseDialect::POSTGRESQL => sprintf(
'%s JSONB %s %s',
$name,
$this->default !== null ? "DEFAULT ('{$this->default}')" : '',
$this->nullable ? '' : 'NOT NULL',
),
};
}
}