Files
grocy/services/DatabaseMigrationService.php

35 lines
1.2 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')))");
2018-04-12 21:13:38 +02:00
$migrationFiles = array();
foreach (new \FilesystemIterator(__DIR__ . '/../migrations') as $file)
{
$migrationFiles[$file->getBasename('.sql')] = $file->getPathname();
}
ksort($migrationFiles);
2018-01-04 12:51:36 +01:00
2018-04-12 21:13:38 +02:00
foreach($migrationFiles as $migrationNumber => $migrationFile)
{
$migrationNumber = ltrim($migrationNumber, '0');
$this->ExecuteMigrationWhenNeeded($migrationNumber, file_get_contents($migrationFile));
}
2017-04-16 23:11:03 +02:00
}
2018-04-11 19:49:35 +02:00
private function ExecuteMigrationWhenNeeded(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
}
}
}