38471-vm/db/migrations/20260503_ensure_entity_balance_columns.php
2026-05-03 01:46:41 +00:00

66 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/../config.php';
if (!function_exists('ensure_entity_balance_columns_20260503_run')) {
function ensure_entity_balance_columns_20260503_run(): void
{
$pdo = db();
$definitions = [
'customers' => [
'balance' => 'DECIMAL(15,3) DEFAULT 0.000',
'credit_limit' => 'DECIMAL(15,3) DEFAULT 0.000',
],
'suppliers' => [
'balance' => 'DECIMAL(15,3) DEFAULT NULL',
'credit_limit' => 'DECIMAL(15,3) DEFAULT NULL',
],
];
foreach ($definitions as $table => $columns) {
if (!ensure_entity_balance_columns_20260503_table_exists($pdo, $table)) {
continue;
}
foreach ($columns as $column => $definition) {
if (ensure_entity_balance_columns_20260503_column_exists($pdo, $table, $column)) {
continue;
}
$statement = sprintf(
'ALTER TABLE `%s` ADD COLUMN `%s` %s',
str_replace('`', '', $table),
str_replace('`', '', $column),
$definition
);
$pdo->exec($statement);
}
}
}
function ensure_entity_balance_columns_20260503_table_exists(PDO $pdo, string $table): bool
{
$stmt = $pdo->prepare(
'SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? LIMIT 1'
);
$stmt->execute([$table]);
return (bool) $stmt->fetchColumn();
}
function ensure_entity_balance_columns_20260503_column_exists(PDO $pdo, string $table, string $column): bool
{
$stmt = $pdo->prepare(
'SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ? LIMIT 1'
);
$stmt->execute([$table, $column]);
return (bool) $stmt->fetchColumn();
}
}
ensure_entity_balance_columns_20260503_run();