-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDBALEventStore.php
302 lines (249 loc) · 9.4 KB
/
DBALEventStore.php
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
<?php
/*
* This file is part of the broadway/broadway package.
*
* (c) Qandidate.com <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Broadway\EventStore;
use Broadway\Domain\DateTime;
use Broadway\Domain\DomainEventStream;
use Broadway\Domain\DomainEventStreamInterface;
use Broadway\Domain\DomainMessage;
use Broadway\EventStore\Exception\InvalidIdentifierException;
use Broadway\EventStore\Management\Criteria;
use Broadway\EventStore\Management\CriteriaNotSupportedException;
use Broadway\EventStore\Management\EventStoreManagementInterface;
use Broadway\Serializer\SerializerInterface;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Version;
use Rhumsaa\Uuid\Uuid;
/**
* Event store using a relational database as storage.
*
* The implementation uses doctrine DBAL for the communication with the
* underlying data store.
*/
class DBALEventStore implements EventStoreInterface, EventStoreManagementInterface
{
private $connection;
private $payloadSerializer;
private $metadataSerializer;
private $loadStatement = null;
private $tableName;
private $useBinary;
/**
* @param string $tableName
*/
public function __construct(
Connection $connection,
SerializerInterface $payloadSerializer,
SerializerInterface $metadataSerializer,
$tableName,
$useBinary = false
) {
$this->connection = $connection;
$this->payloadSerializer = $payloadSerializer;
$this->metadataSerializer = $metadataSerializer;
$this->tableName = $tableName;
$this->useBinary = (bool) $useBinary;
if ($this->useBinary && Version::compare('2.5.0') >= 0) {
throw new \InvalidArgumentException(
'The Binary storage is only available with Doctrine DBAL >= 2.5.0'
);
}
}
/**
* {@inheritDoc}
*/
public function load($id)
{
$statement = $this->prepareLoadStatement();
$statement->bindValue(1, $this->convertIdentifierToStorageValue($id));
$statement->execute();
$events = [];
while ($row = $statement->fetch()) {
$events[] = $this->deserializeEvent($row);
}
if (empty($events)) {
throw new EventStreamNotFoundException(sprintf('EventStream not found for aggregate with id %s for table %s', $id, $this->tableName));
}
return new DomainEventStream($events);
}
/**
* {@inheritDoc}
*/
public function append($id, DomainEventStreamInterface $eventStream)
{
// noop to ensure that an error will be thrown early if the ID
// is not something that can be converted to a string. If we
// let this move on without doing this DBAL will eventually
// give us a hard time but the true reason for the problem
// will be obfuscated.
$id = (string) $id;
$this->connection->beginTransaction();
try {
foreach ($eventStream as $domainMessage) {
$this->insertMessage($this->connection, $domainMessage);
}
$this->connection->commit();
} catch (DBALException $exception) {
$this->connection->rollBack();
throw DBALEventStoreException::create($exception);
}
}
private function insertMessage(Connection $connection, DomainMessage $domainMessage)
{
$data = [
'uuid' => $this->convertIdentifierToStorageValue((string) $domainMessage->getId()),
'playhead' => $domainMessage->getPlayhead(),
'metadata' => json_encode($this->metadataSerializer->serialize($domainMessage->getMetadata())),
'payload' => json_encode($this->payloadSerializer->serialize($domainMessage->getPayload())),
'recorded_on' => $domainMessage->getRecordedOn()->toString(),
'type' => $domainMessage->getType(),
];
$connection->insert($this->tableName, $data);
}
/**
* @return \Doctrine\DBAL\Schema\Table|null
*/
public function configureSchema(Schema $schema)
{
if ($schema->hasTable($this->tableName)) {
return null;
}
return $this->configureTable();
}
public function configureTable()
{
$schema = new Schema();
$uuidColumnDefinition = [
'type' => 'guid',
'params' => [
'length' => 36,
],
];
if ($this->useBinary) {
$uuidColumnDefinition['type'] = 'binary';
$uuidColumnDefinition['params'] = [
'length' => 16,
'fixed' => true,
];
}
$table = $schema->createTable($this->tableName);
$table->addColumn('id', 'integer', ['autoincrement' => true]);
$table->addColumn('uuid', $uuidColumnDefinition['type'], $uuidColumnDefinition['params']);
$table->addColumn('playhead', 'integer', ['unsigned' => true]);
$table->addColumn('payload', 'text');
$table->addColumn('metadata', 'text');
$table->addColumn('recorded_on', 'string', ['length' => 32]);
$table->addColumn('type', 'text');
$table->setPrimaryKey(['id']);
$table->addUniqueIndex(['uuid', 'playhead']);
return $table;
}
private function prepareLoadStatement()
{
if (null === $this->loadStatement) {
$query = 'SELECT uuid, playhead, metadata, payload, recorded_on
FROM ' . $this->tableName . '
WHERE uuid = ?
ORDER BY playhead ASC';
$this->loadStatement = $this->connection->prepare($query);
}
return $this->loadStatement;
}
private function deserializeEvent($row)
{
return new DomainMessage(
$this->convertStorageValueToIdentifier($row['uuid']),
$row['playhead'],
$this->metadataSerializer->deserialize(json_decode($row['metadata'], true)),
$this->payloadSerializer->deserialize(json_decode($row['payload'], true)),
DateTime::fromString($row['recorded_on'])
);
}
private function convertIdentifierToStorageValue($id)
{
if ($this->useBinary) {
try {
return Uuid::fromString($id)->getBytes();
} catch (\Exception $e) {
throw new InvalidIdentifierException(
'Only valid UUIDs are allowed to by used with the binary storage mode.'
);
}
}
return $id;
}
private function convertStorageValueToIdentifier($id)
{
if ($this->useBinary) {
try {
return Uuid::fromBytes($id)->toString();
} catch (\Exception $e) {
throw new InvalidIdentifierException(
'Could not convert binary storage value to UUID.'
);
}
}
return $id;
}
public function visitEvents(Criteria $criteria, EventVisitorInterface $eventVisitor)
{
$statement = $this->prepareVisitEventsStatement($criteria);
$statement->execute();
while ($row = $statement->fetch()) {
$domainMessage = $this->deserializeEvent($row);
$eventVisitor->doWithEvent($domainMessage);
}
}
private function prepareVisitEventsStatement(Criteria $criteria)
{
list($where, $bindValues, $bindValueTypes) = $this->prepareVisitEventsStatementWhereAndBindValues($criteria);
$query = 'SELECT uuid, playhead, metadata, payload, recorded_on
FROM ' . $this->tableName . '
' . $where . '
ORDER BY id ASC';
$statement = $this->connection->executeQuery($query, $bindValues, $bindValueTypes);
return $statement;
}
private function prepareVisitEventsStatementWhereAndBindValues(Criteria $criteria)
{
if ($criteria->getAggregateRootTypes()) {
throw new CriteriaNotSupportedException(
'DBAL implementation cannot support criteria based on aggregate root types.'
);
}
$bindValues = [];
$bindValueTypes = [];
$criteriaTypes = [];
if ($criteria->getAggregateRootIds()) {
$criteriaTypes[] = 'uuid IN (:uuids)';
if ($this->useBinary) {
$bindValues['uuids'] = [];
foreach ($criteria->getAggregateRootIds() as $id) {
$bindValues['uuids'][] = $this->convertIdentifierToStorageValue($id);
}
$bindValueTypes['uuids'] = Connection::PARAM_STR_ARRAY;
} else {
$bindValues['uuids'] = $criteria->getAggregateRootIds();
$bindValueTypes['uuids'] = Connection::PARAM_STR_ARRAY;
}
}
if ($criteria->getEventTypes()) {
$criteriaTypes[] = 'type IN (:types)';
$bindValues['types'] = $criteria->getEventTypes();
$bindValueTypes['types'] = Connection::PARAM_STR_ARRAY;
}
if (! $criteriaTypes) {
return ['', [], []];
}
$where = 'WHERE ' . join(' AND ', $criteriaTypes);
return [$where, $bindValues, $bindValueTypes];
}
}