WP-Database-Helper/Migration.php
2025-02-12 15:55:28 +01:00

80 lines
2.2 KiB
PHP

<?php
namespace DatabaseHelper;
use DatabaseHelper\enums\Propagation;
use DatabaseHelper\enums\Type;
use InvalidArgumentException;
class Migration
{
protected Schema $schema;
protected array $columnsToAdd = [];
protected array $columnsToModify = [];
protected array $columnsToDrop = [];
protected array $primaryKey = null;
protected array $foreignKeysToAdd = [];
protected array $foreignKeysToDrop = [];
public function __construct(Schema $table) {
$this->schema = $table->copy();
}
public function add(string $name, Type $type, mixed $default = null, bool $isNullable = false, bool $isUnique = false): Migration {
if ($this->schema->existsColumn($name))
throw new InvalidArgumentException("Column '$name' already exists.");
$this->schema->columns[$name] = [
'name' => $name,
'type' => $type,
'default' => $default,
'isNullable' => $isNullable,
'isUnique' => $isUnique
];
$this->columnsToAdd[] = $name;
return $this;
}
public function modify(string $name, Type $type, mixed $default = null, bool $isNullable = false, bool $isUnique = false): Migration {
$this->schema->requireColumn($name);
$this->schema->columns[$name] = [
'name' => $name,
'type' => $type,
'default' => $default,
'isNullable' => $isNullable,
'isUnique' => $isUnique
];
$this->columnsToModify[] = $name;
return $this;
}
public function delete(string $name): Migration {
$this->schema->requireColumn($name);
unset($this->schema->columns[$name]);
$this->columnsToDrop[] = $name;
return $this;
}
public function reference(Schema $foreignTable, Propagation $onDelete = Propagation::CASCADE, Propagation $onUpdate = Propagation::CASCADE): Migration {
}
public function dereference(Schema $foreignTable): Migration {
}
public function toSql(): string {
}
public function drop(): null {
global $wpdb;
}
public function migrate(): Schema {
global $wpdb;
$sql = $this->toSql();
$wpdb->query($sql);
return $this->schema;
}
}