packages/sql-fixture/src/Platform/MySql/Schema/CreateTableQuery.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlFixture\Platform\MySql\Schema;
6
7use PDO;
8use RuntimeException;
9
10/**
11 * Reads the database CREATE TABLE declaration.
12 *
13 * @visibility root
14 */
15final class CreateTableQuery
16{
17    /**
18     * Fetch the CREATE TABLE SQL from the database.
19     * @throws RuntimeException
20     */
21    public function fetchCreateTableSql(PDO $pdo, string $tableName): string
22    {
23        $quotedName = (new IdentifierQuoter())->quoteTableName($tableName);
24
25        $stmt = $pdo->query("SHOW CREATE TABLE {$quotedName}");
26        if ($stmt === false) {
27            throw new RuntimeException("Failed to get CREATE TABLE for: {$tableName}");
28        }
29
30        /**
31         * @var array{0: string, 1: string}|false $row
32         */
33        $row = $stmt->fetch(PDO::FETCH_NUM);
34        if ($row === false) {
35            throw new RuntimeException("Table not found: {$tableName}");
36        }
37
38        return $row[1];
39    }
40}
41