Files
grocy/services/DatabaseMigrationService.php

62 lines
2.1 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
{
2018-04-11 19:49:35 +02:00
$this->DatabaseService->ExecuteDbStatement("CREATE TABLE IF NOT EXISTS migrations (migration INTEGER NOT NULL PRIMARY KEY UNIQUE, execution_time_timestamp DATETIME DEFAULT (datetime('now', 'localtime')))");
$sqlMigrationFiles = array();
2018-04-12 21:13:38 +02:00
foreach (new \FilesystemIterator(__DIR__ . '/../migrations') as $file)
{
if ($file->getExtension() === 'sql')
{
$sqlMigrationFiles[$file->getBasename('.sql')] = $file->getPathname();
}
}
ksort($sqlMigrationFiles);
foreach($sqlMigrationFiles as $migrationNumber => $migrationFile)
{
$migrationNumber = ltrim($migrationNumber, '0');
$this->ExecuteSqlMigrationWhenNeeded($migrationNumber, file_get_contents($migrationFile));
2018-04-12 21:13:38 +02:00
}
2018-01-04 12:51:36 +01:00
$phpMigrationFiles = array();
foreach (new \FilesystemIterator(__DIR__ . '/../migrations') as $file)
{
if ($file->getExtension() === 'php')
{
$phpMigrationFiles[$file->getBasename('.php')] = $file->getPathname();
}
}
ksort($phpMigrationFiles);
foreach($phpMigrationFiles as $migrationNumber => $migrationFile)
2018-04-12 21:13:38 +02:00
{
$migrationNumber = ltrim($migrationNumber, '0');
$this->ExecutePhpMigrationWhenNeeded($migrationNumber, $migrationFile);
2018-04-12 21:13:38 +02:00
}
2017-04-16 23:11:03 +02:00
}
private function ExecuteSqlMigrationWhenNeeded(int $migrationId, string $sql)
2017-04-16 23:11:03 +02:00
{
2018-04-11 19:49:35 +02:00
$rowCount = $this->DatabaseService->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
{
2018-04-11 19:49:35 +02:00
$this->DatabaseService->ExecuteDbStatement($sql);
$this->DatabaseService->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
2017-04-16 23:11:03 +02:00
}
}
private function ExecutePhpMigrationWhenNeeded(int $migrationId, string $phpFile)
{
$rowCount = $this->DatabaseService->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn();
if (intval($rowCount) === 0)
{
include $phpFile;
$this->DatabaseService->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
}
}
2017-04-16 23:11:03 +02:00
}