Files
grocy/services/DatabaseMigrationService.php
T

53 lines
2.0 KiB
PHP
Raw Normal View History

2017-04-16 23:11:03 +02:00
<?php
2018-04-11 19:49:35 +02:00
namespace Grocy\Services;
class DatabaseMigrationService extends BaseService
2017-04-16 23:11:03 +02:00
{
2018-04-11 19:49:35 +02:00
public function MigrateDatabase()
2017-04-16 23:11:03 +02:00
{
$this->getDatabaseService()->ExecuteDbStatement("CREATE TABLE IF NOT EXISTS migrations (migration INTEGER NOT NULL PRIMARY KEY UNIQUE, execution_time_timestamp DATETIME DEFAULT (datetime('now', 'localtime')))");
2018-04-11 19:49:35 +02:00
$migrationFiles = array();
2018-04-12 21:13:38 +02:00
foreach (new \FilesystemIterator(__DIR__ . '/../migrations') as $file)
{
$migrationFiles[$file->getBasename()] = $file;
}
ksort($migrationFiles);
foreach($migrationFiles as $migrationKey => $migrationFile)
{
if($migrationFile->getExtension() === 'php')
{
$migrationNumber = ltrim($migrationFile->getBasename('.php'), '0');
$this->ExecutePhpMigrationWhenNeeded($migrationNumber, $migrationFile->getPathname());
}
else if($migrationFile->getExtension() === 'sql')
{
$migrationNumber = ltrim($migrationFile->getBasename('.sql'), '0');
$this->ExecuteSqlMigrationWhenNeeded($migrationNumber, file_get_contents($migrationFile->getPathname()));
}
2018-01-04 12:51:36 +01:00
}
2017-04-16 23:11:03 +02:00
}
private function ExecuteSqlMigrationWhenNeeded(int $migrationId, string $sql)
2017-04-16 23:11:03 +02:00
{
$rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn();
2017-04-21 11:52:24 +02:00
if (intval($rowCount) === 0)
2017-04-16 23:11:03 +02:00
{
$this->getDatabaseService()->ExecuteDbStatement($sql);
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
2017-04-16 23:11:03 +02:00
}
}
private function ExecutePhpMigrationWhenNeeded(int $migrationId, string $phpFile)
{
$rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn();
if (intval($rowCount) === 0)
{
include $phpFile;
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
}
}
2017-04-16 23:11:03 +02:00
}