exec('ALTER TABLE etablissements ADD COLUMN comc VARCHAR(5) NULL'); $pdo->exec('ALTER TABLE etablissements ADD INDEX idx_comc (comc)'); say('✔ Colonne comc ajoutée.'); } catch (Throwable $e) { say('ℹ Colonne comc déjà présente.'); } $tmp = __DIR__ . '/data/insee/annuaire_comc.csv'; @mkdir(dirname($tmp), 0777, true); say('… Téléchargement (identifiant + code_commune) …'); $fp = fopen($tmp, 'w'); $ch = curl_init(ANNUAIRE_COMC); curl_setopt_array($ch, [ CURLOPT_FILE => $fp, CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => 600, CURLOPT_USERAGENT => 'ecoles-import/1.0', ]); if (!curl_exec($ch)) { throw new RuntimeException('Téléchargement échoué : ' . curl_error($ch)); } curl_close($ch); fclose($fp); $fh = fopen($tmp, 'r'); $header = fgetcsv($fh, 0, ';'); $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', (string) $header[0]); $iId = array_search('identifiant_de_l_etablissement', $header, true); $iCom = array_search('code_commune', $header, true); if ($iId === false || $iCom === false) { throw new RuntimeException('Colonnes attendues introuvables.'); } $upd = $pdo->prepare('UPDATE etablissements SET comc = ? WHERE id = ?'); $pdo->beginTransaction(); $n = 0; while (($r = fgetcsv($fh, 0, ';')) !== false) { $id = $r[$iId] ?? ''; $com = $r[$iCom] ?? ''; if ($id === '' || $com === '') { continue; } $upd->execute([$com, $id]); if (++$n % 5000 === 0) { $pdo->commit(); $pdo->beginTransaction(); } } $pdo->commit(); fclose($fh); @unlink($tmp); $filled = (int) $pdo->query("SELECT COUNT(*) FROM etablissements WHERE comc IS NOT NULL AND comc <> ''")->fetchColumn(); say("✔ comc renseigné pour $filled établissements (sur $n lignes)."); say('🎉 Terminé.'); } catch (Throwable $e) { if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); } http_response_code(500); say('!! ERREUR : ' . $e->getMessage()); exit(1); }