Skip to content

Instantly share code, notes, and snippets.

@fritz-gerneth
Created March 15, 2018 11:46
Show Gist options
  • Save fritz-gerneth/1b35ae896b8b9e4a733d8685ef53e29e to your computer and use it in GitHub Desktop.
Save fritz-gerneth/1b35ae896b8b9e4a733d8685ef53e29e to your computer and use it in GitHub Desktop.
<?php
final class BigIdSingleStreamStrategy implements PersistenceStrategy, HasQueryHint
{
/**
* @param string $tableName
* @return string[]
*/
public function createSchema(string $tableName): array
{
$statement = <<<EOT
CREATE TABLE `$tableName` (
`no` BIGINT(20) NOT NULL AUTO_INCREMENT,
`event_id` CHAR(36) COLLATE utf8_bin NOT NULL,
`event_name` VARCHAR(100) COLLATE utf8_bin NOT NULL,
`payload` JSON NOT NULL,
`metadata` JSON NOT NULL,
`created_at` DATETIME(6) NOT NULL,
`aggregate_version` INT(11) UNSIGNED GENERATED ALWAYS AS (JSON_EXTRACT(metadata, '$._aggregate_version')) STORED NOT NULL,
`aggregate_id` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_bin GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(metadata, '$._aggregate_id'))) STORED NOT NULL,
`aggregate_type` VARCHAR(200) GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(metadata, '$._aggregate_type'))) STORED NOT NULL,
PRIMARY KEY (`no`),
UNIQUE KEY `ix_event_id` (`event_id`),
UNIQUE KEY `ix_unique_event` (`aggregate_type`, `aggregate_id`, `aggregate_version`),
KEY `ix_query_aggregate` (`aggregate_type`,`aggregate_id`,`no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
EOT;
return [$statement];
}
public function columnNames(): array
{
return [
'event_id',
'event_name',
'payload',
'metadata',
'created_at',
];
}
public function prepareData(Iterator $streamEvents): array
{
$data = [];
foreach ($streamEvents as $event) {
$data[] = $event->uuid()->toString();
$data[] = $event->messageName();
$data[] = json_encode($event->payload());
$data[] = json_encode($event->metadata());
$data[] = $event->createdAt()->format('Y-m-d\TH:i:s.u');
}
return $data;
}
public function generateTableName(StreamName $streamName): string
{
return '_' . preg_replace('/[^a-zA-Z0-9\-_]/', '', str_replace('-', '_', $streamName));
}
public function indexName(): string
{
return 'ix_query_aggregate';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment