initial commit

This commit is contained in:
rsgrinko committed 2026-09-12 23:55:44 +03:00
commit 3f64f4a49a
221 files changed
+26665

No files matched your search

+301
View File
@@ -0,0 +1,301 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Schema;
/**
* Описание таблицы: колонки и индексы. Миграция получает его в замыкании и
* перечисляет, что нужно; SQL под нужный диалект собирается уже здесь.
*
* $this->create('users', function (Blueprint $table) {
* $table->id();
* $table->string('login', 191);
* $table->timestamps();
* $table->unique('idx_users_login', 'login');
* });
*/
final class Blueprint
{
private const INDEX = 'index';
private const UNIQUE = 'unique';
private const FULLTEXT = 'fulltext';
private string $table;
/** @var array<int, Column> */
private array $columns = [];
/** @var array<int, array{name: string, columns: string, type: string}> */
private array $indexes = [];
/** @var array<int, string> */
private array $dropColumns = [];
/** @var array<int, string> */
private array $dropIndexes = [];
public function __construct(string $table)
{
$this->table = $table;
}
public function table(): string
{
return $this->table;
}
// --- Колонки -------------------------------------------------------------
/**
* Первичный ключ с автоинкрементом.
*/
public function id(string $name = 'id'): Column
{
return $this->addColumn(new Column($name, 'id'));
}
public function string(string $name, int $length = 191): Column
{
return $this->addColumn(new Column($name, 'string', $length));
}
public function text(string $name): Column
{
return $this->addColumn(new Column($name, 'text'));
}
/**
* Длинный текст: тела писем и сырой HTML в MySQL не влезают в TEXT.
*/
public function longText(string $name): Column
{
return $this->addColumn(new Column($name, 'longText'));
}
public function integer(string $name): Column
{
return $this->addColumn(new Column($name, 'integer'));
}
public function boolean(string $name): Column
{
return $this->addColumn(new Column($name, 'boolean'));
}
public function decimal(string $name, int $total = 12, int $scale = 2): Column
{
return $this->addColumn(new Column($name, 'decimal', $total, $scale));
}
public function float(string $name): Column
{
return $this->addColumn(new Column($name, 'float'));
}
public function dateTime(string $name): Column
{
return $this->addColumn(new Column($name, 'dateTime'));
}
public function date(string $name): Column
{
return $this->addColumn(new Column($name, 'date'));
}
/**
* JSON храним текстом: обе базы умеют свой тип json, но искать по нему всё
* равно приходится по-разному, а модель разбирает поле сама (casts).
*/
public function json(string $name): Column
{
return $this->addColumn(new Column($name, 'text'));
}
/**
* Внешний ключ на чужую таблицу: колонка плюс индекс по ней.
* Настоящий FOREIGN KEY не ставим — в SQLite его потом не изменить,
* а целостность в приложении всё равно проверяется кодом.
*/
public function foreignId(string $name, bool $index = true): Column
{
$column = $this->integer($name)->default(0);
if ($index) {
$this->index('idx_' . $this->table . '_' . $name, $name);
}
return $column;
}
/**
* Отметки времени: их сама проставляет модель.
*/
public function timestamps(): void
{
$this->dateTime('created_at')->nullable();
$this->dateTime('updated_at')->nullable();
}
/**
* Колонка мягкого удаления.
*/
public function softDeletes(): void
{
$this->dateTime('deleted_at')->nullable();
}
/**
* Удалить колонку. SQLite умеет это с версии 3.35; если колонка входит
* в индекс, индекс снимается раньше — dropIndex() выполняется первым.
*/
public function dropColumn(string $name): void
{
$this->dropColumns[] = $name;
}
// --- Индексы -------------------------------------------------------------
/**
* @param string|array<int, string> $columns
*/
public function index(string $name, string|array $columns): void
{
$this->indexes[] = ['name' => $name, 'columns' => $this->columnList($columns), 'type' => self::INDEX];
}
/**
* @param string|array<int, string> $columns
*/
public function unique(string $name, string|array $columns): void
{
$this->indexes[] = ['name' => $name, 'columns' => $this->columnList($columns), 'type' => self::UNIQUE];
}
/**
* Полнотекстовый индекс. Есть только в MySQL — в SQLite поиск остаётся на LIKE.
*
* @param string|array<int, string> $columns
*/
public function fulltext(string $name, string|array $columns): void
{
$this->indexes[] = ['name' => $name, 'columns' => $this->columnList($columns), 'type' => self::FULLTEXT];
}
public function dropIndex(string $name): void
{
$this->dropIndexes[] = $name;
}
// --- Сборка SQL ----------------------------------------------------------
/**
* Шаги создания таблицы: сама таблица и её индексы.
*
* @return array<int, Operation>
*/
public function createOperations(Types $types): array
{
$definitions = [];
foreach ($this->columns as $column) {
$definitions[] = ' ' . $column->sql($types);
}
$steps = [Operation::raw(
'CREATE TABLE IF NOT EXISTS ' . $this->table . " (\n" . implode(",\n", $definitions) . "\n)" . $types->tableSuffix()
)];
foreach ($this->indexes as $index) {
$sql = $this->createIndexSql($types, $index);
if ($sql !== '') {
$steps[] = Operation::createIndex($sql, $this->table, $index['name']);
}
}
return $steps;
}
/**
* Шаги правки существующей таблицы. Порядок важен: индексы снимаются раньше,
* чем уходят их колонки, а новый индекс строится по уже добавленной.
*
* @return array<int, Operation>
*/
public function alterOperations(Types $types): array
{
$steps = [];
foreach ($this->dropIndexes as $name) {
$steps[] = Operation::dropIndex($this->dropIndexSql($types, $name), $this->table, $name);
}
foreach ($this->dropColumns as $name) {
$steps[] = Operation::dropColumn(
'ALTER TABLE ' . $this->table . ' DROP COLUMN ' . $name,
$this->table,
$name
);
}
foreach ($this->columns as $column) {
$steps[] = Operation::addColumn(
'ALTER TABLE ' . $this->table . ' ADD COLUMN ' . $column->sql($types),
$this->table,
$column->name()
);
}
foreach ($this->indexes as $index) {
$sql = $this->createIndexSql($types, $index);
if ($sql !== '') {
$steps[] = Operation::createIndex($sql, $this->table, $index['name']);
}
}
return $steps;
}
/**
* @param array{name: string, columns: string, type: string} $index
*/
private function createIndexSql(Types $types, array $index): string
{
if ($index['type'] === self::FULLTEXT) {
return $types->isSqlite()
? ''
: 'ALTER TABLE ' . $this->table . ' ADD FULLTEXT INDEX ' . $index['name'] . ' (' . $index['columns'] . ')';
}
$unique = $index['type'] === self::UNIQUE ? 'UNIQUE ' : '';
// SQLite умеет IF NOT EXISTS, MySQL — нет, но шаг и так проверяется перед выполнением
return $types->isSqlite()
? 'CREATE ' . $unique . 'INDEX IF NOT EXISTS ' . $index['name'] . ' ON ' . $this->table . ' (' . $index['columns'] . ')'
: 'CREATE ' . $unique . 'INDEX ' . $index['name'] . ' ON ' . $this->table . ' (' . $index['columns'] . ')';
}
private function dropIndexSql(Types $types, string $name): string
{
return $types->isSqlite()
? 'DROP INDEX IF EXISTS ' . $name
: 'DROP INDEX ' . $name . ' ON ' . $this->table;
}
private function addColumn(Column $column): Column
{
$this->columns[] = $column;
return $column;
}
/**
* @param string|array<int, string> $columns
*/
private function columnList(string|array $columns): string
{
return is_array($columns) ? implode(', ', $columns) : $columns;
}
}
+152
View File
@@ -0,0 +1,152 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Schema;
use Rsgrinko\Proton\Database\Connection;
/**
* Исполнитель схемы: принимает описание таблицы и выполняет получившийся SQL.
*
* В режиме «на словах» (pretend) ничего не выполняется, а запросы копятся в
* журнале — так работает `migrate --pretend` и так же миграции проверяются
* тестами, не трогая базу.
*/
final class Builder
{
private Connection $db;
private Types $types;
private bool $pretend;
/** @var array<int, string> */
private array $log = [];
/** @var array<int, string> Шаги, которые уже были выполнены раньше */
private array $skipped = [];
public function __construct(Connection $db, bool $pretend = false)
{
$this->db = $db;
$this->types = new Types($db);
$this->pretend = $pretend;
}
public function db(): Connection
{
return $this->db;
}
public function isSqlite(): bool
{
return $this->db->isSqlite();
}
/**
* Режим «на словах»: ничего не выполняется, запросы копятся в журнале.
*
* Знать об этом нужно шагам с данными: в этом режиме таблиц ещё нет,
* и запрос вроде «а нет ли уже такой записи» упадёт на пустой схеме.
*/
public function pretending(): bool
{
return $this->pretend;
}
/**
* Создать таблицу.
*
* @param callable(Blueprint): void $definition
*/
public function create(string $table, callable $definition): void
{
$blueprint = new Blueprint($table);
$definition($blueprint);
foreach ($blueprint->createOperations($this->types) as $operation) {
$this->apply($operation);
}
}
/**
* Изменить существующую таблицу.
*
* @param callable(Blueprint): void $definition
*/
public function table(string $table, callable $definition): void
{
$blueprint = new Blueprint($table);
$definition($blueprint);
foreach ($blueprint->alterOperations($this->types) as $operation) {
$this->apply($operation);
}
}
/**
* Удалить таблицу, если она есть: откат не должен падать на таблице,
* которую предыдущий откат уже снял.
*/
public function drop(string $table): void
{
$this->statement('DROP TABLE IF EXISTS ' . $table);
}
/**
* Произвольный запрос: перенос данных, стартовые записи, свой DDL.
*
* @param array<string, mixed> $params
*/
public function statement(string $sql, array $params = []): void
{
$this->log[] = $sql;
if (!$this->pretend) {
$this->db->execute($sql, $params);
}
}
/**
* Шаги, пропущенные как уже выполненные — их показывает команда миграции,
* чтобы «миграция прошла, а половины запросов не было» не выглядело загадкой.
*
* @return array<int, string>
*/
public function skipped(): array
{
return $this->skipped;
}
/**
* Все запросы, прошедшие через билдер.
*
* @return array<int, string>
*/
public function log(): array
{
return $this->log;
}
private function apply(Operation $operation): void
{
if ($this->pretend) {
$this->log[] = $operation->sql();
return;
}
if (!$operation->needed($this->db)) {
$this->skipped[] = $operation->sql();
return;
}
$this->log[] = $operation->sql();
$this->db->execute($operation->sql());
}
}
+133
View File
@@ -0,0 +1,133 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Schema;
use InvalidArgumentException;
/**
* Колонка таблицы. Тип задаётся отвлечённо (string, integer, dateTime), в SQL его
* переводит Types — миграция пишется одинаково для обеих баз.
*
* Методы возвращают сам объект, поэтому описание читается строкой:
* $table->string('login', 191)->nullable()->default('');
*/
final class Column
{
private string $name;
private string $type;
private int $length;
private int $scale = 2;
private bool $nullable = false;
private bool $primary = false;
private bool $hasDefault = false;
private mixed $default = null;
public function __construct(string $name, string $type, int $length = 0, int $scale = 2)
{
$this->name = $name;
$this->type = $type;
$this->length = $length;
$this->scale = $scale;
}
public function name(): string
{
return $this->name;
}
public function nullable(bool $nullable = true): self
{
$this->nullable = $nullable;
return $this;
}
/**
* Значение по умолчанию. Строки уходят в кавычках, числа — как есть.
*/
public function default(mixed $value): self
{
$this->hasDefault = true;
$this->default = $value;
return $this;
}
/**
* Первичный ключ на самой колонке — для таблиц с текстовым ключом
* (settings, migrations, counters), где автоинкремент не нужен.
*/
public function primary(bool $primary = true): self
{
$this->primary = $primary;
return $this;
}
/**
* Определение колонки для CREATE TABLE или ALTER TABLE ADD COLUMN.
*/
public function sql(Types $types): string
{
// Автоинкремент несёт первичный ключ и NOT NULL в самом типе
if ($this->type === 'id') {
return $this->name . ' ' . $types->id();
}
$sql = $this->name . ' ' . $this->typeSql($types);
$sql .= $this->nullable ? ' NULL' : ' NOT NULL';
if ($this->primary) {
$sql .= ' PRIMARY KEY';
}
if ($this->hasDefault) {
$sql .= ' DEFAULT ' . $this->defaultSql();
}
return $sql;
}
private function typeSql(Types $types): string
{
return match ($this->type) {
'string' => $types->string($this->length),
'text' => $types->text(),
'longText' => $types->longText(),
'integer' => $types->integer(),
'boolean' => $types->boolean(),
'decimal' => $types->decimal($this->length, $this->scale),
'float' => $types->float(),
'dateTime' => $types->dateTime(),
'date' => $types->date(),
default => throw new InvalidArgumentException('Неизвестный тип колонки: ' . $this->type),
};
}
private function defaultSql(): string
{
if (is_bool($this->default)) {
return $this->default ? '1' : '0';
}
if (is_int($this->default) || is_float($this->default)) {
return (string) $this->default;
}
if ($this->default === null) {
return 'NULL';
}
return "'" . str_replace("'", "''", (string) $this->default) . "'";
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Schema;
use Rsgrinko\Proton\Database\Connection;
/**
* Один шаг миграции: запрос и условие, при котором его вообще нужно выполнять.
*
* Условие нужно ради повторного наката. MySQL коммитит каждый ALTER сам по себе,
* поэтому упавшая на середине миграция оставляет половину изменений, а записи о
* ней не появляется. Следующий накат пойдёт с её начала и без проверки упрётся
* в «Duplicate column name» — базу пришлось бы чинить руками. Уже сделанный шаг
* просто пропускается.
*/
final class Operation
{
private const TABLE = 'table';
private const COLUMN = 'column';
private const INDEX = 'index';
private string $sql;
private ?string $object;
private string $table;
private string $name;
/** Выполнять, когда наличие объекта равно этому: false — ещё нет, true — уже есть */
private bool $expect;
private function __construct(string $sql, ?string $object = null, string $table = '', string $name = '', bool $expect = false)
{
$this->sql = $sql;
$this->object = $object;
$this->table = $table;
$this->name = $name;
$this->expect = $expect;
}
/**
* Запрос, который выполняется всегда: перенос данных, CREATE TABLE IF NOT EXISTS,
* DROP TABLE IF EXISTS — всё, что идемпотентно само по себе.
*/
public static function raw(string $sql): self
{
return new self($sql);
}
public static function addColumn(string $sql, string $table, string $column): self
{
return new self($sql, self::COLUMN, $table, $column, false);
}
public static function dropColumn(string $sql, string $table, string $column): self
{
return new self($sql, self::COLUMN, $table, $column, true);
}
public static function createIndex(string $sql, string $table, string $index): self
{
return new self($sql, self::INDEX, $table, $index, false);
}
public static function dropIndex(string $sql, string $table, string $index): self
{
return new self($sql, self::INDEX, $table, $index, true);
}
public static function createTable(string $sql, string $table): self
{
return new self($sql, self::TABLE, $table, $table, false);
}
public function sql(): string
{
return $this->sql;
}
/**
* Нужно ли выполнять шаг.
*/
public function needed(Connection $db): bool
{
if ($this->object === null) {
return true;
}
$exists = match ($this->object) {
self::TABLE => $db->hasTable($this->table),
self::COLUMN => $db->hasColumn($this->table, $this->name),
self::INDEX => $db->hasIndex($this->table, $this->name),
};
return $exists === $this->expect;
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Schema;
use Rsgrinko\Proton\Database\Connection;
/**
* Типы колонок под конкретный драйвер. Всё, что различается между sqlite и mysql,
* собрано здесь: миграции про диалект не знают вовсе.
*/
final class Types
{
private Connection $db;
public function __construct(Connection $db)
{
$this->db = $db;
}
public function isSqlite(): bool
{
return $this->db->isSqlite();
}
public function id(): string
{
return $this->db->isSqlite()
? 'INTEGER PRIMARY KEY AUTOINCREMENT'
: 'BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY';
}
public function string(int $length): string
{
return $this->db->isSqlite() ? 'TEXT' : 'VARCHAR(' . $length . ')';
}
public function text(): string
{
return 'TEXT';
}
public function longText(): string
{
return $this->db->isSqlite() ? 'TEXT' : 'LONGTEXT';
}
public function integer(): string
{
return $this->db->isSqlite() ? 'INTEGER' : 'BIGINT';
}
public function boolean(): string
{
return $this->db->isSqlite() ? 'INTEGER' : 'TINYINT(1)';
}
public function decimal(int $total, int $scale): string
{
return 'DECIMAL(' . $total . ',' . $scale . ')';
}
public function float(): string
{
return $this->db->isSqlite() ? 'REAL' : 'DOUBLE';
}
public function dateTime(): string
{
return $this->db->isSqlite() ? 'TEXT' : 'DATETIME';
}
public function date(): string
{
return $this->db->isSqlite() ? 'TEXT' : 'DATE';
}
/**
* Хвост CREATE TABLE: движок и кодировка для MySQL, пусто для SQLite.
*/
public function tableSuffix(): string
{
return $this->db->isSqlite() ? '' : ' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
}
}