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)'); } if ($version < 5) { 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); } }