Files
Woles-Framework/app/Core/Database/Migration.php

106 lines
2.4 KiB
PHP
Raw Normal View History

<?php
namespace App\Core\Database;
/**
* NovaCore Database Migration
* Base migration class
*/
abstract class Migration
{
protected Connection $connection;
public function __construct()
{
$this->connection = $this->getConnection();
}
/**
* Get database connection
*/
protected function getConnection(): Connection
{
$config = include __DIR__ . '/../../Config/database.php';
$connectionConfig = $config['connections'][$config['default']];
return new Connection($connectionConfig);
}
/**
* Run the migration
*/
abstract public function up(): void;
/**
* Reverse the migration
*/
abstract public function down(): void;
/**
* Create table
*/
protected function createTable(string $table, callable $callback): void
{
$blueprint = new Blueprint($table);
$callback($blueprint);
$sql = $blueprint->toSql();
$this->connection->execute($sql);
}
/**
* Drop table
*/
protected function dropTable(string $table): void
{
$sql = "DROP TABLE IF EXISTS `{$table}`";
$this->connection->execute($sql);
}
/**
* Add column
*/
protected function addColumn(string $table, string $column, string $type): void
{
$sql = "ALTER TABLE `{$table}` ADD COLUMN `{$column}` {$type}";
$this->connection->execute($sql);
}
/**
* Drop column
*/
protected function dropColumn(string $table, string $column): void
{
$sql = "ALTER TABLE `{$table}` DROP COLUMN `{$column}`";
$this->connection->execute($sql);
}
/**
* Rename column
*/
protected function renameColumn(string $table, string $from, string $to): void
{
$sql = "ALTER TABLE `{$table}` RENAME COLUMN `{$from}` TO `{$to}`";
$this->connection->execute($sql);
}
/**
* Add index
*/
protected function addIndex(string $table, string $index, array $columns): void
{
$columnsStr = implode(', ', array_map(fn($col) => "`{$col}`", $columns));
$sql = "CREATE INDEX `{$index}` ON `{$table}` ({$columnsStr})";
$this->connection->execute($sql);
}
/**
* Drop index
*/
protected function dropIndex(string $table, string $index): void
{
$sql = "DROP INDEX `{$index}` ON `{$table}`";
$this->connection->execute($sql);
}
}