database = $database; $this->pdo = $this->database->getPDO(); } public function getTableColumns($tableName) { if (!$this->tableExists($tableName)) { return []; // Retourne un tableau vide si la table n'existe pas } $query = "SELECT column_name, data_type FROM information_schema.columns WHERE table_name = :table_name AND table_schema = :table_schema"; $stmt = $this->pdo->prepare($query); $stmt->execute([ ':table_name' => $tableName ]); return $stmt->fetchAll(PDO::FETCH_ASSOC); } private function tableExists($tableName) { $schema = $this->database->getDefaultSchema(); $query = "SELECT COUNT(*) FROM information_schema.tables WHERE table_name = :table_name AND table_schema = :table_schema"; $stmt = $this->pdo->prepare($query); echo "Vérification de l'existence de la table : $tableName\n"; $stmt->execute([ ':table_name' => $tableName, ':table_schema' => $schema ]); return $stmt->fetchColumn() > 0; } public function processTables($tables) { foreach ($tables as $table) { $this->processTable($table); } } private function processTable($table) { $tableName = $table['name']; $columns = $table['columns']; $existingColumns = $this->getTableColumns($tableName); if (empty($existingColumns) && !$this->tableExists($tableName)) { $this->createTable($tableName, $columns); return; } $existingColumnsMap = []; foreach ($existingColumns as $column) { $existingColumnsMap[$column['column_name']] = $column['data_type']; } foreach ($columns as $column) { $columnName = $column['name']; $columnType = $column['type']; if (isset($existingColumnsMap[$columnName])) { if ($existingColumnsMap[$columnName] !== $columnType) { $this->alterColumnType($tableName, $columnName, $columnType); } unset($existingColumnsMap[$columnName]); } else { $this->addColumn($tableName, $columnName, $columnType); } } foreach ($existingColumnsMap as $columnName => $columnType) { $this->dropColumn($tableName, $columnName); } } public function createTable($tableName, $columns) { $columnsSql = []; foreach ($columns as $column) { $columnsSql[] = "{$column['name']} {$column['type']}"; } $columnsSql = implode(", ", $columnsSql); $sql = "CREATE TABLE $tableName ($columnsSql)"; $this->pdo->exec($sql); } public function dropTable($tableName) { $sql = "DROP TABLE IF EXISTS $tableName"; $this->pdo->exec($sql); } private function alterColumnType($tableName, $columnName, $columnType) { $sql = "ALTER TABLE $tableName ALTER COLUMN $columnName TYPE $columnType USING $columnName::$columnType"; $this->pdo->exec($sql); } private function addColumn($tableName, $columnName, $columnType) { $sql = "ALTER TABLE $tableName ADD COLUMN $columnName $columnType"; $this->pdo->exec($sql); } private function dropColumn($tableName, $columnName) { $sql = "ALTER TABLE $tableName DROP COLUMN $columnName"; $this->pdo->exec($sql); } }