Files
laysite/app/Content/Database.php
T

119 lines
4.8 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Content;
use App\Config\Environment;
use PDO;
use RuntimeException;
use Throwable;
final class Database
{
private const SCHEMA_VERSION = 4;
// Avoid reusing a deleted ID that may still be open in an editing form.
public const NEXT_ARTICLE_ID = 'MAX(COALESCE((SELECT MAX(id) FROM articles), 0),
COALESCE((SELECT MAX(article_id) FROM article_deletions), 0)) + 1';
private static ?PDO $connection = null;
public static function path(): string
{
return Environment::path('LAYSITE_DB', 'storage/laysite.sqlite');
}
public static function connect(): PDO
{
if (self::$connection !== null) {
return self::$connection;
}
$path = self::path();
if (!is_dir(dirname($path)) && !mkdir(dirname($path), 0750, true) && !is_dir(dirname($path))) {
throw new RuntimeException('无法创建 SQLite 存放目录。');
}
$pdo = new PDO('sqlite:' . $path, options: [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]);
$pdo->exec('PRAGMA busy_timeout = 5000');
$pdo->exec('PRAGMA foreign_keys = ON');
self::$connection = $pdo;
return $pdo;
}
public static function initialize(): void
{
$root = dirname(__DIR__, 2);
$pdo = self::connect();
$pdo->exec('PRAGMA journal_mode = WAL');
self::write(function (PDO $pdo) use ($root): void {
$version = (int) $pdo->query('PRAGMA user_version')->fetchColumn();
if ($version > self::SCHEMA_VERSION) {
throw new RuntimeException('当前 SQLite 数据库需要更新版本的 LaySite。');
}
$pdo->exec(file_get_contents($root . '/resources/schema.sql'));
if ($version < 3) {
foreach (['pages', 'sections'] as $table) {
$columns = $pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll();
if (!in_array('presentation', array_column($columns, 'name'), true)) {
$pdo->exec("ALTER TABLE $table ADD COLUMN presentation TEXT NOT NULL DEFAULT '{}'");
}
}
}
$pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)')->execute([self::json(['name' => '我的网站'])]);
$pdo->prepare("INSERT OR IGNORE INTO pages
(slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
VALUES ('home', '首页', '我的网站', '欢迎访问我的网站。', '我的网站', '', '', '', '', '[]', '[]')")
->execute();
$articles = $pdo->prepare("INSERT OR IGNORE INTO pages
(slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
VALUES ('articles', '文章与动态', '文章与动态', '浏览站点发布的文章。', '文章与动态', '', '', '', '', '[]', '[]')");
$articles->execute();
if ($articles->rowCount() === 1) {
$pdo->prepare("INSERT INTO sections (page_slug, key, title, lead, body, feed, position)
VALUES ('articles', 'posts', '最新文章', '', '', ?, 0)")->execute([BlockTemplates::ARTICLE_FEED]);
}
$category = $pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
foreach (Repository::CATEGORIES as $slug => $name) {
$category->execute([$slug, $name]);
}
if ($version < 2) {
OAuthCredentials::migrateLegacy($pdo);
}
if ($version < 4) {
$columns = $pdo->query('PRAGMA table_info(pages)')->fetchAll();
if (!in_array('layout_id', array_column($columns, 'name'), true)) {
$pdo->exec('ALTER TABLE pages ADD COLUMN layout_id INTEGER REFERENCES design_presets(id)');
}
$pdo->exec('CREATE UNIQUE INDEX IF NOT EXISTS pages_layout_id ON pages(layout_id)');
LayoutPage::migrate($pdo);
}
if ($version < self::SCHEMA_VERSION) {
$pdo->exec('PRAGMA user_version = ' . self::SCHEMA_VERSION);
}
});
}
public static function write(callable $operation): mixed
{
$pdo = self::connect();
$pdo->exec('BEGIN IMMEDIATE');
try {
$result = $operation($pdo);
$pdo->exec('COMMIT');
return $result;
} catch (Throwable $error) {
$pdo->exec('ROLLBACK');
throw $error;
}
}
public static function json(array $data): string
{
return json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
}
}