You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/AnnouncementSchema.php

56 lines
2.6 KiB
PHP

<?php
namespace App\Services;
/** Explicit cloudInit migration only. Never called by HTTP request handlers. */
final class AnnouncementSchema
{
public static function upgrade($connection): void
{
$schema = $connection->getSchemaBuilder();
if (!$schema->hasTable('announcement')) {
throw new \RuntimeException('缺少 announcement 表,请先导入 web/sql/ss.sql');
}
$legacy = array_values(array_filter(['date', 'content', 'markdown'],
static fn (string $column): bool => $schema->hasColumn('announcement', $column)));
// Check before any DDL: this rollout only retires an EMPTY legacy table.
if ($legacy !== [] && $connection->table('announcement')->exists()) {
throw new \RuntimeException('旧公告表仍有数据,已停止升级且未修改公告表;请先备份并明确处理旧公告后重试');
}
$mysql = $connection->getDriverName() === 'mysql';
$columns = ['title', 'type', 'status', 'body', 'published_at', 'updated_at'];
foreach ($columns as $column) {
if ($schema->hasColumn('announcement', $column)) {
continue;
}
$schema->table('announcement', static function ($table) use ($column, $mysql): void {
if ($column === 'title') {
$field = $table->string('title', 120)->default('');
if ($mysql) $field->charset('utf8mb4')->collation('utf8mb4_unicode_ci');
} elseif ($column === 'type') {
$table->string('type', 20)->default('notice');
} elseif ($column === 'status') {
$table->string('status', 20)->default('withdrawn');
} elseif ($column === 'body') {
$field = $table->longText('body');
if ($mysql) $field->charset('utf8mb4')->collation('utf8mb4_unicode_ci');
} elseif ($column === 'published_at') {
$table->dateTime($column)->nullable();
} else {
$table->dateTime($column);
}
});
}
if (!$schema->hasIndex('announcement', 'announcement_published')) {
$schema->table('announcement', static function ($table): void {
$table->index(['status', 'published_at', 'id'], 'announcement_published');
});
}
if ($legacy !== []) {
$schema->table('announcement', static function ($table) use ($legacy): void {
$table->dropColumn($legacy);
});
}
}
}