1
0
Fork 0
mirror of synced 2024-06-01 10:29:48 +12:00
appwrite/src/Appwrite/Migration/Migration.php

110 lines
2.4 KiB
PHP
Raw Normal View History

2021-01-14 05:51:02 +13:00
<?php
namespace Appwrite\Migration;
use Appwrite\Database\Document;
use Appwrite\Database\Database;
use Utopia\CLI\Console;
use Utopia\Exception;
2021-01-19 03:43:55 +13:00
use PDO;
2021-01-14 05:51:02 +13:00
abstract class Migration
{
2021-01-19 03:43:55 +13:00
/**
* @var PDO
*/
protected PDO $db;
2021-01-19 03:43:55 +13:00
/**
* @var int
*/
protected int $limit = 30;
2021-01-19 03:43:55 +13:00
/**
* @var Document
*/
protected Document $project;
2021-01-19 03:43:55 +13:00
/**
* @var Database
*/
protected Database $projectDB;
/**
* Migration constructor.
2021-01-19 03:43:55 +13:00
*
* @param PDO $pdo
*/
2021-01-19 03:43:55 +13:00
public function __construct(PDO $db)
{
$this->db = $db;
}
/**
* Set project for migration.
2021-01-19 03:43:55 +13:00
*
* @param Document $project
* @param Database $projectDB
2021-01-21 22:57:15 +13:00
*
* @return Migration
*/
public function setProject(Document $project, Database $projectDB): Migration
{
$this->project = $project;
$this->projectDB = $projectDB;
$this->projectDB->setNamespace('app_' . $project->getId());
return $this;
}
/**
* Iterates through every document.
*
2021-01-19 03:43:55 +13:00
* @param callable $callback
*/
2021-01-21 22:57:15 +13:00
public function forEachDocument(callable $callback): void
{
2021-01-21 22:57:15 +13:00
$sum = $this->limit;
$offset = 0;
2021-01-21 22:57:15 +13:00
while ($sum >= $this->limit) {
$all = $this->projectDB->getCollection([
'limit' => $this->limit,
'offset' => $offset,
'orderType' => 'DESC',
]);
$sum = \count($all);
Console::log('Migrating: ' . $offset . ' / ' . $this->projectDB->getSum());
foreach ($all as $document) {
$document = call_user_func($callback, $document);
if (empty($document->getId())) {
throw new Exception('Missing ID');
}
try {
$new = $this->projectDB->overwriteDocument($document->getArrayCopy());
} catch (\Throwable $th) {
Console::error('Failed to update document: ' . $th->getMessage());
continue;
}
if ($new->getId() !== $document->getId()) {
throw new Exception('Duplication Error');
}
}
$offset += $this->limit;
}
}
/**
* Executes migration for set project.
*/
abstract public function execute(): void;
2021-01-14 05:51:02 +13:00
}