<?php
declare(strict_types=1);

/**
 * 列出当前数据库中的 VIEW 及其 DEFINER，用于排查宝塔备份“缺少表 xxx__view_backup”。
 *
 * 用法（在 server 目录执行）：
 * php db/debug_list_views_and_definers.php
 */

require_once __DIR__ . '/../vendor/autoload.php';

if (class_exists(\Dotenv\Dotenv::class) && is_file(dirname(__DIR__) . '/.env')) {
    if (method_exists(\Dotenv\Dotenv::class, 'createUnsafeMutable')) {
        \Dotenv\Dotenv::createUnsafeMutable(dirname(__DIR__))->load();
    } else {
        \Dotenv\Dotenv::createMutable(dirname(__DIR__))->load();
    }
}

$host = getenv('DB_HOST') ?: '127.0.0.1';
$port = getenv('DB_PORT') ?: '3306';
$dbName = getenv('DB_NAME') ?: '';
$user = getenv('DB_USER') ?: '';
$pass = getenv('DB_PASSWORD') ?: '';

$dsn = "mysql:host={$host};port={$port};dbname={$dbName};charset=utf8mb4";
$pdo = new PDO($dsn, $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

$sql = "SELECT TABLE_NAME, DEFINER, SECURITY_TYPE
        FROM information_schema.VIEWS
        WHERE TABLE_SCHEMA = DATABASE()
        ORDER BY TABLE_NAME";

$rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
if (!$rows) {
    echo "No views found.\n";
    exit(0);
}

foreach ($rows as $row) {
    echo $row['TABLE_NAME'] . "\t" . ($row['DEFINER'] ?? '') . "\t" . ($row['SECURITY_TYPE'] ?? '') . "\n";
}

