- Replace "BetZoo CRM" with "MoneyFlix" in Advertising module description - Replace "Betzoo" option with "MoneyFlix" in ErrorMonitoring project filter - Update GoogleSheetsService to use environment variable for credentials path - Update CDN config from betzoo.app to moneyflix.com - Remove WDMI-specific checks in layouts (topbar, sidebar, main, public-blank) - Update database profile examples from wdmi_importer to moneyflix_importer - Keep BitReport references (company/product name)
1094 lines
38 KiB
PHP
1094 lines
38 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Core\Database;
|
|
|
|
use App\Core\DatabaseManager;
|
|
use App\Core\ErrorReporter;
|
|
use App\Core\Logger;
|
|
|
|
abstract class Migration
|
|
{
|
|
protected DatabaseManager $db;
|
|
protected SchemaBuilder $schema;
|
|
protected array $pendingForeignKeys = [];
|
|
protected Logger $logger;
|
|
protected string $connectionProfile = 'crm'; // Default connection profile
|
|
|
|
/**
|
|
* The name of the database connection to use.
|
|
* Laravel-style property for connection specification
|
|
*
|
|
* @var string|null
|
|
*/
|
|
protected ?string $connection = null;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->db = DatabaseManager::getInstance();
|
|
$this->schema = new SchemaBuilder();
|
|
$this->logger = new Logger();
|
|
|
|
// Apply connection profile if specified (Laravel-style)
|
|
if ($this->connection !== null) {
|
|
$this->setConnectionProfile($this->connection);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Set the connection profile for this migration
|
|
* Available profiles: 'crm', 'moneyflix_importer', 'legacy'
|
|
*/
|
|
protected function setConnectionProfile(string $profile): void
|
|
{
|
|
$this->connectionProfile = $profile;
|
|
$this->db->connectionProfile($profile);
|
|
$this->schema = new SchemaBuilder();
|
|
$this->logger->info("🔗 Migration using connection profile: $profile");
|
|
}
|
|
|
|
/**
|
|
* Get the current connection profile
|
|
*/
|
|
protected function getConnectionProfile(): string
|
|
{
|
|
return $this->connectionProfile;
|
|
}
|
|
|
|
/**
|
|
* Run the migration
|
|
*/
|
|
public function run(): bool
|
|
{
|
|
try {
|
|
$this->up();
|
|
|
|
// Process pending foreign keys after all tables are created
|
|
$this->processPendingForeignKeys();
|
|
|
|
return true;
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'migration_run', 'class' => static::class]);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Rollback the migration
|
|
*/
|
|
public function rollback(): bool
|
|
{
|
|
try {
|
|
$this->down();
|
|
return true;
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'migration_rollback', 'class' => static::class]);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get migration name from class name
|
|
*/
|
|
public function getName(): string
|
|
{
|
|
$className = static::class;
|
|
$parts = explode('\\', $className);
|
|
return end($parts);
|
|
}
|
|
|
|
/**
|
|
* Get migration timestamp from filename
|
|
*/
|
|
public function getTimestamp(): string
|
|
{
|
|
$className = static::class;
|
|
$parts = explode('\\', $className);
|
|
$filename = end($parts);
|
|
|
|
// Extract timestamp from filename like: 2025_07_21_000001_create_table
|
|
if (preg_match('/^(\d{4}_\d{2}_\d{2}_\d{6})_/', $filename, $matches)) {
|
|
return $matches[1];
|
|
}
|
|
|
|
return date('Y_m_d_His');
|
|
}
|
|
|
|
/**
|
|
* Check if migration has been applied
|
|
*/
|
|
public function isApplied(): bool
|
|
{
|
|
try {
|
|
$result = $this->db->fetch(
|
|
"SELECT COUNT(*) as count FROM migrations WHERE migration = ?",
|
|
[$this->getName()]
|
|
);
|
|
return ($result['count'] ?? 0) > 0;
|
|
} catch (\Exception $e) {
|
|
// Migrations table doesn't exist yet
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Mark migration as applied
|
|
*/
|
|
public function markAsApplied(): void
|
|
{
|
|
try {
|
|
// VERIFICAÇÃO RIGOROSA: Só marca como aplicada se a estrutura estiver correta
|
|
if (!$this->validateMigrationStructure()) {
|
|
throw new \Exception("Migration structure validation failed - cannot mark as applied");
|
|
}
|
|
|
|
$this->createMigrationsTable();
|
|
|
|
$batch = $this->getBatch();
|
|
$this->db->query(
|
|
"INSERT INTO migrations (migration, batch, executed_at) VALUES (?, ?, NOW())",
|
|
[$this->getName(), $batch]
|
|
);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'migration_mark_as_applied', 'class' => static::class]);
|
|
throw $e;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Mark migration as rolled back
|
|
*/
|
|
public function markAsRolledBack(): void
|
|
{
|
|
$this->db->query(
|
|
"DELETE FROM migrations WHERE migration = ?",
|
|
[$this->getName()]
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Get current batch number
|
|
*/
|
|
private function getBatch(): int
|
|
{
|
|
try {
|
|
$result = $this->db->fetch("SELECT MAX(batch) as max_batch FROM migrations");
|
|
return ($result['max_batch'] ?? 0) + 1;
|
|
} catch (\Exception $e) {
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Create migrations table if it doesn't exist
|
|
*/
|
|
private function createMigrationsTable(): void
|
|
{
|
|
$this->schema->table('migrations')
|
|
->bigInteger('id')->autoIncrement()->notNull()
|
|
->string('migration', 255)->notNull()
|
|
->integer('batch')->notNull()
|
|
->timestamp('executed_at')->notNull()
|
|
->primaryKey('id')
|
|
->index('migration')
|
|
->index('batch')
|
|
->apply();
|
|
}
|
|
|
|
/**
|
|
* Execute raw SQL query
|
|
*/
|
|
protected function query(string $sql, array $params = []): void
|
|
{
|
|
$this->db->query($sql, $params);
|
|
}
|
|
|
|
/**
|
|
* Execute raw SQL and return results
|
|
*/
|
|
protected function fetch(string $sql, array $params = []): ?array
|
|
{
|
|
return $this->db->fetch($sql, $params);
|
|
}
|
|
|
|
/**
|
|
* Execute raw SQL and return all results
|
|
*/
|
|
protected function fetchAll(string $sql, array $params = []): array
|
|
{
|
|
return $this->db->fetchAll($sql, $params);
|
|
}
|
|
|
|
/**
|
|
* Create a new table using the schema builder
|
|
*/
|
|
protected function createTable(string $tableName, callable $callback): void
|
|
{
|
|
try {
|
|
$table = $this->schema->table($tableName);
|
|
$callback($table);
|
|
$table->apply();
|
|
} catch (\Exception $e) {
|
|
// If table creation fails, try to drop and recreate
|
|
$this->handleTableCreationError($tableName, $callback, $e);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handle table creation errors intelligently
|
|
*/
|
|
private function handleTableCreationError(string $tableName, callable $callback, \Exception $originalError): void
|
|
{
|
|
try {
|
|
// Check if table exists but with different structure
|
|
if ($this->schema->tableExists($tableName)) {
|
|
// Drop table and recreate
|
|
$this->db->query("DROP TABLE IF EXISTS `$tableName`");
|
|
error_log("Dropped existing table $tableName due to structure mismatch");
|
|
}
|
|
|
|
// Try to create table again
|
|
$table = $this->schema->table($tableName);
|
|
$callback($table);
|
|
$table->apply();
|
|
|
|
} catch (\Exception $e) {
|
|
// If still fails, throw the original error
|
|
throw $originalError;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Drop a table
|
|
*/
|
|
protected function dropTable(string $tableName): void
|
|
{
|
|
$this->db->query("DROP TABLE IF EXISTS `$tableName`");
|
|
}
|
|
|
|
/**
|
|
* Add a column to existing table
|
|
*/
|
|
protected function addColumn(string $tableName, string $columnName, callable $callback): void
|
|
{
|
|
$table = $this->schema->table($tableName);
|
|
$callback($table);
|
|
$columnDef = $table->getColumns()[$columnName] ?? null;
|
|
|
|
if ($columnDef) {
|
|
$this->schema->addColumn($tableName, $columnName, $columnDef);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Modify an existing column
|
|
*/
|
|
protected function modifyColumn(string $tableName, string $columnName, callable $callback): void
|
|
{
|
|
try {
|
|
$table = $this->schema->table($tableName);
|
|
$callback($table);
|
|
$columnDef = $table->getColumns()[$columnName] ?? null;
|
|
|
|
if ($columnDef) {
|
|
$this->schema->modifyColumn($tableName, $columnName, $columnDef);
|
|
}
|
|
} catch (\Exception $e) {
|
|
// If modification fails, try to recreate the column
|
|
$this->handleColumnModificationError($tableName, $columnName, $callback, $e);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handle column modification errors intelligently
|
|
*/
|
|
private function handleColumnModificationError(string $tableName, string $columnName, callable $callback, \Exception $originalError): void
|
|
{
|
|
try {
|
|
// Get current column definition
|
|
$currentDef = $this->getColumnDefinition($tableName, $columnName);
|
|
if (!$currentDef) {
|
|
throw $originalError; // Column doesn't exist
|
|
}
|
|
|
|
// Create new column definition
|
|
$table = $this->schema->table($tableName);
|
|
$callback($table);
|
|
$newColumnDef = $table->getColumns()[$columnName] ?? null;
|
|
|
|
if (!$newColumnDef) {
|
|
throw $originalError;
|
|
}
|
|
|
|
// Create temporary column with new definition
|
|
$tempColumn = $columnName . '_temp_' . time();
|
|
$tempDef = $this->buildColumnDefinition($tempColumn, $newColumnDef);
|
|
$sql = "ALTER TABLE `$tableName` ADD COLUMN $tempDef";
|
|
$this->db->query($sql);
|
|
|
|
// Copy data
|
|
try {
|
|
$sql = "UPDATE `$tableName` SET `$tempColumn` = `$columnName`";
|
|
$this->db->query($sql);
|
|
} catch (\Exception $e) {
|
|
// If copy fails, set to NULL
|
|
$sql = "UPDATE `$tableName` SET `$tempColumn` = NULL";
|
|
$this->db->query($sql);
|
|
}
|
|
|
|
// Drop old column and rename new one
|
|
$sql = "ALTER TABLE `$tableName` DROP COLUMN `$columnName`";
|
|
$this->db->query($sql);
|
|
|
|
$sql = "ALTER TABLE `$tableName` CHANGE `$tempColumn` `$columnName` " . $this->buildColumnDefinitionWithoutName($newColumnDef);
|
|
$this->db->query($sql);
|
|
|
|
} catch (\Exception $e) {
|
|
throw $originalError;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Drop a column from table
|
|
*/
|
|
protected function dropColumn(string $tableName, string $columnName): void
|
|
{
|
|
$this->schema->dropColumn($tableName, $columnName);
|
|
}
|
|
|
|
/**
|
|
* Add an index to table
|
|
*/
|
|
protected function addIndex(string $tableName, string $indexName, array $columns, string $type = 'INDEX'): void
|
|
{
|
|
$columnsList = implode(', ', array_map(fn($col) => "`$col`", $columns));
|
|
$sql = "ALTER TABLE `$tableName` ADD $type `$indexName` ($columnsList)";
|
|
$this->db->query($sql);
|
|
}
|
|
|
|
/**
|
|
* Drop an index from table
|
|
*/
|
|
protected function dropIndex(string $tableName, string $indexName): void
|
|
{
|
|
$sql = "ALTER TABLE `$tableName` DROP INDEX `$indexName`";
|
|
$this->db->query($sql);
|
|
}
|
|
|
|
/**
|
|
* Add a foreign key constraint with intelligent handling
|
|
*/
|
|
protected function addForeignKey(string $tableName, string $column, string $referencedTable, string $referencedColumn, string $onDelete = 'CASCADE', string $onUpdate = 'CASCADE'): void
|
|
{
|
|
$constraintName = "fk_{$tableName}_{$column}";
|
|
|
|
// Verificar se a foreign key já existe
|
|
if ($this->foreignKeyExists($tableName, $column, $referencedTable)) {
|
|
return;
|
|
}
|
|
|
|
// Verificar se as tabelas existem - se não existirem, adicionar à fila para depois
|
|
if (!$this->schema->tableExists($tableName) || !$this->schema->tableExists($referencedTable)) {
|
|
$this->queueForeignKey($tableName, $column, $referencedTable, $referencedColumn, $onDelete, $onUpdate);
|
|
return;
|
|
}
|
|
|
|
// Garantir que a coluna referenciada tem índice (obrigatório para foreign keys)
|
|
$this->ensureReferencedColumnHasIndex($referencedTable, $referencedColumn);
|
|
|
|
// Verificar e corrigir tipos de colunas automaticamente
|
|
$this->ensureCompatibleColumnTypes($tableName, $column, $referencedTable, $referencedColumn);
|
|
|
|
// Verificar se há dados órfãos
|
|
$this->checkOrphanedRecords($tableName, $column, $referencedTable, $referencedColumn);
|
|
|
|
// Criar a foreign key
|
|
$sql = "ALTER TABLE `$tableName` ADD CONSTRAINT `$constraintName` FOREIGN KEY (`$column`) REFERENCES `$referencedTable`(`$referencedColumn`) ON DELETE $onDelete ON UPDATE $onUpdate";
|
|
$this->db->query($sql);
|
|
}
|
|
|
|
/**
|
|
* Queue foreign key for later creation when all tables exist
|
|
*/
|
|
private function queueForeignKey(string $tableName, string $column, string $referencedTable, string $referencedColumn, string $onDelete, string $onUpdate): void
|
|
{
|
|
if (!isset($this->pendingForeignKeys)) {
|
|
$this->pendingForeignKeys = [];
|
|
}
|
|
|
|
$this->pendingForeignKeys[] = [
|
|
'table' => $tableName,
|
|
'column' => $column,
|
|
'referenced_table' => $referencedTable,
|
|
'referenced_column' => $referencedColumn,
|
|
'on_delete' => $onDelete,
|
|
'on_update' => $onUpdate
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Process all pending foreign keys after all tables are created
|
|
*/
|
|
protected function processPendingForeignKeys(): void
|
|
{
|
|
if (!isset($this->pendingForeignKeys) || empty($this->pendingForeignKeys)) {
|
|
return;
|
|
}
|
|
|
|
// Sort by dependency order (tables that depend on others come later)
|
|
$this->sortForeignKeysByDependency();
|
|
|
|
foreach ($this->pendingForeignKeys as $fk) {
|
|
try {
|
|
$this->addForeignKey(
|
|
$fk['table'],
|
|
$fk['column'],
|
|
$fk['referenced_table'],
|
|
$fk['referenced_column'],
|
|
$fk['on_delete'],
|
|
$fk['on_update']
|
|
);
|
|
} catch (\Exception $e) {
|
|
// Log error but continue with other foreign keys
|
|
error_log("Failed to create foreign key {$fk['table']}.{$fk['column']} -> {$fk['referenced_table']}.{$fk['referenced_column']}: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
// Clear the queue
|
|
$this->pendingForeignKeys = [];
|
|
}
|
|
|
|
/**
|
|
* Sort foreign keys by dependency order to avoid circular references
|
|
*/
|
|
private function sortForeignKeysByDependency(): void
|
|
{
|
|
// Simple topological sort - tables with fewer dependencies come first
|
|
usort($this->pendingForeignKeys, function($a, $b) {
|
|
$aDeps = $this->countTableDependencies($a['table']);
|
|
$bDeps = $this->countTableDependencies($b['table']);
|
|
return $aDeps - $bDeps;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Count how many foreign keys depend on a table
|
|
*/
|
|
private function countTableDependencies(string $tableName): int
|
|
{
|
|
$count = 0;
|
|
foreach ($this->pendingForeignKeys as $fk) {
|
|
if ($fk['referenced_table'] === $tableName) {
|
|
$count++;
|
|
}
|
|
}
|
|
return $count;
|
|
}
|
|
|
|
/**
|
|
* Verificar se foreign key já existe
|
|
*/
|
|
private function foreignKeyExists(string $tableName, string $column, string $referencedTable): bool
|
|
{
|
|
$exists = $this->db->fetch("
|
|
SELECT COUNT(*) as count
|
|
FROM information_schema.KEY_COLUMN_USAGE
|
|
WHERE TABLE_SCHEMA = DATABASE()
|
|
AND TABLE_NAME = ?
|
|
AND COLUMN_NAME = ?
|
|
AND REFERENCED_TABLE_NAME = ?
|
|
", [$tableName, $column, $referencedTable]);
|
|
|
|
return ($exists['count'] ?? 0) > 0;
|
|
}
|
|
|
|
/**
|
|
* Ensure compatible column types for foreign keys with automatic correction
|
|
*/
|
|
private function ensureCompatibleColumnTypes(string $tableName, string $column, string $referencedTable, string $referencedColumn): void
|
|
{
|
|
try {
|
|
// Get current column definitions
|
|
$currentColumn = $this->getColumnDefinition($tableName, $column);
|
|
$referencedColumnDef = $this->getColumnDefinition($referencedTable, $referencedColumn);
|
|
|
|
if (!$currentColumn || !$referencedColumnDef) {
|
|
return; // Columns don't exist, skip
|
|
}
|
|
|
|
// Check if types are compatible
|
|
if ($this->areColumnTypesCompatible($currentColumn['type'], $referencedColumnDef['type'])) {
|
|
return; // Types are already compatible
|
|
}
|
|
|
|
// Auto-correct column type to match referenced column
|
|
$this->autoCorrectColumnType($tableName, $column, $referencedColumnDef['type']);
|
|
|
|
} catch (\Exception $e) {
|
|
// Log error but don't fail the migration
|
|
error_log("Warning: Could not ensure compatible column types for {$tableName}.{$column}: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get column definition from database
|
|
*/
|
|
private function getColumnDefinition(string $tableName, string $columnName): ?array
|
|
{
|
|
try {
|
|
$result = $this->db->fetch(
|
|
"SELECT COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, EXTRA
|
|
FROM information_schema.COLUMNS
|
|
WHERE TABLE_SCHEMA = DATABASE()
|
|
AND TABLE_NAME = ? AND COLUMN_NAME = ?",
|
|
[$tableName, $columnName]
|
|
);
|
|
|
|
if (!$result) {
|
|
return null;
|
|
}
|
|
|
|
return [
|
|
'type' => $result['COLUMN_TYPE'],
|
|
'null' => $result['IS_NULLABLE'] === 'YES',
|
|
'default' => $result['COLUMN_DEFAULT'],
|
|
'extra' => $result['EXTRA']
|
|
];
|
|
} catch (\Exception $e) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check if two column types are compatible for foreign keys
|
|
*/
|
|
private function areColumnTypesCompatible(string $type1, string $type2): bool
|
|
{
|
|
// Normalize types for comparison
|
|
$type1 = strtoupper(preg_replace('/\s+/', ' ', trim($type1)));
|
|
$type2 = strtoupper(preg_replace('/\s+/', ' ', trim($type2)));
|
|
|
|
// Exact match
|
|
if ($type1 === $type2) {
|
|
return true;
|
|
}
|
|
|
|
// Check for common compatible patterns
|
|
$compatiblePatterns = [
|
|
['BIGINT', 'BIGINT UNSIGNED'],
|
|
['BIGINT UNSIGNED', 'BIGINT'],
|
|
['INT', 'INT UNSIGNED'],
|
|
['INT UNSIGNED', 'INT'],
|
|
['VARCHAR(255)', 'VARCHAR(100)'],
|
|
['VARCHAR(100)', 'VARCHAR(255)']
|
|
];
|
|
|
|
foreach ($compatiblePatterns as $pattern) {
|
|
if (($type1 === $pattern[0] && $type2 === $pattern[1]) ||
|
|
($type1 === $pattern[1] && $type2 === $pattern[0])) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Auto-correct column type to match referenced column
|
|
*/
|
|
private function autoCorrectColumnType(string $tableName, string $columnName, string $targetType): void
|
|
{
|
|
try {
|
|
$sql = "ALTER TABLE `$tableName` MODIFY COLUMN `$columnName` $targetType";
|
|
$this->db->query($sql);
|
|
} catch (\Exception $e) {
|
|
// If modification fails, try to drop and recreate the column
|
|
$this->recreateColumnWithCorrectType($tableName, $columnName, $targetType);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Recreate column with correct type (fallback method)
|
|
*/
|
|
private function recreateColumnWithCorrectType(string $tableName, string $columnName, string $targetType): void
|
|
{
|
|
try {
|
|
// Get current column definition
|
|
$currentDef = $this->getColumnDefinition($tableName, $columnName);
|
|
if (!$currentDef) {
|
|
return;
|
|
}
|
|
|
|
// Create temporary column
|
|
$tempColumn = $columnName . '_temp_' . time();
|
|
$sql = "ALTER TABLE `$tableName` ADD COLUMN `$tempColumn` $targetType";
|
|
$this->db->query($sql);
|
|
|
|
// Copy data if possible
|
|
try {
|
|
$sql = "UPDATE `$tableName` SET `$tempColumn` = CAST(`$columnName` AS $targetType)";
|
|
$this->db->query($sql);
|
|
} catch (\Exception $e) {
|
|
// If cast fails, set to NULL or default
|
|
$sql = "UPDATE `$tableName` SET `$tempColumn` = NULL";
|
|
$this->db->query($sql);
|
|
}
|
|
|
|
// Drop old column and rename new one
|
|
$sql = "ALTER TABLE `$tableName` DROP COLUMN `$columnName`";
|
|
$this->db->query($sql);
|
|
|
|
$sql = "ALTER TABLE `$tableName` CHANGE `$tempColumn` `$columnName` $targetType";
|
|
$this->db->query($sql);
|
|
|
|
} catch (\Exception $e) {
|
|
error_log("Failed to recreate column {$tableName}.{$columnName}: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Verificar se há registos órfãos que impedem a criação da foreign key
|
|
*/
|
|
private function checkOrphanedRecords(string $tableName, string $column, string $referencedTable, string $referencedColumn): void
|
|
{
|
|
try {
|
|
// Check for orphaned records
|
|
$sql = "SELECT COUNT(*) as count FROM `$tableName` t1
|
|
LEFT JOIN `$referencedTable` t2 ON t1.`$column` = t2.`$referencedColumn`
|
|
WHERE t2.`$referencedColumn` IS NULL AND t1.`$column` IS NOT NULL";
|
|
|
|
$result = $this->db->fetch($sql);
|
|
$orphanedCount = $result['count'] ?? 0;
|
|
|
|
if ($orphanedCount > 0) {
|
|
// Auto-fix: Set orphaned records to NULL
|
|
$sql = "UPDATE `$tableName` t1
|
|
LEFT JOIN `$referencedTable` t2 ON t1.`$column` = t2.`$referencedColumn`
|
|
SET t1.`$column` = NULL
|
|
WHERE t2.`$referencedColumn` IS NULL AND t1.`$column` IS NOT NULL";
|
|
$this->db->query($sql);
|
|
|
|
error_log("Auto-fixed $orphanedCount orphaned records in {$tableName}.{$column}");
|
|
}
|
|
|
|
} catch (\Exception $e) {
|
|
error_log("Warning: Could not check orphaned records for {$tableName}.{$column}: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Ensure referenced column has index (required for foreign keys)
|
|
*/
|
|
private function ensureReferencedColumnHasIndex(string $tableName, string $columnName): void
|
|
{
|
|
try {
|
|
// Check if column already has an index
|
|
$sql = "SELECT COUNT(*) as count FROM information_schema.STATISTICS
|
|
WHERE TABLE_SCHEMA = DATABASE()
|
|
AND TABLE_NAME = ? AND COLUMN_NAME = ?";
|
|
|
|
$result = $this->db->fetch($sql, [$tableName, $columnName]);
|
|
$hasIndex = ($result['count'] ?? 0) > 0;
|
|
|
|
if (!$hasIndex) {
|
|
// Create index automatically
|
|
$indexName = "idx_{$tableName}_{$columnName}";
|
|
$sql = "ALTER TABLE `$tableName` ADD INDEX `$indexName` (`$columnName`)";
|
|
$this->db->query($sql);
|
|
|
|
error_log("Auto-created index {$indexName} for {$tableName}.{$columnName}");
|
|
}
|
|
|
|
} catch (\Exception $e) {
|
|
error_log("Warning: Could not ensure index for {$tableName}.{$columnName}: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Drop a foreign key constraint
|
|
*/
|
|
protected function dropForeignKey(string $tableName, string $constraintName): void
|
|
{
|
|
$sql = "ALTER TABLE `$tableName` DROP FOREIGN KEY `$constraintName`";
|
|
$this->db->query($sql);
|
|
}
|
|
|
|
/**
|
|
* Rename a table
|
|
*/
|
|
protected function renameTable(string $oldName, string $newName): void
|
|
{
|
|
$sql = "RENAME TABLE `$oldName` TO `$newName`";
|
|
$this->db->query($sql);
|
|
}
|
|
|
|
/**
|
|
* Rename a column
|
|
*/
|
|
protected function renameColumn(string $tableName, string $oldName, string $newName): void
|
|
{
|
|
// Get current column definition
|
|
$current = $this->schema->getCurrentStructure($tableName)[$oldName] ?? null;
|
|
if (!$current) {
|
|
throw new \Exception("Column $oldName not found in table $tableName");
|
|
}
|
|
|
|
// Drop old column and add new one
|
|
$this->dropColumn($tableName, $oldName);
|
|
$this->addColumn($tableName, $newName, function($table) use ($current) {
|
|
// Recreate the column with new name but same definition
|
|
$this->recreateColumnDefinition($table, $current);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Recreate column definition from current structure
|
|
*/
|
|
private function recreateColumnDefinition($table, array $columnDef): void
|
|
{
|
|
// This is a simplified version - in practice you'd need to parse the type
|
|
// and recreate the appropriate column definition
|
|
$type = $columnDef['type'];
|
|
|
|
if (strpos($type, 'int') !== false) {
|
|
$table->integer('temp')->notNull();
|
|
} elseif (strpos($type, 'varchar') !== false) {
|
|
preg_match('/varchar\((\d+)\)/', $type, $matches);
|
|
$length = $matches[1] ?? 255;
|
|
$table->string('temp', (int)$length);
|
|
} elseif (strpos($type, 'text') !== false) {
|
|
$table->text('temp');
|
|
} elseif (strpos($type, 'timestamp') !== false) {
|
|
$table->timestamp('temp');
|
|
} elseif (strpos($type, 'decimal') !== false) {
|
|
preg_match('/decimal\((\d+),(\d+)\)/', $type, $matches);
|
|
$precision = $matches[1] ?? 10;
|
|
$scale = $matches[2] ?? 2;
|
|
$table->decimal('temp', (int)$precision, (int)$scale);
|
|
} elseif (strpos($type, 'enum') !== false) {
|
|
preg_match('/enum\((.*)\)/', $type, $matches);
|
|
$values = array_map('trim', explode(',', str_replace("'", '', $matches[1] ?? '')));
|
|
$table->enum('temp', $values);
|
|
} elseif (strpos($type, 'json') !== false) {
|
|
$table->json('temp');
|
|
}
|
|
|
|
if (!$columnDef['null']) {
|
|
$table->notNull();
|
|
}
|
|
|
|
if ($columnDef['default'] !== null) {
|
|
$table->default($columnDef['default']);
|
|
}
|
|
|
|
if (strpos($columnDef['extra'], 'AUTO_INCREMENT') !== false) {
|
|
$table->autoIncrement();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Abstract methods that must be implemented by migrations
|
|
*/
|
|
abstract public function up(): void;
|
|
abstract public function down(): void;
|
|
|
|
/**
|
|
* Create a trigger
|
|
*/
|
|
protected function createTrigger(string $triggerName, string $tableName, string $timing, string $event, string $body): void
|
|
{
|
|
$this->schema->createTrigger($triggerName, $tableName, $timing, $event, $body);
|
|
}
|
|
|
|
/**
|
|
* Drop a trigger
|
|
*/
|
|
protected function dropTrigger(string $triggerName): void
|
|
{
|
|
$this->schema->dropTrigger($triggerName);
|
|
}
|
|
|
|
/**
|
|
* Check if trigger exists
|
|
*/
|
|
protected function triggerExists(string $triggerName): bool
|
|
{
|
|
return $this->schema->triggerExists($triggerName);
|
|
}
|
|
|
|
/**
|
|
* Get triggers for a table
|
|
*/
|
|
protected function getTableTriggers(string $tableName): array
|
|
{
|
|
return $this->schema->getTableTriggers($tableName);
|
|
}
|
|
|
|
/**
|
|
* Build column definition for SQL
|
|
*/
|
|
private function buildColumnDefinition(string $columnName, array $columnDef): string
|
|
{
|
|
$sql = "`$columnName` " . $columnDef['type'];
|
|
|
|
if (!$columnDef['null']) {
|
|
$sql .= ' NOT NULL';
|
|
}
|
|
|
|
if ($columnDef['default'] !== null) {
|
|
if (is_string($columnDef['default'])) {
|
|
$sql .= " DEFAULT '" . addslashes($columnDef['default']) . "'";
|
|
} else {
|
|
$sql .= " DEFAULT " . $columnDef['default'];
|
|
}
|
|
}
|
|
|
|
if ($columnDef['extra']) {
|
|
$sql .= ' ' . $columnDef['extra'];
|
|
}
|
|
|
|
return $sql;
|
|
}
|
|
|
|
/**
|
|
* Build column definition without column name
|
|
*/
|
|
private function buildColumnDefinitionWithoutName(array $columnDef): string
|
|
{
|
|
$sql = $columnDef['type'];
|
|
|
|
if (!$columnDef['null']) {
|
|
$sql .= ' NOT NULL';
|
|
}
|
|
|
|
if ($columnDef['default'] !== null) {
|
|
if (is_string($columnDef['default'])) {
|
|
$sql .= " DEFAULT '" . addslashes($columnDef['default']) . "'";
|
|
} else {
|
|
$sql .= " DEFAULT " . $columnDef['default'];
|
|
}
|
|
}
|
|
|
|
if ($columnDef['extra']) {
|
|
$sql .= ' ' . $columnDef['extra'];
|
|
}
|
|
|
|
return $sql;
|
|
}
|
|
|
|
/**
|
|
* VALIDAÇÃO RIGOROSA: Verifica se a estrutura da tabela está exatamente igual à definida
|
|
* Só marca como aplicada se cada tabela e cada coluna estiverem corretas
|
|
*/
|
|
protected function validateMigrationStructure(): bool
|
|
{
|
|
try {
|
|
$this->logger->info("🔍 VALIDAÇÃO RIGOROSA: Verificando estrutura da migration " . $this->getName());
|
|
|
|
// Obter todas as tabelas definidas nesta migration
|
|
$definedTables = $this->getDefinedTables();
|
|
|
|
if (empty($definedTables)) {
|
|
$this->logger->warning("⚠️ Migration " . $this->getName() . " não define tabelas - marcando como aplicada");
|
|
return true;
|
|
}
|
|
|
|
foreach ($definedTables as $tableName => $tableDefinition) {
|
|
$this->logger->info("🔍 Verificando tabela: $tableName");
|
|
|
|
// 1. Verificar se a tabela existe
|
|
if (!$this->schema->tableExists($tableName)) {
|
|
$this->logger->error("❌ Tabela $tableName não existe - migration não pode ser marcada como aplicada");
|
|
return false;
|
|
}
|
|
|
|
// 2. Verificar cada coluna
|
|
$currentStructure = $this->schema->getCurrentStructure($tableName);
|
|
$desiredColumns = $tableDefinition['columns'] ?? [];
|
|
|
|
// Se a estrutura atual está vazia, a tabela não existe
|
|
if (empty($currentStructure)) {
|
|
$this->logger->error("❌ Tabela $tableName não existe - estrutura vazia");
|
|
return false;
|
|
}
|
|
|
|
foreach ($desiredColumns as $columnName => $desiredColumn) {
|
|
if (!isset($currentStructure[$columnName])) {
|
|
$this->logger->error("❌ Coluna $columnName não existe na tabela $tableName");
|
|
return false;
|
|
}
|
|
|
|
$currentColumn = $currentStructure[$columnName];
|
|
|
|
// Verificar tipo (com normalização)
|
|
$currentType = $this->normalizeType($currentColumn['type']);
|
|
$desiredType = $this->normalizeType($desiredColumn['type']);
|
|
if ($currentType !== $desiredType) {
|
|
$this->logger->error("❌ Tipo da coluna $columnName difere: atual='{$currentColumn['type']}' (normalizado: '$currentType'), desejado='{$desiredColumn['type']}' (normalizado: '$desiredType')");
|
|
return false;
|
|
}
|
|
|
|
// Verificar nullable
|
|
$currentNull = $currentColumn['null'] === true;
|
|
$desiredNull = $desiredColumn['null'];
|
|
if ($currentNull !== $desiredNull) {
|
|
$this->logger->error("❌ Nullable da coluna $columnName difere: atual=" . ($currentNull ? 'true' : 'false') . ", desejado=" . ($desiredNull ? 'true' : 'false'));
|
|
return false;
|
|
}
|
|
|
|
// Verificar default (com normalização)
|
|
$currentDefault = $this->normalizeDefault($currentColumn['default']);
|
|
$desiredDefault = $this->normalizeDefault($desiredColumn['default']);
|
|
if ($currentDefault !== $desiredDefault) {
|
|
$this->logger->error("❌ Default da coluna $columnName difere: atual='{$currentColumn['default']}' (normalizado: '$currentDefault'), desejado='{$desiredColumn['default']}' (normalizado: '$desiredDefault')");
|
|
return false;
|
|
}
|
|
|
|
// Verificar extra (auto_increment, etc)
|
|
if ($currentColumn['extra'] !== $desiredColumn['extra']) {
|
|
$this->logger->error("❌ Extra da coluna $columnName difere: atual='{$currentColumn['extra']}', desejado='{$desiredColumn['extra']}'");
|
|
return false;
|
|
}
|
|
|
|
$this->logger->info("✅ Coluna $columnName está correta");
|
|
}
|
|
|
|
// 3. Verificar índices
|
|
$desiredIndexes = $tableDefinition['indexes'] ?? [];
|
|
foreach ($desiredIndexes as $indexDef) {
|
|
if (preg_match('/`([^`]+)`/', $indexDef, $matches)) {
|
|
$indexName = $matches[1];
|
|
|
|
// Verificar se é PRIMARY KEY
|
|
if (stripos($indexDef, 'PRIMARY KEY') !== false) {
|
|
$exists = $this->db->fetch("
|
|
SELECT COUNT(*) as count
|
|
FROM information_schema.KEY_COLUMN_USAGE
|
|
WHERE TABLE_SCHEMA = DATABASE()
|
|
AND TABLE_NAME = ?
|
|
AND CONSTRAINT_NAME = 'PRIMARY'
|
|
", [$tableName]);
|
|
|
|
if (($exists['count'] ?? 0) === 0) {
|
|
$this->logger->error("❌ PRIMARY KEY não existe na tabela $tableName");
|
|
return false;
|
|
}
|
|
|
|
$this->logger->info("✅ PRIMARY KEY está correto");
|
|
} else {
|
|
// Verificar outros índices
|
|
$exists = $this->db->fetch("
|
|
SELECT COUNT(*) as count
|
|
FROM information_schema.STATISTICS
|
|
WHERE TABLE_SCHEMA = DATABASE()
|
|
AND TABLE_NAME = ?
|
|
AND INDEX_NAME = ?
|
|
", [$tableName, $indexName]);
|
|
|
|
if (($exists['count'] ?? 0) === 0) {
|
|
$this->logger->error("❌ Índice $indexName não existe na tabela $tableName");
|
|
return false;
|
|
}
|
|
|
|
$this->logger->info("✅ Índice $indexName está correto");
|
|
}
|
|
}
|
|
}
|
|
|
|
$this->logger->info("✅ Tabela $tableName está completamente correta");
|
|
}
|
|
|
|
$this->logger->info("✅ VALIDAÇÃO RIGOROSA PASSOU: Migration " . $this->getName() . " pode ser marcada como aplicada");
|
|
return true;
|
|
|
|
} catch (\Exception $e) {
|
|
$this->logger->error("❌ Erro na validação rigorosa: " . $e->getMessage());
|
|
ErrorReporter::report($e, ['context' => 'migration_validation', 'class' => static::class]);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter todas as tabelas definidas nesta migration
|
|
* Por padrão, usa o SchemaBuilder para obter a estrutura definida
|
|
*/
|
|
protected function getDefinedTables(): array
|
|
{
|
|
// Por padrão, retorna vazio - as migrations podem sobrescrever se necessário
|
|
return [];
|
|
}
|
|
|
|
/**
|
|
* Obtém a estrutura definida pelo SchemaBuilder para uma tabela específica
|
|
* Usa o TableBuilder para obter columns e indexes definidos
|
|
*/
|
|
protected function getSchemaBuilderStructure(string $tableName): array
|
|
{
|
|
// Recriar o TableBuilder para obter a estrutura definida
|
|
$tableBuilder = $this->schema->table($tableName);
|
|
|
|
// Simular a definição da tabela (sem aplicar)
|
|
$this->defineTableStructure($tableName, $tableBuilder);
|
|
|
|
return [
|
|
'columns' => $tableBuilder->getColumns(),
|
|
'indexes' => $tableBuilder->getIndexes()
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Define a estrutura da tabela no TableBuilder
|
|
* Deve ser implementado pelas migrations específicas
|
|
*/
|
|
protected function defineTableStructure(string $tableName, $tableBuilder): void
|
|
{
|
|
// Por padrão, não faz nada - as migrations devem sobrescrever
|
|
}
|
|
|
|
/**
|
|
* Normalize MySQL type for comparison
|
|
*/
|
|
private function normalizeType(string $type): string
|
|
{
|
|
// Convert to uppercase and remove length specifications for comparison
|
|
$type = strtoupper(trim($type));
|
|
|
|
// Remove length specifications like (11), (255), etc.
|
|
$type = preg_replace('/\(\d+\)/', '', $type);
|
|
|
|
// Normalize common variations
|
|
$type = str_replace('INTEGER', 'INT', $type);
|
|
$type = str_replace('CHARACTER VARYING', 'VARCHAR', $type);
|
|
|
|
return trim($type);
|
|
}
|
|
|
|
/**
|
|
* Normalize default values for comparison
|
|
*/
|
|
private function normalizeDefault($default): string
|
|
{
|
|
if ($default === null) {
|
|
return 'NULL';
|
|
}
|
|
|
|
// Convert to string and normalize
|
|
$default = (string)$default;
|
|
|
|
// Normalize common default values
|
|
if ($default === '1' || $default === 1) {
|
|
return '1';
|
|
}
|
|
|
|
if ($default === '0' || $default === 0) {
|
|
return '0';
|
|
}
|
|
|
|
if (strtoupper($default) === 'CURRENT_TIMESTAMP') {
|
|
return 'CURRENT_TIMESTAMP';
|
|
}
|
|
|
|
return $default;
|
|
}
|
|
}
|