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

+555
View File
@@ -0,0 +1,555 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database;
use PDO;
use PDOException;
use PDOStatement;
use Rsgrinko\Proton\Database\Query\Builder;
use Rsgrinko\Proton\Support\Config;
use Throwable;
/**
* Подключение к базе: тонкая обёртка над PDO. Знает два драйвера — sqlite и mysql —
* и прячет различия между ними (автоинкремент, upsert, блокировки строк).
*
* Долгоживущий процесс (воркер) держит соединение часами, поэтому обрыв связи
* ловится и соединение поднимается заново — см. run().
*/
final class Connection
{
public const SQLITE = 'sqlite';
public const MYSQL = 'mysql';
private static ?self $instance = null;
private PDO $pdo;
private string $driver;
/**
* Настройки, с которыми открыли это подключение.
*
* Держим их у себя, а не подсматриваем в конфиге: подключений в процессе бывает
* несколько (тесты работают на своей базе), и «взять настройки из конфига»
* означало бы переподключиться не туда, откуда выпали.
*
* @var array<string, mixed>
*/
private array $config;
/**
* @param array<string, mixed>|null $config блок 'db' конфигурации
*/
public function __construct(?array $config = null)
{
$config = $config ?? (array) Config::get('db', []);
$driver = (string) ($config['driver'] ?? self::SQLITE);
if (!in_array($driver, [self::SQLITE, self::MYSQL], true)) {
throw new DatabaseException('Неизвестный драйвер базы данных: ' . $driver);
}
$this->config = $config;
$this->driver = $driver;
$this->pdo = $driver === self::SQLITE
? $this->connectSqlite((array) ($config['sqlite'] ?? []))
: $this->connectMysql((array) ($config['mysql'] ?? []));
}
/**
* Общее подключение на весь процесс.
*/
public static function instance(): self
{
return self::$instance ??= new self();
}
/**
* Подменить подключение — нужно тестам и командам, работающим со второй базой.
*/
public static function setInstance(?self $connection): void
{
self::$instance = $connection;
}
public function pdo(): PDO
{
return $this->pdo;
}
public function driver(): string
{
return $this->driver;
}
public function isSqlite(): bool
{
return $this->driver === self::SQLITE;
}
/**
* Настройки MySQL — с ними работает mysqldump в резервных копиях.
*
* @return array<string, mixed>
*/
public function mysqlConfig(): array
{
return (array) ($this->config['mysql'] ?? []);
}
/**
* Путь к файлу базы SQLite или пустая строка.
*/
public function sqlitePath(): string
{
return (string) ($this->config['sqlite']['path'] ?? '');
}
/**
* Построитель запросов по таблице: $db->table('users')->where(...)->get().
*/
public function table(string $table): Builder
{
return new Builder($this, $table);
}
/**
* Все строки запроса.
*
* @param array<string|int, mixed> $params
*
* @return array<int, array<string, mixed>>
*/
public function select(string $sql, array $params = []): array
{
return $this->run($sql, $params)->fetchAll();
}
/**
* Первая строка или null.
*
* @param array<string|int, mixed> $params
*
* @return array<string, mixed>|null
*/
public function selectOne(string $sql, array $params = []): ?array
{
$row = $this->run($sql, $params)->fetch();
return $row === false ? null : $row;
}
/**
* Одно значение из первой строки.
*
* @param array<string|int, mixed> $params
*/
public function value(string $sql, array $params = []): mixed
{
$row = $this->selectOne($sql, $params);
if ($row === null) {
return null;
}
return reset($row);
}
/**
* Запрос без выборки. Возвращает число затронутых строк.
*
* @param array<string|int, mixed> $params
*/
public function execute(string $sql, array $params = []): int
{
return $this->run($sql, $params)->rowCount();
}
/**
* Вставка строки, возвращает id новой записи.
*
* @param array<string, mixed> $data
*/
public function insert(string $table, array $data): int
{
$columns = array_keys($data);
$placeholders = array_map(static fn (string $column): string => ':' . $column, $columns);
$this->run(
sprintf('INSERT INTO %s (%s) VALUES (%s)', $table, implode(', ', $columns), implode(', ', $placeholders)),
$data
);
return (int) $this->pdo->lastInsertId();
}
/**
* Обновление по условию вида ['id' => 5].
*
* @param array<string, mixed> $data
* @param array<string, mixed> $where
*/
public function update(string $table, array $data, array $where): int
{
$set = [];
$parameters = [];
foreach ($data as $column => $value) {
$set[] = $column . ' = :set_' . $column;
$parameters['set_' . $column] = $value;
}
$conditions = [];
foreach ($where as $column => $value) {
$conditions[] = $column . ' = :where_' . $column;
$parameters['where_' . $column] = $value;
}
return $this->execute(
sprintf('UPDATE %s SET %s WHERE %s', $table, implode(', ', $set), implode(' AND ', $conditions)),
$parameters
);
}
/**
* Удаление по условию.
*
* @param array<string, mixed> $where
*/
public function delete(string $table, array $where): int
{
$conditions = [];
foreach (array_keys($where) as $column) {
$conditions[] = $column . ' = :' . $column;
}
return $this->execute(
sprintf('DELETE FROM %s WHERE %s', $table, implode(' AND ', $conditions)),
$where
);
}
/**
* Выполняет замыкание в транзакции: ошибка — всё откатывается.
* Вложенный вызов работает внутри уже открытой транзакции.
*
* @template T
*
* @param callable(self): T $callback
*
* @return T
*/
public function transaction(callable $callback): mixed
{
if ($this->pdo->inTransaction()) {
return $callback($this);
}
$this->pdo->beginTransaction();
try {
$result = $callback($this);
// Коммитим, только если транзакция ещё жива: в MySQL любой ALTER
// коммитит её сам, и commit() бросил бы «There is no active transaction»
if ($this->pdo->inTransaction()) {
$this->pdo->commit();
}
return $result;
} catch (Throwable $e) {
if ($this->pdo->inTransaction()) {
$this->pdo->rollBack();
}
throw $e;
}
}
/**
* Страница результатов: считает общее число строк и отдаёт нужный кусок.
* Запрос передаётся без LIMIT.
*
* @param array<string|int, mixed> $params
*
* @return array{items: array<int, array<string, mixed>>, total: int, page: int, pages: int, per_page: int}
*/
public function page(string $sql, array $params = [], int $page = 1, int $perPage = 30): array
{
$perPage = max(1, min(200, $perPage));
$total = (int) $this->value($this->countSql($sql), $params);
$pages = max(1, (int) ceil($total / $perPage));
$page = max(1, min($page, $pages));
return [
'items' => $this->select($sql . ' LIMIT ' . $perPage . ' OFFSET ' . (($page - 1) * $perPage), $params),
'total' => $total,
'page' => $page,
'pages' => $pages,
'per_page' => $perPage,
];
}
/**
* Сколько строк в таблице. Нет таблицы — ноль: страница состояния это переживёт.
*/
public function count(string $table): int
{
return $this->hasTable($table) ? (int) $this->value('SELECT COUNT(*) FROM ' . $table) : 0;
}
public function hasTable(string $table): bool
{
if ($this->isSqlite()) {
return $this->selectOne(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = :name",
['name' => $table]
) !== null;
}
return $this->selectOne(
'SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :name',
['name' => $table]
) !== null;
}
/**
* Есть ли колонка. Нужно миграциям и коду, который может приехать раньше них.
*/
public function hasColumn(string $table, string $column): bool
{
if (!$this->hasTable($table)) {
return false;
}
if ($this->isSqlite()) {
// Имя таблицы в PRAGMA параметром не подставить — сверяем его сами
if (preg_match('/^[A-Za-z0-9_]+$/', $table) !== 1) {
throw new DatabaseException('Недопустимое имя таблицы: ' . $table);
}
foreach ($this->select('PRAGMA table_info(' . $table . ')') as $row) {
if ((string) $row['name'] === $column) {
return true;
}
}
return false;
}
return $this->selectOne(
'SELECT column_name FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = :table AND column_name = :column',
['table' => $table, 'column' => $column]
) !== null;
}
public function hasIndex(string $table, string $index): bool
{
if (!$this->hasTable($table)) {
return false;
}
if ($this->isSqlite()) {
return $this->selectOne(
"SELECT name FROM sqlite_master WHERE type = 'index' AND name = :index AND tbl_name = :table",
['index' => $index, 'table' => $table]
) !== null;
}
return $this->selectOne(
'SELECT index_name FROM information_schema.STATISTICS
WHERE table_schema = DATABASE() AND table_name = :table AND index_name = :index
LIMIT 1',
['table' => $table, 'index' => $index]
) !== null;
}
/**
* Имена всех таблиц базы.
*
* @return array<int, string>
*/
public function tables(): array
{
$rows = $this->isSqlite()
? $this->select("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
: $this->select('SELECT table_name AS name FROM information_schema.tables WHERE table_schema = DATABASE() ORDER BY table_name');
return array_map(static fn (array $row): string => (string) $row['name'], $rows);
}
/**
* Текущее время в том виде, в каком мы храним даты.
*/
public static function now(): string
{
return date('Y-m-d H:i:s');
}
/**
* Время со сдвигом в секундах.
*/
public static function at(int $secondsFromNow): string
{
return date('Y-m-d H:i:s', time() + $secondsFromNow);
}
private function connectSqlite(array $config): PDO
{
$path = (string) ($config['path'] ?? '');
if ($path === '') {
$path = APP_ROOT . '/var/app.sqlite';
}
if ($path !== ':memory:') {
$dir = dirname($path);
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
}
try {
$pdo = new PDO('sqlite:' . $path, null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
} catch (PDOException $e) {
throw new DatabaseException('Не удалось открыть базу SQLite: ' . $e->getMessage(), [], 0, $e);
}
// WAL даёт нормальную параллельную работу воркера и веб-части
$pdo->exec('PRAGMA journal_mode = WAL');
$pdo->exec('PRAGMA synchronous = NORMAL');
$pdo->exec('PRAGMA foreign_keys = ON');
$pdo->exec('PRAGMA busy_timeout = 10000');
return $pdo;
}
private function connectMysql(array $config): PDO
{
$dsn = sprintf(
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
(string) ($config['host'] ?? '127.0.0.1'),
(int) ($config['port'] ?? 3306),
(string) ($config['database'] ?? ''),
(string) ($config['charset'] ?? 'utf8mb4')
);
try {
return new PDO($dsn, (string) ($config['username'] ?? ''), (string) ($config['password'] ?? ''), [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
// Настоящие подготовленные выражения: параметр в запросе должен
// встречаться один раз, зато данные точно не склеятся с SQL
PDO::ATTR_EMULATE_PREPARES => false,
]);
} catch (PDOException $e) {
throw new DatabaseException('Не удалось подключиться к MySQL: ' . $e->getMessage(), [], 0, $e);
}
}
/**
* Запрос, считающий строки для пагинации.
*
* Простую выборку считаем по тем же условиям, без обёртки в подзапрос: на
* больших таблицах подзапрос материализуется и стоит в разы дороже. Всё
* сложное (группировки, DISTINCT, объединения) — по-прежнему подзапросом.
*/
private function countSql(string $sql): string
{
$normalized = trim((string) preg_replace('#\s+#', ' ', $sql));
$simple = preg_match('#^SELECT (?!DISTINCT\b)(?:.+?) FROM (.+)$#i', $normalized, $matches) === 1
&& preg_match('#\b(GROUP BY|HAVING|UNION|LIMIT)\b#i', $normalized) !== 1;
if (!$simple) {
return 'SELECT COUNT(*) FROM (' . $sql . ') AS page_source';
}
return 'SELECT COUNT(*) FROM ' . preg_replace('#\s+ORDER BY\s+.+$#i', '', $matches[1]);
}
/**
* @param array<string|int, mixed> $params
*/
private function run(string $sql, array $params): PDOStatement
{
try {
return $this->prepareAndRun($sql, $params);
} catch (PDOException $e) {
// Воркер живёт часами, и MySQL успевает закрыть соединение по
// wait_timeout. Одна попытка переподключиться — и запрос повторяется
if ($this->connectionLost($e)) {
$this->reconnect();
try {
return $this->prepareAndRun($sql, $params);
} catch (PDOException $retry) {
$e = $retry;
}
}
throw new DatabaseException('Ошибка запроса к базе: ' . $e->getMessage(), ['sql' => $sql], 0, $e);
}
}
/**
* @param array<string|int, mixed> $params
*/
private function prepareAndRun(string $sql, array $params): PDOStatement
{
$statement = $this->pdo->prepare($sql);
foreach ($params as $key => $value) {
$name = is_int($key) ? $key + 1 : ':' . ltrim((string) $key, ':');
$type = match (true) {
is_int($value) => PDO::PARAM_INT,
is_bool($value) => PDO::PARAM_INT,
$value === null => PDO::PARAM_NULL,
default => PDO::PARAM_STR,
};
$statement->bindValue($name, is_bool($value) ? (int) $value : $value, $type);
}
$statement->execute();
return $statement;
}
/**
* Оборвалась ли связь. Внутри транзакции повторять нечего — она уже потеряна.
*/
private function connectionLost(PDOException $e): bool
{
if ($this->driver !== self::MYSQL || $this->pdo->inTransaction()) {
return false;
}
$code = (int) ($e->errorInfo[1] ?? 0);
$message = $e->getMessage();
return in_array($code, [2006, 2013, 2055], true)
|| str_contains($message, 'server has gone away')
|| str_contains($message, 'Lost connection');
}
private function reconnect(): void
{
try {
$this->pdo = $this->connectMysql($this->mysqlConfig());
} catch (DatabaseException $e) {
throw new DatabaseException('Соединение с базой потеряно и не восстановилось: ' . $e->getMessage(), [], 0, $e);
}
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database;
use Rsgrinko\Proton\Support\ProtonException;
/**
* Ошибка работы с базой: не подключились, не выполнили запрос, не накатили миграцию.
*/
final class DatabaseException extends ProtonException
{
}
+117
View File
@@ -0,0 +1,117 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database;
use Rsgrinko\Proton\Support\Config;
/**
* Блокировка на время долгой операции: накат миграций, разовая задача воркера.
*
* Без неё дважды нажатая кнопка или деплой одновременно с ручным `migrate`
* разойдутся между проверкой «применена ли миграция» и записью о ней, и одна
* и та же миграция выполнится дважды.
*
* В MySQL берём GET_LOCK — он общий для всех процессов этой базы. В SQLite базой
* пользуются с одной машины, поэтому хватает flock на файле.
*/
final class Lock
{
private Connection $db;
private string $name;
/** @var resource|null Файл блокировки для SQLite */
private $handle = null;
private bool $held = false;
public function __construct(?Connection $db = null, string $name = 'app')
{
$this->db = $db ?? Connection::instance();
$this->name = preg_replace('/[^A-Za-z0-9_.-]/', '_', $name) ?? 'app';
}
/**
* Пытается взять блокировку, ожидая не дольше указанного времени.
*/
public function acquire(int $seconds = 30): bool
{
if ($this->held) {
return true;
}
$this->held = $this->db->isSqlite() ? $this->acquireFile($seconds) : $this->acquireMysql($seconds);
return $this->held;
}
public function release(): void
{
if (!$this->held) {
return;
}
if ($this->db->isSqlite()) {
if (is_resource($this->handle)) {
flock($this->handle, LOCK_UN);
fclose($this->handle);
}
$this->handle = null;
} else {
$this->db->value('SELECT RELEASE_LOCK(:name)', ['name' => $this->name]);
}
$this->held = false;
}
public function __destruct()
{
$this->release();
}
/**
* GET_LOCK живёт в соединении: оборвётся связь — пропадёт и блокировка.
* Для миграций это то, что нужно: упавший процесс не оставит базу запертой.
*/
private function acquireMysql(int $seconds): bool
{
return (int) $this->db->value(
'SELECT GET_LOCK(:name, :timeout)',
['name' => $this->name, 'timeout' => $seconds]
) === 1;
}
private function acquireFile(int $seconds): bool
{
$dir = (string) Config::get('paths.tmp', APP_ROOT . '/var/tmp') . '/lock';
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
$handle = @fopen($dir . '/' . $this->name . '.lock', 'c');
if ($handle === false) {
throw new DatabaseException('Не удалось открыть файл блокировки: ' . $this->name);
}
$deadline = microtime(true) + $seconds;
do {
if (flock($handle, LOCK_EX | LOCK_NB)) {
$this->handle = $handle;
return true;
}
usleep(200000);
} while (microtime(true) < $deadline);
fclose($handle);
return false;
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database;
use Rsgrinko\Proton\Database\Schema\Blueprint;
use Rsgrinko\Proton\Database\Schema\Builder;
/**
* Одна миграция — один файл в каталоге migrations/ с именем вида
* `20260912093000_create_users.php` и классом `CreateUsers` в App\Migrations.
*
* up() накатывает изменение, down() отменяет его. Имя файла — это и есть имя
* миграции в таблице migrations, поэтому переименовывать файл нельзя: миграция
* станет новой и применится второй раз.
*/
abstract class Migration
{
protected Builder $schema;
public function __construct(Builder $schema)
{
$this->schema = $schema;
}
/**
* Что миграция делает.
*/
abstract public function up(): void;
/**
* Как это отменить. Откат обязан быть честным: это проверяется тестом,
* который накатывает всё, откатывает и накатывает снова.
*/
abstract public function down(): void;
/**
* @param callable(Blueprint): void $definition
*/
protected function create(string $table, callable $definition): void
{
$this->schema->create($table, $definition);
}
/**
* @param callable(Blueprint): void $definition
*/
protected function table(string $table, callable $definition): void
{
$this->schema->table($table, $definition);
}
protected function drop(string $table): void
{
$this->schema->drop($table);
}
/**
* Свой запрос — только с параметрами, а не склейкой строк.
*
* @param array<string, mixed> $params
*/
protected function statement(string $sql, array $params = []): void
{
$this->schema->statement($sql, $params);
}
protected function isSqlite(): bool
{
return $this->schema->isSqlite();
}
/**
* Идёт ли `migrate --pretend`. Шагу с данными это важно: в этом режиме
* таблиц в базе ещё нет, и проверка «нет ли уже такой записи» упадёт.
*/
protected function pretending(): bool
{
return $this->schema->pretending();
}
protected function db(): Connection
{
return $this->schema->db();
}
/**
* Текущее время в том виде, в каком мы храним даты.
*/
protected function now(): string
{
return Connection::now();
}
}
+336
View File
@@ -0,0 +1,336 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database;
use Rsgrinko\Proton\Database\Schema\Blueprint;
use Rsgrinko\Proton\Database\Schema\Builder;
use Throwable;
/**
* Миграции. Каждая — свой файл в каталоге migrations/:
* `20260912093000_create_users.php` с классом `CreateUsers` в App\Migrations.
* Файлы подхватываются сами, реестр править не нужно, порядок — по имени файла,
* то есть по времени создания.
*
* Применённые запоминаются в таблице migrations вместе с номером пачки: накат
* кладёт всё сделанное за раз в одну пачку, откат снимает последнюю пачку целиком.
*/
final class Migrator
{
/** Имя общей блокировки и сколько ждать её освобождения */
private const LOCK_NAME = 'migrations';
private const LOCK_TIMEOUT = 60;
private Connection $db;
private string $path;
private ?Builder $builder = null;
/** @var array<string, Migration>|null */
private ?array $migrations = null;
public function __construct(?Connection $db = null, ?string $path = null)
{
$this->db = $db ?? Connection::instance();
$this->path = $path ?? APP_ROOT . '/migrations';
}
/**
* Применяет все новые миграции, возвращает список применённых имён.
*
* @return array<int, string>
*/
public function run(): array
{
return $this->locked(function (): array {
$this->prepare();
$pending = $this->pending();
if ($pending === []) {
return [];
}
$batch = $this->nextBatch();
$applied = [];
foreach ($pending as $name) {
$migration = $this->migrations()[$name];
$this->guard($name, function () use ($migration, $name, $batch): void {
// В SQLite DDL транзакционен, и упавшая миграция откатится целиком.
// MySQL на каждом ALTER делает неявный коммит — там транзакция не
// спасёт, зато записи о наполовину применённой миграции не появится,
// и следующий накат повторит её шаги, пропустив уже сделанные
$this->db->transaction(function () use ($migration, $name, $batch): void {
$migration->up();
$this->db->insert('migrations', [
'name' => $name,
'batch' => $batch,
'applied_at' => Connection::now(),
]);
});
});
$applied[] = $name;
}
return $applied;
});
}
/**
* Откатывает последние пачки, возвращает откаченные имена в порядке отката.
*
* @return array<int, string>
*/
public function rollback(int $batches = 1): array
{
if (!$this->db->hasTable('migrations')) {
return [];
}
return $this->locked(function () use ($batches): array {
$this->prepare();
$names = $this->lastBatches(max(1, $batches));
if ($names === []) {
return [];
}
$known = $this->migrations();
$rolledBack = [];
foreach ($names as $name) {
if (!isset($known[$name])) {
throw new DatabaseException(
'Миграция ' . $name . ' есть в базе, но не в коде — откатить её нечем.'
);
}
$migration = $known[$name];
$this->guard($name, function () use ($migration, $name): void {
$this->db->transaction(function () use ($migration, $name): void {
$migration->down();
$this->db->execute('DELETE FROM migrations WHERE name = :name', ['name' => $name]);
});
});
$rolledBack[] = $name;
}
return $rolledBack;
});
}
/**
* Что сделают новые миграции, если их применить: имя -> список запросов.
* Ничего не выполняет — это `migrate --pretend`.
*
* @return array<string, array<int, string>>
*/
public function pretend(): array
{
$plan = [];
foreach ($this->pending() as $name) {
$builder = new Builder($this->db, true);
$class = get_class($this->migrations()[$name]);
/** @var Migration $migration */
$migration = new $class($builder);
$migration->up();
$plan[$name] = $builder->log();
}
return $plan;
}
/**
* Ещё не применённые миграции.
*
* @return array<int, string>
*/
public function pending(): array
{
return array_values(array_diff(array_keys($this->migrations()), $this->applied()));
}
/**
* Применённые миграции в порядке применения.
*
* @return array<int, string>
*/
public function applied(): array
{
if (!$this->db->hasTable('migrations')) {
return [];
}
return array_map(
static fn (array $row): string => (string) $row['name'],
$this->db->select('SELECT name FROM migrations ORDER BY name')
);
}
/**
* Шаги последнего наката, пропущенные как уже выполненные: так выглядит докат
* миграции, упавшей на середине.
*
* @return array<int, string>
*/
public function skipped(): array
{
return $this->builder === null ? [] : $this->builder->skipped();
}
/**
* Миграции, которые есть в базе, но которых нет в коде: обычно это откат
* релиза. Молча игнорировать такое нельзя.
*
* @return array<int, string>
*/
public function unknown(): array
{
return array_values(array_diff($this->applied(), array_keys($this->migrations())));
}
/**
* Все миграции: имя файла без расширения -> объект.
*
* @return array<string, Migration>
*/
public function migrations(): array
{
if ($this->migrations !== null) {
return $this->migrations;
}
$builder = $this->builder = new Builder($this->db);
$found = [];
foreach ((array) glob($this->path . '/*.php') as $file) {
$file = (string) $file;
$name = basename($file, '.php');
if (preg_match('/^(\d{14})_([a-z0-9_]+)$/', $name, $matches) !== 1) {
throw new DatabaseException(
'Файл миграции ' . $name . ' назван не по правилу 20260912093000_имя_миграции.php'
);
}
$class = $this->className($matches[2]);
require_once $file;
if (!class_exists($class) || !is_subclass_of($class, Migration::class)) {
throw new DatabaseException(
'В файле миграции ' . $name . ' нет класса ' . $class . ', унаследованного от Migration.'
);
}
$found[$name] = new $class($builder);
}
ksort($found);
return $this->migrations = $found;
}
/**
* Класс миграции по хвосту имени файла: create_users -> CreateUsers.
*/
private function className(string $slug): string
{
return 'App\\Migrations\\' . str_replace(' ', '', ucwords(str_replace('_', ' ', $slug)));
}
/**
* Выполняет работу под общей блокировкой: два наката разом — это дважды
* применённая миграция, а на бою обычно ещё и упавший деплой.
*
* @template T
*
* @param callable(): T $work
*
* @return T
*/
private function locked(callable $work): mixed
{
$lock = new Lock($this->db, self::LOCK_NAME);
if (!$lock->acquire(self::LOCK_TIMEOUT)) {
throw new DatabaseException('Миграции уже накатывает другой процесс. Дождитесь его и повторите.');
}
try {
return $work();
} finally {
$lock->release();
}
}
/**
* Выполняет шаг, дополняя любую ошибку именем миграции: без этого на бою
* приходится гадать, на чём именно встал накат.
*/
private function guard(string $name, callable $step): void
{
try {
$step();
} catch (Throwable $e) {
throw new DatabaseException('Миграция ' . $name . ' не выполнена: ' . $e->getMessage(), [], 0, $e);
}
}
/**
* Имена миграций последних пачек в порядке отката.
*
* @return array<int, string>
*/
private function lastBatches(int $batches): array
{
$rows = $this->db->select('SELECT DISTINCT batch FROM migrations ORDER BY batch DESC LIMIT ' . $batches);
if ($rows === []) {
return [];
}
$lowest = (int) $rows[count($rows) - 1]['batch'];
return array_map(
static fn (array $row): string => (string) $row['name'],
$this->db->select('SELECT name FROM migrations WHERE batch >= :batch ORDER BY name DESC', ['batch' => $lowest])
);
}
private function nextBatch(): int
{
return (int) $this->db->value('SELECT MAX(batch) FROM migrations') + 1;
}
/**
* Служебная таблица: создать, если её нет.
*/
private function prepare(): void
{
if ($this->db->hasTable('migrations')) {
return;
}
(new Builder($this->db))->create('migrations', function (Blueprint $table): void {
$table->string('name')->primary();
$table->integer('batch')->default(0);
$table->dateTime('applied_at');
});
}
}
+732
View File
@@ -0,0 +1,732 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Model;
use JsonSerializable;
use Rsgrinko\Proton\Database\Connection;
use Rsgrinko\Proton\Database\Model\Relations\BelongsTo;
use Rsgrinko\Proton\Database\Model\Relations\BelongsToMany;
use Rsgrinko\Proton\Database\Model\Relations\HasMany;
use Rsgrinko\Proton\Database\Model\Relations\HasOne;
use Rsgrinko\Proton\Database\Model\Relations\Relation;
use Rsgrinko\Proton\Support\ProtonException;
use Rsgrinko\Proton\Support\Str;
/**
* Модель: строка таблицы как объект (Active Record).
*
* class User extends Model
* {
* protected static string $table = 'users';
* protected array $fillable = ['login', 'email', 'name'];
* protected array $casts = ['active' => 'bool', 'settings' => 'json'];
*
* public function posts(): HasMany
* {
* return $this->hasMany(Post::class);
* }
* }
*
* $user = User::where('login', 'ivan')->first();
* $user->name = 'Иван';
* $user->save();
*
* Имя таблицы можно не задавать — оно берётся из имени класса (User -> users).
* Отметки created_at/updated_at проставляются сами, если в таблице есть такие
* колонки; мягкое удаление включается свойством $softDelete.
*
* Массовое присвоение работает по «белому списку» $fillable: без него форма,
* в которую дописали лишнее поле, меняла бы что угодно, вплоть до role_id.
*/
abstract class Model implements JsonSerializable
{
public const CREATED_AT = 'created_at';
public const UPDATED_AT = 'updated_at';
public const DELETED_AT = 'deleted_at';
/** Имя таблицы; пусто — считается по имени класса */
protected static string $table = '';
/** Первичный ключ */
protected static string $primaryKey = 'id';
/** Проставлять ли created_at и updated_at */
protected bool $timestamps = true;
/** Мягкое удаление: запись остаётся, но помечается deleted_at */
protected bool $softDelete = false;
/** @var array<int, string> Поля, которые можно заполнять массово */
protected array $fillable = [];
/** @var array<int, string> Поля, которые нельзя показывать наружу (toArray, JSON) */
protected array $hidden = [];
/** @var array<string, string> Приведение типов: int, float, bool, json, datetime */
protected array $casts = [];
/** @var array<string, mixed> Значения колонок */
protected array $attributes = [];
/** @var array<string, mixed> Значения, прочитанные из базы, — по ним видно, что изменилось */
protected array $original = [];
/** @var array<string, mixed> Загруженные связи */
protected array $loaded = [];
/** Запись уже есть в базе */
protected bool $exists = false;
/**
* @param array<string, mixed> $attributes
*/
public function __construct(array $attributes = [])
{
$this->fill($attributes);
}
// --- Настройки модели ----------------------------------------------------
/**
* Имя таблицы: задано свойством или посчитано по имени класса.
*/
public function table(): string
{
if (static::$table !== '') {
return static::$table;
}
$short = substr(strrchr(static::class, '\\') ?: static::class, 1);
return Str::plural(Str::snake($short));
}
public function keyName(): string
{
return static::$primaryKey;
}
/**
* Значение первичного ключа.
*/
public function key(): mixed
{
return $this->attributes[static::$primaryKey] ?? null;
}
public function id(): int
{
return (int) $this->key();
}
public function connection(): Connection
{
return Connection::instance();
}
public function hasTimestamps(): bool
{
return $this->timestamps;
}
public function softDeletes(): bool
{
return $this->softDelete;
}
public function existsInDatabase(): bool
{
return $this->exists;
}
// --- Выборка -------------------------------------------------------------
/**
* Построитель запросов этой модели.
*/
public static function query(): Query
{
return new Query(static::class);
}
/**
* @return array<int, static>
*/
public static function all(): array
{
/** @var array<int, static> $models */
$models = static::query()->get();
return $models;
}
public static function find(int|string|null $id): ?static
{
if ($id === null || $id === '' || $id === 0) {
return null;
}
/** @var static|null $model */
$model = static::query()->where(static::$primaryKey, $id)->first();
return $model;
}
/**
* Запись обязана быть — иначе исключение, которое ядро превратит в 404.
*/
public static function findOrFail(int|string|null $id): static
{
$model = static::find($id);
if ($model === null) {
throw new RecordNotFound('Запись не найдена: ' . static::class . ' #' . (string) $id);
}
return $model;
}
/**
* Условие прямо от класса: User::where('active', 1)->get().
*/
public static function where(string $column, mixed $operator = null, mixed $value = null): Query
{
if (func_num_args() === 2) {
return static::query()->where($column, $operator);
}
return static::query()->where($column, $operator, $value);
}
/**
* Первая запись по условию — короткая запись для поиска по одному полю.
*/
public static function findBy(string $column, mixed $value): ?static
{
/** @var static|null $model */
$model = static::query()->where($column, $value)->first();
return $model;
}
/**
* Создать и сразу сохранить.
*
* @param array<string, mixed> $attributes
*/
public static function create(array $attributes): static
{
$model = new static($attributes);
$model->save();
return $model;
}
/**
* Найти по условию или создать новую запись.
*
* @param array<string, mixed> $search
* @param array<string, mixed> $values
*/
public static function firstOrCreate(array $search, array $values = []): static
{
$query = static::query();
foreach ($search as $column => $value) {
$query->where($column, $value);
}
/** @var static|null $found */
$found = $query->first();
if ($found !== null) {
return $found;
}
return static::create(array_merge($search, $values));
}
/**
* Модель из готовой строки базы. Значения считаются сохранёнными.
*
* @param array<string, mixed> $row
*/
public static function fromRow(array $row): static
{
$model = new static();
$model->attributes = $row;
$model->original = $row;
$model->exists = true;
return $model;
}
// --- Запись --------------------------------------------------------------
/**
* Заполняет разрешённые поля.
*
* @param array<string, mixed> $attributes
*/
public function fill(array $attributes): static
{
foreach ($attributes as $key => $value) {
if ($this->fillable === [] || in_array($key, $this->fillable, true)) {
$this->setAttribute((string) $key, $value);
}
}
return $this;
}
/**
* Заполняет что угодно, минуя белый список. Только для своего кода —
* данные из запроса сюда пускать нельзя.
*
* @param array<string, mixed> $attributes
*/
public function forceFill(array $attributes): static
{
foreach ($attributes as $key => $value) {
$this->setAttribute((string) $key, $value);
}
return $this;
}
/**
* Сохраняет: вставляет новую запись или обновляет изменённые поля.
*/
public function save(): bool
{
$now = date('Y-m-d H:i:s');
if ($this->exists) {
$changes = $this->changes();
if ($changes === []) {
return true;
}
if ($this->timestamps && $this->hasColumn(self::UPDATED_AT)) {
$changes[self::UPDATED_AT] = $this->attributes[self::UPDATED_AT] = $now;
}
$this->connection()->update($this->table(), $changes, [static::$primaryKey => $this->key()]);
$this->original = $this->attributes;
return true;
}
if ($this->timestamps) {
foreach ([self::CREATED_AT, self::UPDATED_AT] as $column) {
if (!isset($this->attributes[$column]) && $this->hasColumn($column)) {
$this->attributes[$column] = $now;
}
}
}
$id = $this->connection()->insert($this->table(), $this->forStorage($this->attributes));
if ($id > 0 && !isset($this->attributes[static::$primaryKey])) {
$this->attributes[static::$primaryKey] = $id;
}
$this->original = $this->attributes;
$this->exists = true;
return true;
}
/**
* Обновить поля и сразу сохранить.
*
* @param array<string, mixed> $attributes
*/
public function update(array $attributes): bool
{
return $this->fill($attributes)->save();
}
/**
* Удалить. При включённом мягком удалении запись остаётся с отметкой времени.
*/
public function delete(): bool
{
if (!$this->exists) {
return false;
}
if ($this->softDelete) {
$this->attributes[self::DELETED_AT] = date('Y-m-d H:i:s');
$this->connection()->update(
$this->table(),
[self::DELETED_AT => $this->attributes[self::DELETED_AT]],
[static::$primaryKey => $this->key()]
);
return true;
}
$this->connection()->delete($this->table(), [static::$primaryKey => $this->key()]);
$this->exists = false;
return true;
}
/**
* Удалить насовсем, даже если включено мягкое удаление.
*/
public function forceDelete(): bool
{
if (!$this->exists) {
return false;
}
$this->connection()->delete($this->table(), [static::$primaryKey => $this->key()]);
$this->exists = false;
return true;
}
/**
* Вернуть мягко удалённую запись.
*/
public function restore(): bool
{
if (!$this->softDelete) {
return false;
}
$this->attributes[self::DELETED_AT] = null;
$this->connection()->update(
$this->table(),
[self::DELETED_AT => null],
[static::$primaryKey => $this->key()]
);
return true;
}
public function trashed(): bool
{
return $this->softDelete && ($this->attributes[self::DELETED_AT] ?? null) !== null;
}
/**
* Перечитать запись из базы.
*/
public function refresh(): static
{
$fresh = static::find($this->key());
if ($fresh !== null) {
$this->attributes = $fresh->attributes;
$this->original = $fresh->attributes;
$this->loaded = [];
}
return $this;
}
/**
* Что изменилось после чтения из базы.
*
* @return array<string, mixed>
*/
public function changes(): array
{
$changes = [];
foreach ($this->attributes as $key => $value) {
if (!array_key_exists($key, $this->original) || $this->original[$key] !== $value) {
$changes[$key] = $value;
}
}
// Ключ не меняем никогда: править первичный ключ через save() нельзя
unset($changes[static::$primaryKey]);
return $this->forStorage($changes);
}
public function isDirty(): bool
{
return $this->changes() !== [];
}
// --- Связи ---------------------------------------------------------------
/**
* Много записей чужой таблицы ссылаются на нас.
*
* @param class-string<Model> $related
*/
public function hasMany(string $related, ?string $foreignKey = null, ?string $localKey = null): HasMany
{
return new HasMany($this, $related, $foreignKey ?? $this->foreignKeyName(), $localKey ?? static::$primaryKey);
}
/**
* Одна чужая запись ссылается на нас.
*
* @param class-string<Model> $related
*/
public function hasOne(string $related, ?string $foreignKey = null, ?string $localKey = null): HasOne
{
return new HasOne($this, $related, $foreignKey ?? $this->foreignKeyName(), $localKey ?? static::$primaryKey);
}
/**
* Мы ссылаемся на чужую запись.
*
* @param class-string<Model> $related
*/
public function belongsTo(string $related, ?string $foreignKey = null, ?string $ownerKey = null): BelongsTo
{
$instance = new $related();
return new BelongsTo(
$this,
$related,
$foreignKey ?? $instance->foreignKeyName(),
$ownerKey ?? $instance->keyName()
);
}
/**
* Многие ко многим через таблицу-связку.
*
* @param class-string<Model> $related
*/
public function belongsToMany(
string $related,
?string $pivot = null,
?string $foreignKey = null,
?string $relatedKey = null
): BelongsToMany {
$instance = new $related();
// Имя связки по умолчанию — обе таблицы через подчёркивание по алфавиту
if ($pivot === null) {
$tables = [$this->table(), $instance->table()];
sort($tables);
$pivot = implode('_', $tables);
}
return new BelongsToMany(
$this,
$related,
$pivot,
$foreignKey ?? $this->foreignKeyName(),
$relatedKey ?? $instance->foreignKeyName()
);
}
/**
* Имя внешнего ключа на эту модель: User -> user_id.
*/
public function foreignKeyName(): string
{
$short = substr(strrchr(static::class, '\\') ?: static::class, 1);
return Str::snake($short) . '_id';
}
/**
* Объект связи по имени метода — нужен подгрузке через with().
*/
public function relation(string $name): Relation
{
if (!method_exists($this, $name)) {
throw new ProtonException('У модели ' . static::class . ' нет связи «' . $name . '»');
}
$relation = $this->{$name}();
if (!$relation instanceof Relation) {
throw new ProtonException('Метод ' . $name . '() модели ' . static::class . ' не возвращает связь');
}
return $relation;
}
/**
* Кладёт готовое значение связи — так работает подгрузка через with().
*/
public function setRelation(string $name, mixed $value): void
{
$this->loaded[$name] = $value;
}
public function relationLoaded(string $name): bool
{
return array_key_exists($name, $this->loaded);
}
// --- Доступ к значениям --------------------------------------------------
public function __get(string $name): mixed
{
if (array_key_exists($name, $this->loaded)) {
return $this->loaded[$name];
}
if (array_key_exists($name, $this->attributes)) {
return $this->castValue($name, $this->attributes[$name]);
}
// Связь, объявленная методом: $user->posts вернёт результат, $user->posts() — саму связь
if (method_exists($this, $name)) {
$relation = $this->{$name}();
if ($relation instanceof Relation) {
return $this->loaded[$name] = $relation->result();
}
}
return null;
}
public function __set(string $name, mixed $value): void
{
$this->setAttribute($name, $value);
}
public function __isset(string $name): bool
{
return isset($this->attributes[$name]) || isset($this->loaded[$name]);
}
public function setAttribute(string $name, mixed $value): void
{
$this->attributes[$name] = $value;
}
/**
* Значение как оно лежит в базе, без приведения типов.
*/
public function raw(string $name): mixed
{
return $this->attributes[$name] ?? null;
}
/**
* Все значения как массив — с приведением типов и без скрытых полей.
*
* @return array<string, mixed>
*/
public function toArray(): array
{
$result = [];
foreach ($this->attributes as $key => $value) {
if (in_array($key, $this->hidden, true)) {
continue;
}
$result[$key] = $this->castValue((string) $key, $value);
}
foreach ($this->loaded as $key => $value) {
if (is_array($value)) {
$result[$key] = array_map(
static fn (mixed $item): mixed => $item instanceof self ? $item->toArray() : $item,
$value
);
continue;
}
$result[$key] = $value instanceof self ? $value->toArray() : $value;
}
return $result;
}
/**
* @return array<string, mixed>
*/
public function jsonSerialize(): array
{
return $this->toArray();
}
/**
* Приведение значения по объявленному типу.
*/
protected function castValue(string $name, mixed $value): mixed
{
$type = $this->casts[$name] ?? null;
if ($type === null || $value === null) {
return $value;
}
return match ($type) {
'int', 'integer' => (int) $value,
'float', 'double' => (float) $value,
'bool', 'boolean' => (bool) $value && $value !== '0',
'json', 'array' => is_array($value) ? $value : (json_decode((string) $value, true) ?? []),
'datetime' => is_string($value) ? $value : (string) $value,
default => $value,
};
}
/**
* Готовит значения к записи: массивы и объекты уезжают в базу как JSON,
* булево — числом. Иначе PDO спотыкается о тип, которого не знает.
*
* @param array<string, mixed> $values
*
* @return array<string, mixed>
*/
protected function forStorage(array $values): array
{
foreach ($values as $key => $value) {
if (is_array($value)) {
$values[$key] = (string) json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
continue;
}
if (is_bool($value)) {
$values[$key] = (int) $value;
}
}
return $values;
}
/**
* Есть ли колонка в таблице. Ответ на процесс один: спрашивать схему на
* каждое сохранение незачем.
*/
protected function hasColumn(string $column): bool
{
static $columns = [];
$table = $this->table();
if (!isset($columns[$table])) {
$columns[$table] = [];
}
if (!array_key_exists($column, $columns[$table])) {
$columns[$table][$column] = $this->connection()->hasColumn($table, $column);
}
return $columns[$table][$column];
}
}
+257
View File
@@ -0,0 +1,257 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Model;
use Rsgrinko\Proton\Database\Query\Builder;
/**
* Построитель запросов, который отдаёт не массивы, а модели.
*
* Всё, что умеет обычный Builder (where, join, orderBy, paginate), работает и здесь —
* различие только в том, что приходит на выходе. Отдельный класс, а не флаг в
* построителе: возвращаемый тип должен быть понятен по коду, а не по настройке.
*/
final class Query extends Builder
{
/** @var class-string<Model> */
private string $model;
/** @var array<int, string> Связи, которые нужно подгрузить сразу */
private array $with = [];
/** Показывать ли мягко удалённые записи */
private bool $withTrashed = false;
/** Только мягко удалённые */
private bool $onlyTrashed = false;
/**
* @param class-string<Model> $model
*/
public function __construct(string $model)
{
$instance = new $model();
parent::__construct($instance->connection(), $instance->table());
$this->model = $model;
}
/**
* Подгрузить связи одним запросом на связь, а не по запросу на строку.
*/
public function with(string ...$relations): self
{
foreach ($relations as $relation) {
$this->with[] = $relation;
}
return $this;
}
/**
* Вместе с мягко удалёнными.
*/
public function withTrashed(bool $with = true): self
{
$this->withTrashed = $with;
return $this;
}
/**
* Только мягко удалённые — корзина.
*/
public function onlyTrashed(): self
{
$this->onlyTrashed = true;
return $this;
}
/**
* Модели по запросу.
*
* @return array<int, Model>
*/
public function get(): array
{
$this->applyTrashed();
$models = [];
foreach (parent::get() as $row) {
$models[] = ($this->model)::fromRow($row);
}
if ($models !== [] && $this->with !== []) {
$this->loadRelations($models);
}
return $models;
}
/**
* Строки как есть, без превращения в модели — нужно агрегатам и pluck.
*
* @return array<int, array<string, mixed>>
*/
public function rows(): array
{
$this->applyTrashed();
return parent::get();
}
/**
* Первая модель или null.
*/
public function first(): ?Model
{
$models = (clone $this)->limit(1)->get();
return $models[0] ?? null;
}
/**
* Первая модель или исключение — когда запись обязана быть.
*/
public function firstOrFail(): Model
{
$model = $this->first();
if ($model === null) {
throw new RecordNotFound('Запись не найдена: ' . $this->model);
}
return $model;
}
/**
* Одно значение — берём из сырой строки, модель тут не нужна.
*/
public function value(string $column): mixed
{
$row = (clone $this)->select($column)->limit(1)->rows()[0] ?? null;
if ($row === null) {
return null;
}
return reset($row);
}
public function count(string $column = '*'): int
{
$this->applyTrashed();
return parent::count($column);
}
/**
* Страница моделей.
*
* @return array{items: array<int, Model>, total: int, page: int, pages: int, per_page: int}
*/
public function paginate(int $page = 1, int $perPage = 30): array
{
$total = $this->count();
$pages = max(1, (int) ceil($total / max(1, $perPage)));
$page = max(1, min($page, $pages));
return [
'items' => (clone $this)->limit($perPage)->offset(($page - 1) * $perPage)->get(),
'total' => $total,
'page' => $page,
'pages' => $pages,
'per_page' => $perPage,
];
}
/**
* Обновление через модель проставляет отметку времени — иначе updated_at
* молча отстаёт от данных.
*
* @param array<string, mixed> $data
*/
public function update(array $data): int
{
$model = new ($this->model)();
if ($model->hasTimestamps() && !array_key_exists('updated_at', $data)) {
$data['updated_at'] = date('Y-m-d H:i:s');
}
$this->applyTrashed();
return parent::update($data);
}
/**
* Мягкое удаление, если модель его поддерживает, иначе обычное.
*/
public function delete(): int
{
$model = new ($this->model)();
if ($model->softDeletes()) {
return parent::update([Model::DELETED_AT => date('Y-m-d H:i:s')]);
}
return parent::delete();
}
/**
* Настоящее удаление, даже если включено мягкое.
*/
public function forceDelete(): int
{
return parent::delete();
}
/**
* Условие по мягкому удалению добавляется один раз и перед самым запросом:
* до этого момента ещё может прийти withTrashed().
*/
private function applyTrashed(): void
{
static $applied = false;
$model = new ($this->model)();
if (!$model->softDeletes() || $this->withTrashed) {
return;
}
// Повторный вызов (count(), затем get()) не должен добавлять условие дважды
foreach ($this->wheres as $where) {
if (str_contains($where['sql'], Model::DELETED_AT)) {
return;
}
}
if ($this->onlyTrashed) {
$this->whereNotNull(Model::DELETED_AT);
return;
}
$this->whereNull(Model::DELETED_AT);
}
/**
* Подгружает объявленные связи: один запрос на связь.
*
* @param array<int, Model> $models
*/
private function loadRelations(array $models): void
{
foreach ($this->with as $name) {
$relation = $models[0]->relation($name);
$relation->load($name, $models);
}
}
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Model;
use Rsgrinko\Proton\Support\ProtonException;
/**
* Записи нет. Ядро панели ловит это исключение и возвращает человека в список
* с сообщением, API отвечает 404 — проверять «а вдруг null» в каждом контроллере
* не нужно.
*/
final class RecordNotFound extends ProtonException
{
/** Куда вернуть человека — имя маршрута списка */
private string $route;
public function __construct(string $message = 'Запись не найдена', string $route = '')
{
parent::__construct($message, [], 404);
$this->route = $route;
}
public function route(): string
{
return $this->route;
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Model\Relations;
use Rsgrinko\Proton\Database\Model\Model;
/**
* «Мой хозяин»: внешний ключ лежит у нас. У заметки есть автор —
* $note->belongsTo(User::class) по note.user_id.
*/
final class BelongsTo extends Relation
{
public function result(): ?Model
{
$key = $this->parent->raw($this->foreignKey);
if ($key === null || $key === '' || $key === 0) {
return null;
}
return $this->query()->where($this->localKey, $key)->first();
}
/**
* @param array<int, Model> $models
*/
public function load(string $name, array $models): void
{
$keys = $this->keys($models, $this->foreignKey);
if ($keys === []) {
return;
}
$owners = [];
foreach ($this->query()->whereIn($this->localKey, $keys)->get() as $owner) {
$owners[(string) $owner->raw($this->localKey)] = $owner;
}
foreach ($models as $model) {
$model->setRelation($name, $owners[(string) $model->raw($this->foreignKey)] ?? null);
}
}
}
@@ -0,0 +1,167 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Model\Relations;
use Rsgrinko\Proton\Database\Connection;
use Rsgrinko\Proton\Database\Model\Model;
/**
* «Многие ко многим» через таблицу-связку: у роли много прав, у пользователя
* много проектов. Сама связка — обычная таблица из двух ключей, своей модели
* ей не нужно.
*/
final class BelongsToMany extends Relation
{
private string $pivot;
/** Колонка связки, указывающая на связанную модель */
private string $relatedKey;
/**
* @param class-string<Model> $related
*/
public function __construct(Model $parent, string $related, string $pivot, string $foreignKey, string $relatedKey)
{
parent::__construct($parent, $related, $foreignKey, $parent->keyName());
$this->pivot = $pivot;
$this->relatedKey = $relatedKey;
}
/**
* @return array<int, Model>
*/
public function result(): array
{
$key = $this->parent->raw($this->localKey);
if ($key === null) {
return [];
}
$ids = $this->db()->table($this->pivot)
->where($this->foreignKey, $key)
->pluck($this->relatedKey);
if ($ids === []) {
return [];
}
$instance = new ($this->related)();
return $this->query()->whereIn($instance->keyName(), array_values($ids))->get();
}
/**
* Привязать запись, если её ещё нет в связке.
*/
public function attach(int|string $id): void
{
$exists = $this->db()->table($this->pivot)
->where($this->foreignKey, $this->parent->raw($this->localKey))
->where($this->relatedKey, $id)
->exists();
if ($exists) {
return;
}
$this->db()->insert($this->pivot, [
$this->foreignKey => $this->parent->raw($this->localKey),
$this->relatedKey => $id,
]);
}
/**
* Отвязать запись.
*/
public function detach(int|string $id): void
{
$this->db()->delete($this->pivot, [
$this->foreignKey => $this->parent->raw($this->localKey),
$this->relatedKey => $id,
]);
}
/**
* Оставить в связке ровно этот список: чего нет — добавить, лишнее — убрать.
*
* @param array<int, int|string> $ids
*/
public function sync(array $ids): void
{
$current = array_map(
'strval',
array_values($this->db()->table($this->pivot)
->where($this->foreignKey, $this->parent->raw($this->localKey))
->pluck($this->relatedKey))
);
$wanted = array_map('strval', $ids);
foreach (array_diff($wanted, $current) as $id) {
$this->attach($id);
}
foreach (array_diff($current, $wanted) as $id) {
$this->detach($id);
}
}
/**
* @param array<int, Model> $models
*/
public function load(string $name, array $models): void
{
$keys = $this->keys($models, $this->localKey);
if ($keys === []) {
return;
}
$links = $this->db()->table($this->pivot)
->whereIn($this->foreignKey, $keys)
->get();
if ($links === []) {
foreach ($models as $model) {
$model->setRelation($name, []);
}
return;
}
$instance = new ($this->related)();
$ids = array_values(array_unique(array_map(
fn (array $row): mixed => $row[$this->relatedKey],
$links
)));
$related = [];
foreach ($this->query()->whereIn($instance->keyName(), $ids)->get() as $model) {
$related[(string) $model->key()] = $model;
}
$grouped = [];
foreach ($links as $link) {
$target = $related[(string) $link[$this->relatedKey]] ?? null;
if ($target !== null) {
$grouped[(string) $link[$this->foreignKey]][] = $target;
}
}
foreach ($models as $model) {
$model->setRelation($name, $grouped[(string) $model->raw($this->localKey)] ?? []);
}
}
private function db(): Connection
{
return $this->parent->connection();
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Model\Relations;
use Rsgrinko\Proton\Database\Model\Model;
/**
* «Много моих»: чужие записи ссылаются на нас своим внешним ключом.
* У пользователя — заметки: $user->hasMany(Note::class) по note.user_id.
*/
class HasMany extends Relation
{
/**
* @return array<int, Model>
*/
public function result(): array
{
$key = $this->parent->raw($this->localKey);
if ($key === null) {
return [];
}
return $this->query()->where($this->foreignKey, $key)->get();
}
/**
* Новая запись на этой стороне связи — внешний ключ проставляется сам.
*
* @param array<string, mixed> $attributes
*/
public function create(array $attributes): Model
{
$model = new ($this->related)($attributes);
$model->setAttribute($this->foreignKey, $this->parent->raw($this->localKey));
$model->save();
return $model;
}
/**
* @param array<int, Model> $models
*/
public function load(string $name, array $models): void
{
$keys = $this->keys($models, $this->localKey);
if ($keys === []) {
return;
}
$grouped = [];
foreach ($this->query()->whereIn($this->foreignKey, $keys)->get() as $related) {
$grouped[(string) $related->raw($this->foreignKey)][] = $related;
}
foreach ($models as $model) {
$model->setRelation($name, $grouped[(string) $model->raw($this->localKey)] ?? []);
}
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Model\Relations;
use Rsgrinko\Proton\Database\Model\Model;
/**
* «Один мой»: то же, что HasMany, только запись ожидается одна —
* профиль пользователя, настройки, последняя сессия.
*/
final class HasOne extends HasMany
{
public function result(): ?Model
{
$key = $this->parent->raw($this->localKey);
if ($key === null) {
return null;
}
return $this->query()->where($this->foreignKey, $key)->first();
}
/**
* @param array<int, Model> $models
*/
public function load(string $name, array $models): void
{
$keys = $this->keys($models, $this->localKey);
if ($keys === []) {
return;
}
$found = [];
foreach ($this->query()->whereIn($this->foreignKey, $keys)->get() as $related) {
$found[(string) $related->raw($this->foreignKey)] ??= $related;
}
foreach ($models as $model) {
$model->setRelation($name, $found[(string) $model->raw($this->localKey)] ?? null);
}
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Model\Relations;
use Rsgrinko\Proton\Database\Model\Model;
use Rsgrinko\Proton\Database\Model\Query;
/**
* Связь между моделями.
*
* Умеет две вещи: достать результат для одной записи ($user->posts) и подгрузить
* связь сразу для списка записей (Query::with('posts')) — одним запросом на связь,
* а не по запросу на строку. Второе и есть причина, по которой связь оформлена
* объектом, а не методом, возвращающим сразу данные.
*/
abstract class Relation
{
protected Model $parent;
/** @var class-string<Model> */
protected string $related;
protected string $foreignKey;
protected string $localKey;
/**
* @param class-string<Model> $related
*/
public function __construct(Model $parent, string $related, string $foreignKey, string $localKey)
{
$this->parent = $parent;
$this->related = $related;
$this->foreignKey = $foreignKey;
$this->localKey = $localKey;
}
/**
* Построитель по связанной модели — на него можно навесить свои условия:
* $user->posts()->where('published', 1)->get().
*/
public function query(): Query
{
return ($this->related)::query();
}
/**
* Результат связи для одной записи.
*/
abstract public function result(): mixed;
/**
* Подгружает связь сразу для списка моделей.
*
* @param array<int, Model> $models
*/
abstract public function load(string $name, array $models): void;
/**
* Собирает значения ключа у списка моделей — по ним и идёт один общий запрос.
*
* @param array<int, Model> $models
*
* @return array<int, mixed>
*/
protected function keys(array $models, string $column): array
{
$keys = [];
foreach ($models as $model) {
$value = $model->raw($column);
if ($value !== null && !in_array($value, $keys, true)) {
$keys[] = $value;
}
}
return $keys;
}
}
+675
View File
@@ -0,0 +1,675 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Query;
use Closure;
use Rsgrinko\Proton\Database\Connection;
use Rsgrinko\Proton\Database\DatabaseException;
/**
* Построитель запросов.
*
* $rows = $db->table('users')
* ->where('active', 1)
* ->whereIn('role_id', [1, 2])
* ->orderBy('created_at', 'desc')
* ->limit(20)
* ->get();
*
* Значения всегда уходят параметрами, имена таблиц и колонок сверяются регуляркой:
* их параметром не подставить, а склеивать в SQL что попало нельзя. Каждое значение
* получает своё имя параметра (p0, p1, …) — MySQL с настоящими подготовленными
* выражениями не разрешает использовать один параметр дважды.
*/
class Builder
{
protected Connection $db;
protected string $table;
/** @var array<int, string> */
protected array $columns = ['*'];
protected bool $distinct = false;
/** @var array<int, array{type: string, sql: string, boolean: string}> */
protected array $wheres = [];
/** @var array<int, string> */
protected array $joins = [];
/** @var array<int, string> */
protected array $groups = [];
/** @var array<int, string> */
protected array $havings = [];
/** @var array<int, string> */
protected array $orders = [];
protected ?int $limit = null;
protected ?int $offset = null;
/** @var array<string, mixed> Значения параметров */
protected array $bindings = [];
/** Счётчик имён параметров */
protected int $counter = 0;
public function __construct(Connection $db, string $table)
{
$this->db = $db;
$this->table = $this->name($table);
}
public function connection(): Connection
{
return $this->db;
}
public function from(string $table): static
{
$this->table = $this->name($table);
return $this;
}
/**
* Колонки выборки. Выражения (COUNT(*), a.b AS c) допускаются как есть —
* их пишет разработчик, а не пользователь.
*/
public function select(string ...$columns): static
{
$this->columns = $columns === [] ? ['*'] : $columns;
return $this;
}
public function addSelect(string $column): static
{
if ($this->columns === ['*']) {
$this->columns = [];
}
$this->columns[] = $column;
return $this;
}
public function distinct(bool $distinct = true): static
{
$this->distinct = $distinct;
return $this;
}
/**
* Условие. Два аргумента — равенство, три — со своим оператором.
* Замыкание — скобка: ->where(function (Builder $q) { … }).
*/
public function where(string|Closure $column, mixed $operator = null, mixed $value = null, string $boolean = 'AND'): static
{
if ($column instanceof Closure) {
return $this->nested($column, $boolean);
}
if (func_num_args() === 2) {
$value = $operator;
$operator = '=';
}
$operator = strtoupper(trim((string) $operator));
if (!in_array($operator, ['=', '<>', '!=', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE'], true)) {
throw new DatabaseException('Недопустимый оператор условия: ' . $operator);
}
if ($value === null) {
return $operator === '=' ? $this->whereNull($column, $boolean) : $this->whereNotNull($column, $boolean);
}
$this->wheres[] = [
'type' => 'basic',
'sql' => $this->name($column) . ' ' . $operator . ' ' . $this->bind($value),
'boolean' => $boolean,
];
return $this;
}
public function orWhere(string|Closure $column, mixed $operator = null, mixed $value = null): static
{
if (func_num_args() === 2) {
return $this->where($column, '=', $operator, 'OR');
}
return $this->where($column, $operator, $value, 'OR');
}
/**
* @param array<int, mixed> $values
*/
public function whereIn(string $column, array $values, string $boolean = 'AND', bool $not = false): static
{
if ($values === []) {
// Пустой список: «ни одно значение не подходит» — и это не ошибка,
// а нормальный результат фильтра, из которого ничего не выбрали
$this->wheres[] = ['type' => 'basic', 'sql' => $not ? '1 = 1' : '1 = 0', 'boolean' => $boolean];
return $this;
}
$placeholders = array_map(fn (mixed $value): string => $this->bind($value), array_values($values));
$this->wheres[] = [
'type' => 'basic',
'sql' => $this->name($column) . ($not ? ' NOT IN (' : ' IN (') . implode(', ', $placeholders) . ')',
'boolean' => $boolean,
];
return $this;
}
/**
* @param array<int, mixed> $values
*/
public function whereNotIn(string $column, array $values, string $boolean = 'AND'): static
{
return $this->whereIn($column, $values, $boolean, true);
}
public function whereNull(string $column, string $boolean = 'AND'): static
{
$this->wheres[] = ['type' => 'basic', 'sql' => $this->name($column) . ' IS NULL', 'boolean' => $boolean];
return $this;
}
public function whereNotNull(string $column, string $boolean = 'AND'): static
{
$this->wheres[] = ['type' => 'basic', 'sql' => $this->name($column) . ' IS NOT NULL', 'boolean' => $boolean];
return $this;
}
public function whereBetween(string $column, mixed $from, mixed $to, string $boolean = 'AND'): static
{
$this->wheres[] = [
'type' => 'basic',
'sql' => $this->name($column) . ' BETWEEN ' . $this->bind($from) . ' AND ' . $this->bind($to),
'boolean' => $boolean,
];
return $this;
}
/**
* Поиск подстроки. Служебные символы LIKE экранируем: иначе «100%» в поиске
* превращается в «что угодно после 100».
*/
public function whereLike(string $column, string $value, string $boolean = 'AND'): static
{
$escaped = str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $value);
$this->wheres[] = [
'type' => 'basic',
'sql' => $this->name($column) . ' LIKE ' . $this->bind('%' . $escaped . '%'),
'boolean' => $boolean,
];
return $this;
}
/**
* Готовое условие со своими параметрами — там, где построителя не хватает.
*
* @param array<string, mixed> $bindings
*/
public function whereRaw(string $sql, array $bindings = [], string $boolean = 'AND'): static
{
foreach ($bindings as $key => $value) {
$this->bindings[ltrim((string) $key, ':')] = $value;
}
$this->wheres[] = ['type' => 'raw', 'sql' => $sql, 'boolean' => $boolean];
return $this;
}
/**
* Условие, только если значение чего-то стоит: удобно для фильтров списка.
*/
public function when(mixed $condition, callable $callback): static
{
if ($condition !== null && $condition !== '' && $condition !== false && $condition !== []) {
$callback($this, $condition);
}
return $this;
}
public function join(string $table, string $first, string $operator, string $second, string $type = 'INNER'): static
{
$type = strtoupper($type);
if (!in_array($type, ['INNER', 'LEFT', 'RIGHT'], true)) {
throw new DatabaseException('Недопустимый тип соединения: ' . $type);
}
if (!in_array($operator, ['=', '<', '<=', '>', '>=', '<>'], true)) {
throw new DatabaseException('Недопустимый оператор соединения: ' . $operator);
}
$this->joins[] = $type . ' JOIN ' . $this->name($table) . ' ON '
. $this->name($first) . ' ' . $operator . ' ' . $this->name($second);
return $this;
}
public function leftJoin(string $table, string $first, string $operator, string $second): static
{
return $this->join($table, $first, $operator, $second, 'LEFT');
}
public function groupBy(string ...$columns): static
{
foreach ($columns as $column) {
$this->groups[] = $this->name($column);
}
return $this;
}
/**
* @param array<string, mixed> $bindings
*/
public function having(string $sql, array $bindings = []): static
{
foreach ($bindings as $key => $value) {
$this->bindings[ltrim((string) $key, ':')] = $value;
}
$this->havings[] = $sql;
return $this;
}
public function orderBy(string $column, string $direction = 'asc'): static
{
$direction = strtolower($direction) === 'desc' ? 'DESC' : 'ASC';
$this->orders[] = $this->name($column) . ' ' . $direction;
return $this;
}
public function latest(string $column = 'created_at'): static
{
return $this->orderBy($column, 'desc');
}
public function limit(?int $limit): static
{
$this->limit = $limit === null ? null : max(0, $limit);
return $this;
}
public function offset(int $offset): static
{
$this->offset = max(0, $offset);
return $this;
}
/**
* Строки запроса.
*
* @return array<int, array<string, mixed>>
*/
public function get(): array
{
return $this->db->select($this->toSql(), $this->bindings);
}
/**
* Первая строка или null.
*
* Тип возврата шире, чем массив: наследник для моделей отдаёт отсюда объект,
* а сузить объявленный ?array он бы не смог.
*
* @return array<string, mixed>|object|null
*/
public function first(): array|object|null
{
$limit = $this->limit;
$this->limit(1);
$rows = $this->get();
$this->limit = $limit;
return $rows[0] ?? null;
}
/**
* Одно значение первой строки.
*/
public function value(string $column): mixed
{
$row = (clone $this)->select($column)->first();
if ($row === null) {
return null;
}
return reset($row);
}
/**
* Плоский список значений колонки, при желании с ключами.
*
* @return array<int|string, mixed>
*/
public function pluck(string $column, ?string $key = null): array
{
$query = clone $this;
$rows = $key === null ? $query->select($column)->get() : $query->select($key, $column)->get();
$result = [];
foreach ($rows as $row) {
$short = $this->shortName($column);
if ($key === null) {
$result[] = $row[$short] ?? null;
continue;
}
$result[(string) ($row[$this->shortName($key)] ?? '')] = $row[$short] ?? null;
}
return $result;
}
public function count(string $column = '*'): int
{
$query = clone $this;
$query->orders = [];
return (int) $query->db->value(
$query->select('COUNT(' . ($column === '*' ? '*' : $this->name($column)) . ') AS aggregate')->toSql(),
$query->bindings
);
}
public function sum(string $column): float
{
$query = clone $this;
$query->orders = [];
return (float) $query->db->value(
$query->select('SUM(' . $this->name($column) . ') AS aggregate')->toSql(),
$query->bindings
);
}
public function max(string $column): mixed
{
$query = clone $this;
$query->orders = [];
return $query->db->value(
$query->select('MAX(' . $this->name($column) . ') AS aggregate')->toSql(),
$query->bindings
);
}
public function exists(): bool
{
return (clone $this)->limit(1)->first() !== null;
}
/**
* Страница результатов вместе со счётчиком — для списков в панели.
*
* @return array{items: array<int, array<string, mixed>>, total: int, page: int, pages: int, per_page: int}
*/
public function paginate(int $page = 1, int $perPage = 30): array
{
$total = $this->count();
$pages = max(1, (int) ceil($total / max(1, $perPage)));
$page = max(1, min($page, $pages));
$items = (clone $this)->limit($perPage)->offset(($page - 1) * $perPage)->get();
return [
'items' => $items,
'total' => $total,
'page' => $page,
'pages' => $pages,
'per_page' => $perPage,
];
}
/**
* Обходит таблицу порциями — чтобы не поднимать в память миллион строк.
* Замыкание вернуло false — обход прекращается.
*
* @param callable(array<int, array<string, mixed>>): (bool|void) $callback
*/
public function chunk(int $size, callable $callback): void
{
$page = 1;
do {
$rows = (clone $this)->limit($size)->offset(($page - 1) * $size)->get();
if ($rows === []) {
return;
}
if ($callback($rows) === false) {
return;
}
$page++;
} while (count($rows) === $size);
}
/**
* Вставка. Возвращает id новой записи.
*
* @param array<string, mixed> $data
*/
public function insert(array $data): int
{
return $this->db->insert($this->table, $data);
}
/**
* Обновление по накопленным условиям.
*
* @param array<string, mixed> $data
*/
public function update(array $data): int
{
if ($data === []) {
return 0;
}
$set = [];
foreach ($data as $column => $value) {
$set[] = $this->name($column) . ' = ' . $this->bind($value, 'set');
}
$sql = 'UPDATE ' . $this->table . ' SET ' . implode(', ', $set) . $this->whereSql();
return $this->db->execute($sql, $this->bindings);
}
/**
* Увеличить числовую колонку — счётчики просмотров и попыток.
*/
public function increment(string $column, int $amount = 1): int
{
$column = $this->name($column);
return $this->db->execute(
'UPDATE ' . $this->table . ' SET ' . $column . ' = ' . $column . ' + ' . (int) $amount . $this->whereSql(),
$this->bindings
);
}
/**
* Удаление по накопленным условиям. Без условий удалять отказываемся:
* «снести всю таблицу» должно писаться явно, а не получаться по забывчивости.
*/
public function delete(): int
{
if ($this->wheres === []) {
throw new DatabaseException('Удаление без условий запрещено: добавьте where() или зовите truncate()');
}
return $this->db->execute('DELETE FROM ' . $this->table . $this->whereSql(), $this->bindings);
}
/**
* Собранный SQL — пригождается в отладке и тестах.
*/
public function toSql(): string
{
$sql = 'SELECT ' . ($this->distinct ? 'DISTINCT ' : '') . implode(', ', $this->columns)
. ' FROM ' . $this->table;
if ($this->joins !== []) {
$sql .= ' ' . implode(' ', $this->joins);
}
$sql .= $this->whereSql();
if ($this->groups !== []) {
$sql .= ' GROUP BY ' . implode(', ', $this->groups);
}
if ($this->havings !== []) {
$sql .= ' HAVING ' . implode(' AND ', $this->havings);
}
if ($this->orders !== []) {
$sql .= ' ORDER BY ' . implode(', ', $this->orders);
}
if ($this->limit !== null) {
$sql .= ' LIMIT ' . $this->limit;
}
if ($this->offset !== null && $this->offset > 0) {
// В обеих базах OFFSET без LIMIT не работает — подставляем предел сами
$sql .= ($this->limit === null ? ' LIMIT 18446744073709551615' : '') . ' OFFSET ' . $this->offset;
}
return $sql;
}
/**
* Значения параметров запроса.
*
* @return array<string, mixed>
*/
public function bindings(): array
{
return $this->bindings;
}
protected function whereSql(): string
{
if ($this->wheres === []) {
return '';
}
$sql = '';
foreach ($this->wheres as $index => $where) {
$sql .= ($index === 0 ? '' : ' ' . $where['boolean'] . ' ') . $where['sql'];
}
return ' WHERE ' . $sql;
}
/**
* Скобка из замыкания: ->where(function (Builder $q) { $q->where(…)->orWhere(…); }).
*/
protected function nested(Closure $callback, string $boolean): static
{
$nested = new self($this->db, $this->table);
// Счётчик общий, иначе имена параметров во вложенной части столкнутся с нашими
$nested->counter = $this->counter;
$callback($nested);
$this->counter = $nested->counter;
if ($nested->wheres === []) {
return $this;
}
$this->bindings = array_merge($this->bindings, $nested->bindings);
$this->wheres[] = [
'type' => 'nested',
'sql' => '(' . substr($nested->whereSql(), 7) . ')',
'boolean' => $boolean,
];
return $this;
}
/**
* Кладёт значение в параметры и возвращает его имя для SQL.
*/
protected function bind(mixed $value, string $prefix = 'p'): string
{
$name = $prefix . $this->counter++;
$this->bindings[$name] = $value;
return ':' . $name;
}
/**
* Имя таблицы или колонки. Разрешаем «таблица.колонка» и звёздочку —
* всё остальное отвергаем: подставлять в SQL непонятно что нельзя.
*/
protected function name(string $name): string
{
$name = trim($name);
if (preg_match('/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*|\.\*)?$/', $name) !== 1) {
throw new DatabaseException('Недопустимое имя таблицы или колонки: ' . $name);
}
return $name;
}
/**
* Имя колонки без таблицы: строки из базы приходят с короткими ключами.
*/
protected function shortName(string $column): string
{
$dot = strrpos($column, '.');
return $dot === false ? $column : substr($column, $dot + 1);
}
}
+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';
}
}