|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Tarantool\Mapper\Plugin; |
|
6
|
|
|
|
|
7
|
|
|
use Exception; |
|
8
|
|
|
use Tarantool\Client\Schema\Operations; |
|
9
|
|
|
use Tarantool\Mapper\Entity; |
|
10
|
|
|
use Tarantool\Mapper\Plugin; |
|
11
|
|
|
use Tarantool\Mapper\Procedure\CreateSequence; |
|
12
|
|
|
use Tarantool\Mapper\Space; |
|
13
|
|
|
|
|
14
|
|
|
class Sequence extends Plugin |
|
15
|
|
|
{ |
|
16
|
|
|
public function generateKey(Entity $instance, Space $space) : Entity |
|
17
|
|
|
{ |
|
18
|
|
|
$primary = $space->getPrimaryIndex(); |
|
19
|
|
|
if (count($primary['parts']) == 1) { |
|
20
|
|
|
$key = $space->getFormat()[$primary['parts'][0][0]]['name']; |
|
21
|
|
|
if (!property_exists($instance, $key) || is_null($instance->$key)) { |
|
22
|
|
|
$instance->$key = $this->generateValue($space); |
|
23
|
|
|
} |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
return $instance; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
private $sequences = []; |
|
30
|
|
|
|
|
31
|
|
|
public function initializeSequence(Space $space) |
|
32
|
|
|
{ |
|
33
|
|
|
if (!count($this->sequences)) { |
|
34
|
|
|
foreach ($this->mapper->find('_vsequence') as $sq) { |
|
35
|
|
|
$this->sequences[$sq->name] = true; |
|
36
|
|
|
} |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
$name = $space->getName(); |
|
40
|
|
|
|
|
41
|
|
|
if (!array_key_exists($name, $this->sequences)) { |
|
42
|
|
|
$primaryIndex = $space->getIndexes()[0]; |
|
43
|
|
|
if (count($primaryIndex['parts']) !== 1) { |
|
44
|
|
|
throw new Exception("Composite primary key"); |
|
45
|
|
|
} |
|
46
|
|
|
$this->mapper |
|
47
|
|
|
->getPlugin(Procedure::class) |
|
48
|
|
|
->get(CreateSequence::class) |
|
49
|
|
|
->execute($name, $primaryIndex['name'], $primaryIndex['parts'][0][0]+1); |
|
50
|
|
|
|
|
51
|
|
|
$this->mapper->getRepository('_vsequence')->flushCache(); |
|
52
|
|
|
|
|
53
|
|
|
$this->sequences[$name] = true; |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
private function generateValue(Space $space) : int |
|
58
|
|
|
{ |
|
59
|
|
|
$this->initializeSequence($space); |
|
60
|
|
|
|
|
61
|
|
|
$next = $this->mapper->getClient() |
|
62
|
|
|
->call('box.sequence.'.$space->getName().':next'); |
|
63
|
|
|
|
|
64
|
|
|
return $next[0]; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|