Skip to content

Commit aa9d725

Browse files
committed
dynamic sequence creation
1 parent 857fea4 commit aa9d725

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/Space.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Exception;
88
use ReflectionClass;
99
use ReflectionMethod;
10+
use Tarantool\Client\Exception\RequestFailed;
1011
use Tarantool\Client\Keys;
1112
use Tarantool\Client\Request\InsertRequest;
1213
use Tarantool\Client\Response;
@@ -115,7 +116,15 @@ public function castIndex(array $fields): ?array
115116
public function create(array $data)
116117
{
117118
if (!array_key_exists('id', $data) && $this->fields[0] == 'id') {
118-
[$data['id']] = $this->mapper->client->call("box.sequence.$this->name:next");
119+
try {
120+
[$data['id']] = $this->mapper->client->call("box.sequence.$this->name:next");
121+
} catch (RequestFailed $e) {
122+
if (str_contains($e->getMessage(), "box.sequence.$this->name:next")) {
123+
$this->mapper->client->call('box.schema.sequence.create', $this->name);
124+
return $this->create($data);
125+
}
126+
throw $e;
127+
}
119128
}
120129
[$tuple] = $this->mapper->client->getSpaceById($this->id)->insert($this->getTuple($data));
121130
return $this->getInstance($tuple);

tests/MapperTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,28 @@ public function testCreateRow()
123123

124124
$tester->drop();
125125

126+
// 'id' field present, but sequence isn't created
127+
$tester = $mapper->createSpace('tester');
128+
$format = [
129+
[
130+
'name' => 'id',
131+
'type' => 'unsigned'
132+
],[
133+
'name' => 'value',
134+
'type' => 'string'
135+
]
136+
];
137+
$tester->setFormat($format);
138+
$mapper->client->call("box.space.tester:format", $format);
139+
$tester->addIndex(['id']);
140+
$testRow = ['value' => 'apple'];
141+
$tester->create($testRow);
142+
$result = $mapper->client->evaluate("return box.space.tester:select()")[0][0];
143+
$this->assertNotSame($result[0], 0);
144+
$this->assertSame($testRow['value'], $result[1]);
145+
$this->assertNotNull($mapper->client->evaluate('return box.sequence.tester')[0]);
146+
$tester->drop();
147+
126148
// There is 'id' field and it is first, sequense is created
127149
$tester = $mapper->createSpace('tester');
128150
$tester->addProperty('id', 'unsigned');

0 commit comments

Comments
 (0)