-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathDoctrineDbalStore.php
More file actions
534 lines (452 loc) · 18.1 KB
/
DoctrineDbalStore.php
File metadata and controls
534 lines (452 loc) · 18.1 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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
<?php
declare(strict_types=1);
namespace Patchlevel\EventSourcing\Store;
use Closure;
use Doctrine\DBAL\ArrayParameterType;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Doctrine\DBAL\Platforms\MariaDBPlatform;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\DBAL\Platforms\PostgreSQLPlatform;
use Doctrine\DBAL\Platforms\SQLitePlatform;
use Doctrine\DBAL\Query\QueryBuilder;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Types\Types;
use Patchlevel\EventSourcing\Aggregate\AggregateHeader;
use Patchlevel\EventSourcing\Message\HeaderNotFound;
use Patchlevel\EventSourcing\Message\Message;
use Patchlevel\EventSourcing\Message\Serializer\DefaultHeadersSerializer;
use Patchlevel\EventSourcing\Message\Serializer\HeadersSerializer;
use Patchlevel\EventSourcing\Schema\DoctrineSchemaConfigurator;
use Patchlevel\EventSourcing\Serializer\EventSerializer;
use Patchlevel\EventSourcing\Store\Criteria\AggregateIdCriterion;
use Patchlevel\EventSourcing\Store\Criteria\AggregateNameCriterion;
use Patchlevel\EventSourcing\Store\Criteria\ArchivedCriterion;
use Patchlevel\EventSourcing\Store\Criteria\Criteria;
use Patchlevel\EventSourcing\Store\Criteria\EventsCriterion;
use Patchlevel\EventSourcing\Store\Criteria\FromIndexCriterion;
use Patchlevel\EventSourcing\Store\Criteria\FromPlayheadCriterion;
use Patchlevel\EventSourcing\Store\Criteria\ToIndexCriterion;
use Patchlevel\EventSourcing\Store\Header\IndexHeader;
use PDO;
use function array_fill;
use function array_filter;
use function array_merge;
use function array_values;
use function class_exists;
use function count;
use function explode;
use function floor;
use function implode;
use function in_array;
use function is_int;
use function is_string;
use function sprintf;
final class DoctrineDbalStore implements Store, SubscriptionStore, DoctrineSchemaConfigurator
{
/**
* PostgreSQL has a limit of 65535 parameters in a single query.
*/
private const MAX_UNSIGNED_SMALL_INT = 65_535;
/**
* Default lock id for advisory lock.
*/
private const DEFAULT_LOCK_ID = 133742;
private readonly HeadersSerializer $headersSerializer;
/** @var array{table_name: string, aggregate_id_type: 'string'|'uuid', locking: bool, lock_id: int, lock_timeout: int} */
private readonly array $config;
private bool $hasLock = false;
/** @param array{table_name?: string, aggregate_id_type?: 'string'|'uuid', locking?: bool, lock_id?: int, lock_timeout?: int} $config */
public function __construct(
private readonly Connection $connection,
private readonly EventSerializer $eventSerializer,
HeadersSerializer|null $headersSerializer = null,
array $config = [],
) {
$this->headersSerializer = $headersSerializer ?? DefaultHeadersSerializer::createDefault();
$this->config = array_merge([
'table_name' => 'eventstore',
'aggregate_id_type' => 'uuid',
'locking' => true,
'lock_id' => self::DEFAULT_LOCK_ID,
'lock_timeout' => -1,
], $config);
}
public function load(
Criteria|null $criteria = null,
int|null $limit = null,
int|null $offset = null,
bool $backwards = false,
): DoctrineDbalStoreStream {
$builder = $this->connection->createQueryBuilder()
->select('*')
->from($this->config['table_name'])
->orderBy('id', $backwards ? 'DESC' : 'ASC');
$this->applyCriteria($builder, $criteria ?? new Criteria());
$builder->setMaxResults($limit);
$builder->setFirstResult($offset ?? 0);
return new DoctrineDbalStoreStream(
$this->connection->executeQuery(
$builder->getSQL(),
$builder->getParameters(),
$builder->getParameterTypes(),
),
$this->eventSerializer,
$this->headersSerializer,
$this->connection->getDatabasePlatform(),
);
}
public function count(Criteria|null $criteria = null): int
{
$builder = $this->connection->createQueryBuilder()
->select('COUNT(*)')
->from($this->config['table_name']);
$this->applyCriteria($builder, $criteria ?? new Criteria());
$result = $this->connection->fetchOne(
$builder->getSQL(),
$builder->getParameters(),
$builder->getParameterTypes(),
);
if (!is_int($result) && !is_string($result)) {
throw new WrongQueryResult();
}
return (int)$result;
}
private function applyCriteria(QueryBuilder $builder, Criteria $criteria): void
{
$criteriaList = $criteria->all();
foreach ($criteriaList as $criterion) {
switch ($criterion::class) {
case AggregateNameCriterion::class:
$builder->andWhere('aggregate = :aggregate');
$builder->setParameter('aggregate', $criterion->aggregateName);
break;
case AggregateIdCriterion::class:
$builder->andWhere('aggregate_id = :id');
$builder->setParameter('id', $criterion->aggregateId);
break;
case FromPlayheadCriterion::class:
$builder->andWhere('playhead > :playhead');
$builder->setParameter('playhead', $criterion->fromPlayhead, Types::INTEGER);
break;
case ArchivedCriterion::class:
$builder->andWhere('archived = :archived');
$builder->setParameter('archived', $criterion->archived, Types::BOOLEAN);
break;
case FromIndexCriterion::class:
$builder->andWhere('id > :fromIndex');
$builder->setParameter('fromIndex', $criterion->fromIndex, Types::INTEGER);
break;
case ToIndexCriterion::class:
$builder->andWhere('id < :toIndex');
$builder->setParameter('toIndex', $criterion->toIndex, Types::INTEGER);
break;
case EventsCriterion::class:
$builder->andWhere('event IN (:events)');
$builder->setParameter('events', $criterion->events, ArrayParameterType::STRING);
break;
default:
throw new UnsupportedCriterion($criterion::class);
}
}
}
public function save(Message ...$messages): void
{
if ($messages === []) {
return;
}
$this->transactional(
function () use ($messages): void {
/** @var array<string, int> $achievedUntilPlayhead */
$achievedUntilPlayhead = [];
$booleanType = Type::getType(Types::BOOLEAN);
$dateTimeType = Type::getType(Types::DATETIMETZ_IMMUTABLE);
$columns = [
'aggregate',
'aggregate_id',
'playhead',
'event',
'payload',
'recorded_on',
'new_stream_start',
'archived',
'custom_headers',
];
$columnsLength = count($columns);
$batchSize = (int)floor(self::MAX_UNSIGNED_SMALL_INT / $columnsLength);
$placeholder = implode(', ', array_fill(0, $columnsLength, '?'));
$parameters = [];
$placeholders = [];
/** @var array<int<0, max>, Type> $types */
$types = [];
$position = 0;
foreach ($messages as $message) {
/** @var int<0, max> $offset */
$offset = $position * $columnsLength;
$placeholders[] = $placeholder;
$data = $this->eventSerializer->serialize($message->event());
try {
$aggregateHeader = $message->header(AggregateHeader::class);
} catch (HeaderNotFound $e) {
throw new MissingDataForStorage($e->name, $e);
}
$parameters[] = $aggregateHeader->aggregateName;
$parameters[] = $aggregateHeader->aggregateId;
$parameters[] = $aggregateHeader->playhead;
$parameters[] = $data->name;
$parameters[] = $data->payload;
$parameters[] = $aggregateHeader->recordedOn;
$types[$offset + 5] = $dateTimeType;
$streamStart = $message->hasHeader(StreamStartHeader::class);
if ($streamStart) {
$key = $aggregateHeader->aggregateName . '/' . $aggregateHeader->aggregateId;
$achievedUntilPlayhead[$key] = $aggregateHeader->playhead;
}
$parameters[] = $streamStart;
$types[$offset + 6] = $booleanType;
$parameters[] = $message->hasHeader(ArchivedHeader::class);
$types[$offset + 7] = $booleanType;
$parameters[] = $this->headersSerializer->serialize($this->getCustomHeaders($message));
$position++;
if ($position !== $batchSize) {
continue;
}
$this->executeSave($columns, $placeholders, $parameters, $types, $this->connection);
$parameters = [];
$placeholders = [];
$types = [];
$position = 0;
}
if ($position !== 0) {
$this->executeSave($columns, $placeholders, $parameters, $types, $this->connection);
}
foreach ($achievedUntilPlayhead as $key => $playhead) {
[$aggregateName, $aggregateId] = explode('/', $key);
$this->connection->executeStatement(
sprintf(
<<<'SQL'
UPDATE %s
SET archived = true
WHERE aggregate = :aggregate
AND aggregate_id = :aggregate_id
AND playhead < :playhead
AND archived = false
SQL,
$this->config['table_name'],
),
[
'aggregate' => $aggregateName,
'aggregate_id' => $aggregateId,
'playhead' => $playhead,
],
);
}
},
);
}
/**
* @param Closure():ClosureReturn $function
*
* @template ClosureReturn
*/
public function transactional(Closure $function): void
{
if ($this->hasLock || !$this->config['locking']) {
$this->connection->transactional($function);
} else {
$this->connection->transactional(function () use ($function): void {
$this->lock();
try {
$function();
} finally {
$this->unlock();
}
});
}
}
public function configureSchema(Schema $schema, Connection $connection): void
{
if ($this->connection !== $connection) {
return;
}
$table = $schema->createTable($this->config['table_name']);
$table->addColumn('id', Types::BIGINT)
->setAutoincrement(true);
$table->addColumn('aggregate', Types::STRING)
->setLength(255)
->setNotnull(true);
$table->addColumn(
'aggregate_id',
$this->config['aggregate_id_type'] === 'uuid' ? Types::GUID : Types::STRING,
)
->setLength(36)
->setNotnull(true);
$table->addColumn('playhead', Types::INTEGER)
->setNotnull(true);
$table->addColumn('event', Types::STRING)
->setLength(255)
->setNotnull(true);
$table->addColumn('payload', Types::JSON)
->setPlatformOption('jsonb', true)
->setNotnull(true);
$table->addColumn('recorded_on', Types::DATETIMETZ_IMMUTABLE)
->setNotnull(true);
$table->addColumn('new_stream_start', Types::BOOLEAN)
->setNotnull(true)
->setDefault(false);
$table->addColumn('archived', Types::BOOLEAN)
->setNotnull(true)
->setDefault(false);
$table->addColumn('custom_headers', Types::JSON)
->setPlatformOption('jsonb', true)
->setNotnull(true);
$table->setPrimaryKey(['id']);
$table->addUniqueIndex(['aggregate', 'aggregate_id', 'playhead']);
$table->addIndex(['aggregate', 'aggregate_id', 'playhead', 'archived']);
}
/** @return list<object> */
private function getCustomHeaders(Message $message): array
{
$filteredHeaders = [
IndexHeader::class,
AggregateHeader::class,
StreamStartHeader::class,
ArchivedHeader::class,
];
return array_values(
array_filter(
$message->headers(),
static fn (object $header) => !in_array($header::class, $filteredHeaders, true),
),
);
}
public function supportSubscription(): bool
{
return $this->connection->getDatabasePlatform() instanceof PostgreSQLPlatform && class_exists(PDO::class);
}
public function wait(int $timeoutMilliseconds): void
{
if (!$this->supportSubscription()) {
return;
}
$this->connection->executeStatement(sprintf('LISTEN "%s"', $this->config['table_name']));
/** @var PDO $nativeConnection */
$nativeConnection = $this->connection->getNativeConnection();
$nativeConnection->pgsqlGetNotify(PDO::FETCH_ASSOC, $timeoutMilliseconds);
}
public function setupSubscription(): void
{
if (!$this->supportSubscription()) {
return;
}
$functionName = $this->createTriggerFunctionName();
$this->connection->executeStatement(sprintf(
<<<'SQL'
CREATE OR REPLACE FUNCTION %1$s() RETURNS TRIGGER AS $$
BEGIN
PERFORM pg_notify('%2$s', 'update');
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
SQL,
$functionName,
$this->config['table_name'],
));
$this->connection->executeStatement(sprintf(
'DROP TRIGGER IF EXISTS notify_trigger ON %s;',
$this->config['table_name'],
));
$this->connection->executeStatement(sprintf(
'CREATE TRIGGER notify_trigger AFTER INSERT OR UPDATE ON %1$s FOR EACH ROW EXECUTE PROCEDURE %2$s();',
$this->config['table_name'],
$functionName,
));
}
public function connection(): Connection
{
return $this->connection;
}
private function createTriggerFunctionName(): string
{
$tableConfig = explode('.', $this->config['table_name']);
if (count($tableConfig) === 1) {
return sprintf('notify_%1$s', $tableConfig[0]);
}
return sprintf('%1$s.notify_%2$s', $tableConfig[0], $tableConfig[1]);
}
/**
* @param array<string> $columns
* @param array<string> $placeholders
* @param list<mixed> $parameters
* @param array<0|positive-int, Type> $types
*/
private function executeSave(
array $columns,
array $placeholders,
array $parameters,
array $types,
Connection $connection,
): void {
$query = sprintf(
"INSERT INTO %s (%s) VALUES\n(%s)",
$this->config['table_name'],
implode(', ', $columns),
implode("),\n(", $placeholders),
);
try {
$connection->executeStatement($query, $parameters, $types);
} catch (UniqueConstraintViolationException $e) {
throw new UniqueConstraintViolation($e);
}
}
private function lock(): void
{
$this->hasLock = true;
$platform = $this->connection->getDatabasePlatform();
if ($platform instanceof PostgreSQLPlatform) {
$this->connection->executeStatement(
sprintf(
'SELECT pg_advisory_xact_lock(%s)',
$this->config['lock_id'],
),
);
return;
}
if ($platform instanceof MariaDBPlatform || $platform instanceof MySQLPlatform) {
$this->connection->fetchAllAssociative(
sprintf(
'SELECT GET_LOCK("%s", %d)',
$this->config['lock_id'],
$this->config['lock_timeout'],
),
);
return;
}
if ($platform instanceof SQLitePlatform) {
return; // sql locking is not needed because of file locking
}
throw new LockingNotImplemented($platform::class);
}
private function unlock(): void
{
$this->hasLock = false;
$platform = $this->connection->getDatabasePlatform();
if ($platform instanceof PostgreSQLPlatform) {
return; // lock is released automatically after transaction
}
if ($platform instanceof MariaDBPlatform || $platform instanceof MySQLPlatform) {
$this->connection->fetchAllAssociative(
sprintf(
'SELECT RELEASE_LOCK("%s")',
$this->config['lock_id'],
),
);
return;
}
if ($platform instanceof SQLitePlatform) {
return; // sql locking is not needed because of file locking
}
throw new LockingNotImplemented($platform::class);
}
}