<?php
declare(strict_types=1);

/**
 * 查询指定表/视图的类型（BASE TABLE / VIEW）。
 *
 * 用法（在 server 目录执行）：
 * php db/debug_check_table_type.php bet_order_view
 */

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();
    }
}

$table = $argv[1] ?? '';
$table = trim((string) $table);
if ($table === '') {
    fwrite(STDERR, "Missing table name.\n");
    exit(1);
}

$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,
]);

$stmt = $pdo->prepare(
    "SELECT TABLE_NAME, TABLE_TYPE
     FROM information_schema.TABLES
     WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :name"
);
$stmt->execute(['name' => $table]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
    echo "NOT_FOUND\t{$table}\n";
    exit(0);
}

echo $row['TABLE_NAME'] . "\t" . $row['TABLE_TYPE'] . "\n";

