<?php
declare(strict_types=1);

/**
 * 列出当前数据库中所有 *__view_backup 对象，用于排查宝塔备份报错。
 *
 * 用法（在 server 目录执行）：
 * php db/debug_list_view_backup_objects.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, TABLE_TYPE
        FROM information_schema.TABLES
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME LIKE '%\\_\\_view\\_backup'
        ORDER BY TABLE_NAME";

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

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

