1: <?php
2:
3: namespace Baril\Orderly\Mixins;
4:
5: use Illuminate\Database\Query\Grammars\MySqlGrammar;
6: use Illuminate\Database\Query\Grammars\PostgresGrammar;
7: use Illuminate\Database\Query\Grammars\SQLiteGrammar;
8: use Illuminate\Database\Query\Grammars\SqlServerGrammar;
9: use LogicException;
10:
11: /**
12: * @mixin \Illuminate\Database\Query\Grammars\Grammar
13: */
14: class Grammar
15: {
16: public function compileCase()
17: {
18: return function ($expression, array $cases, $else = null): string {
19: /** @var \Illuminate\Database\Query\Grammars\Grammar $this */
20: $cases = implode(' ', array_map(function ($when, $then) {
21: return "when {$this->quoteString($when)} then {$this->quoteString($then)}";
22: }, array_keys($cases), array_values($cases)));
23: $else = is_null($else) ? '' : "else {$this->quoteString($else)}";
24: return "case {$this->wrap($expression)} $cases $else END";
25: };
26: }
27:
28: public function supportsUpdateWithOrderBy()
29: {
30: return function (): bool {
31: return $this instanceof MySqlGrammar || $this instanceof SQLiteGrammar;
32: };
33: }
34:
35: public function supportsSequences()
36: {
37: return function (): bool {
38: return !($this instanceof SQLiteGrammar);
39: };
40: }
41:
42: public function compileCreateSequence()
43: {
44: return function (string $name, int $start = 1, int $increment = 1): string {
45: switch (true) {
46: case $this instanceof MySqlGrammar:
47: $start -= $increment;
48: return "set @$name := $start";
49: case $this instanceof PostgresGrammar:
50: case $this instanceof SqlServerGrammar:
51: return "create sequence {$this->wrap($name)} start with $start increment by $increment";
52: default:
53: throw new LogicException('This grammar doesn\'t support sequences!');
54: }
55: };
56: }
57:
58: public function compileNextVal()
59: {
60: return function (string $name, int $increment = 1): string {
61: switch (true) {
62: case $this instanceof MySqlGrammar:
63: return "@$name := @$name + $increment";
64: case $this instanceof PostgresGrammar:
65: return "nextval({$this->quoteString($name)})";
66: case $this instanceof SqlServerGrammar:
67: return "next value for {$this->wrap($name)}";
68: default:
69: throw new LogicException('This grammar doesn\'t support sequences!');
70: }
71: };
72: }
73:
74: public function compileDropSequence()
75: {
76: return function (string $name): string {
77: switch (true) {
78: case $this instanceof MySqlGrammar:
79: return 'select 1';
80: case $this instanceof PostgresGrammar:
81: case $this instanceof SqlServerGrammar:
82: return "drop sequence {$this->wrap($name)}";
83: default:
84: throw new LogicException('This grammar doesn\'t support sequences!');
85: }
86: };
87: }
88: }
89: