forked from laysense/laysense.cn
149 lines
7.1 KiB
PHP
149 lines
7.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Content;
|
|
|
|
use PDO;
|
|
use RuntimeException;
|
|
use Throwable;
|
|
|
|
final class Database
|
|
{
|
|
// 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 connect(): PDO
|
|
{
|
|
if (self::$connection !== null) {
|
|
return self::$connection;
|
|
}
|
|
|
|
$path = getenv('LAYSENSE_DB') ?: dirname(__DIR__, 2) . '/storage/laysense.sqlite';
|
|
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);
|
|
$seed = json_decode(file_get_contents($root . '/resources/seed.json'), true, flags: JSON_THROW_ON_ERROR);
|
|
$pdo = self::connect();
|
|
$pdo->exec('PRAGMA journal_mode = WAL');
|
|
|
|
self::write(function (PDO $pdo) use ($root, $seed): void {
|
|
$articleColumns = array_column($pdo->query('PRAGMA table_info(articles)')->fetchAll(), 'name');
|
|
if (in_array('category', $articleColumns, true)) {
|
|
throw new RuntimeException('请将 LAYSENSE_DB 指向一个新的 SQLite 文件,再运行安装命令。');
|
|
}
|
|
$pdo->exec(file_get_contents($root . '/resources/schema.sql'));
|
|
foreach (['pages', 'sections'] as $table) {
|
|
$columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name');
|
|
if (!in_array('alignments', $columns, true)) {
|
|
$pdo->exec("ALTER TABLE $table ADD COLUMN alignments TEXT NOT NULL DEFAULT '{}'");
|
|
}
|
|
}
|
|
$pageColumns = array_column($pdo->query('PRAGMA table_info(pages)')->fetchAll(), 'name');
|
|
if (!in_array('theme', $pageColumns, true)) {
|
|
$pdo->exec("ALTER TABLE pages ADD COLUMN theme TEXT NOT NULL DEFAULT ''");
|
|
}
|
|
$site = $pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)');
|
|
$site->execute([self::json($seed['site'])]);
|
|
|
|
$pageQuery = $pdo->prepare('INSERT OR IGNORE INTO pages
|
|
(slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
$sectionQuery = $pdo->prepare('INSERT OR IGNORE INTO sections
|
|
(page_slug, key, title, lead, style, body, feed, position) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
|
|
foreach ($seed['pages'] as $page) {
|
|
$pageQuery->execute([
|
|
$page['slug'], $page['name'], $page['title'], $page['description'], $page['heading'],
|
|
$page['accent'], $page['lead'], $page['image'], $page['alt'],
|
|
self::json($page['actions']), self::json($page['quicklinks']),
|
|
]);
|
|
if ($pageQuery->rowCount() !== 1) {
|
|
continue;
|
|
}
|
|
foreach ($page['sections'] as $index => $section) {
|
|
$sectionQuery->execute([
|
|
$page['slug'], $section['key'], $section['title'], $section['lead'],
|
|
$section['style'], Html::sanitize($section['body']), isset($section['feed']) ? self::json($section['feed']) : null, $index,
|
|
]);
|
|
}
|
|
}
|
|
|
|
if ((int) $pdo->query('PRAGMA user_version')->fetchColumn() === 0) {
|
|
$heroDirectory = $pdo->prepare("INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, position)
|
|
VALUES ('home', 'hero-directory', '产品与服务导航', '', 'hero-links', ?, -1)");
|
|
$heroDirectory->execute([BlockTemplates::PRODUCT_LINKS]);
|
|
$network = $pdo->prepare("INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, position)
|
|
SELECT 'home', 'network', '支持项目与合作伙伴', '', 'plain', '', ?, COALESCE(MAX(position), -1) + 1
|
|
FROM sections WHERE page_slug = 'home'");
|
|
$network->execute([BlockTemplates::NETWORK_FEED]);
|
|
if ($heroDirectory->rowCount() + $network->rowCount() > 0) {
|
|
$pdo->exec("UPDATE pages SET version = version + 1 WHERE slug = 'home'");
|
|
}
|
|
$pdo->exec('PRAGMA user_version = 1');
|
|
}
|
|
|
|
$category = $pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
|
|
foreach (Repository::CATEGORIES as $slug => $name) {
|
|
$category->execute([$slug, $name]);
|
|
}
|
|
$article = $pdo->prepare("INSERT OR IGNORE INTO articles
|
|
(id, slug, title, summary, body, body_format, card, tags, status, published_at, updated_at, legacy_path)
|
|
SELECT " . self::NEXT_ARTICLE_ID . ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
|
|
WHERE NOT EXISTS (SELECT 1 FROM article_redirects WHERE slug = ?)
|
|
AND NOT EXISTS (SELECT 1 FROM article_deletions WHERE slug = ?)");
|
|
$link = $pdo->prepare('INSERT INTO article_category_links (article_id, category_slug) VALUES (?, ?)');
|
|
foreach ($seed['articles'] as $item) {
|
|
$format = $item['body_format'] ?? 'markdown';
|
|
$date = $item['date'] ?? null;
|
|
$article->execute([
|
|
$item['slug'], $item['title'], $item['summary'] ?? '',
|
|
$format === 'html' ? Html::sanitize($item['body']) : $item['body'], $format,
|
|
self::json($item['card'] ?? []), self::json($item['tags'] ?? []),
|
|
$item['status'] ?? 'published', $date, $date ?? gmdate(DATE_ATOM), $item['legacy'] ?? null, $item['slug'], $item['slug'],
|
|
]);
|
|
if ($article->rowCount() === 1) {
|
|
$id = $pdo->lastInsertId();
|
|
foreach ($item['categories'] as $slug) {
|
|
$link->execute([$id, $slug]);
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|