From 00255b04eb2b1601e14867dc6ecf028d87196656 Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Fri, 6 Nov 2020 19:43:05 +0100 Subject: [PATCH] Added migration to create new author_api_key_id in short_urls --- data/migrations/Version20201102113208.php | 84 +++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 data/migrations/Version20201102113208.php diff --git a/data/migrations/Version20201102113208.php b/data/migrations/Version20201102113208.php new file mode 100644 index 00000000..14ce6504 --- /dev/null +++ b/data/migrations/Version20201102113208.php @@ -0,0 +1,84 @@ +getTable('short_urls'); + $this->skipIf($shortUrls->hasColumn(self::API_KEY_COLUMN)); + + $shortUrls->addColumn(self::API_KEY_COLUMN, Types::BIGINT, [ + 'unsigned' => true, + 'notnull' => false, + ]); + + $shortUrls->addForeignKeyConstraint('api_keys', [self::API_KEY_COLUMN], ['id'], [ + 'onDelete' => 'SET NULL', + 'onUpdate' => 'RESTRICT', + ], 'FK_' . self::API_KEY_COLUMN); + } + + public function postUp(Schema $schema): void + { + // If there's only one API key and it's active, link all existing URLs with it + $qb = $this->connection->createQueryBuilder(); + $qb->select('id') + ->from('api_keys') + ->where($qb->expr()->eq('enabled', ':enabled')) + ->andWhere($qb->expr()->or( + $qb->expr()->isNull('expiration_date'), + $qb->expr()->gt('expiration_date', ':expiration'), + )) + ->setParameters([ + 'enabled' => true, + 'expiration' => Chronos::now()->toDateTimeString(), + ]); + + $id = $this->resolveOneApiKeyId($qb->execute()); + if ($id === null) { + return; + } + + $qb = $this->connection->createQueryBuilder(); + $qb->update('short_urls') + ->set(self::API_KEY_COLUMN, ':apiKeyId') + ->setParameter('apiKeyId', $id) + ->execute(); + } + + private function resolveOneApiKeyId(Result $result): ?string + { + $results = []; + while ($row = $result->fetchAssociative()) { + // As soon as we have to iterate more than once, then we cannot resolve a single API key + if (! empty($results)) { + return null; + } + + $results[] = $row['id'] ?? null; + } + + return $results[0] ?? null; + } + + public function down(Schema $schema): void + { + $shortUrls = $schema->getTable('short_urls'); + $this->skipIf(! $shortUrls->hasColumn(self::API_KEY_COLUMN)); + + $shortUrls->removeForeignKey('FK_' . self::API_KEY_COLUMN); + $shortUrls->dropColumn(self::API_KEY_COLUMN); + } +}