You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
88 lines
2.1 KiB
88 lines
2.1 KiB
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* @author Robert Strutts
|
|
* @copyright (c) 2026, Robert Strutts
|
|
* @license MIT
|
|
*/
|
|
|
|
namespace IOcornerstone\Framework\Database;
|
|
|
|
/**
|
|
* Description of BuildSQL
|
|
*
|
|
* @author Robert Strutts
|
|
*/
|
|
class BuildSQL
|
|
{
|
|
|
|
/**
|
|
* Generate CREATE TABLE SQL from an existing MySQL table.
|
|
*/
|
|
public function generateCreateTable(\PDO $pdo, string $table): string
|
|
{
|
|
$sql = "
|
|
SELECT
|
|
COLUMN_NAME,
|
|
COLUMN_TYPE,
|
|
IS_NULLABLE,
|
|
COLUMN_DEFAULT,
|
|
EXTRA,
|
|
COLUMN_KEY,
|
|
COLUMN_COMMENT
|
|
FROM INFORMATION_SCHEMA.COLUMNS
|
|
WHERE TABLE_SCHEMA = DATABASE()
|
|
AND TABLE_NAME = ?
|
|
ORDER BY ORDINAL_POSITION
|
|
";
|
|
|
|
$stmt = $pdo->prepare($sql);
|
|
$stmt->execute([$table]);
|
|
|
|
$columns = [];
|
|
$primary = [];
|
|
|
|
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
|
|
$line = '`' . $row['COLUMN_NAME'] . '` ' . $row['COLUMN_TYPE'];
|
|
|
|
if ($row['IS_NULLABLE'] === 'NO') {
|
|
$line .= ' NOT NULL';
|
|
}
|
|
|
|
if ($row['COLUMN_DEFAULT'] !== null) {
|
|
$default = $row['COLUMN_DEFAULT'];
|
|
|
|
if (strtoupper($default) === 'CURRENT_TIMESTAMP') {
|
|
$line .= ' DEFAULT CURRENT_TIMESTAMP';
|
|
} else {
|
|
$line .= ' DEFAULT ' . $pdo->quote($default);
|
|
}
|
|
}
|
|
|
|
if (!empty($row['EXTRA'])) {
|
|
$line .= ' ' . strtoupper($row['EXTRA']);
|
|
}
|
|
|
|
if (!empty($row['COLUMN_COMMENT'])) {
|
|
$line .= ' COMMENT ' . $pdo->quote($row['COLUMN_COMMENT']);
|
|
}
|
|
|
|
$columns[] = $line;
|
|
|
|
if ($row['COLUMN_KEY'] === 'PRI') {
|
|
$primary[] = '`' . $row['COLUMN_NAME'] . '`';
|
|
}
|
|
}
|
|
|
|
if (!empty($primary)) {
|
|
$columns[] = 'PRIMARY KEY (' . implode(', ', $primary) . ')';
|
|
}
|
|
|
|
return "CREATE TABLE IF NOT EXISTS `{$table}` (\n "
|
|
. implode(",\n ", $columns)
|
|
. "\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
|
|
}
|
|
|
|
}
|
|
|