Files
portspoof_concentrator/setup.php
2026-03-11 10:14:26 -04:00

45 lines
1.5 KiB
PHP

<?php
/**
* First-run database setup.
* Run once from the CLI: php setup.php
* Then delete or protect this file.
*/
require_once __DIR__ . '/config.php';
$dsn = sprintf('mysql:host=%s;port=%d;charset=utf8mb4', DB_HOST, DB_PORT);
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
} catch (PDOException $e) {
fwrite(STDERR, "Connection failed: " . $e->getMessage() . "\n");
exit(1);
}
$pdo->exec("CREATE DATABASE IF NOT EXISTS `" . DB_NAME . "` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
$pdo->exec("USE `" . DB_NAME . "`");
$schema = file_get_contents(__DIR__ . '/schema.sql');
foreach (array_filter(array_map('trim', explode(';', $schema))) as $stmt) {
$pdo->exec($stmt);
}
// Migration: add last_event_at if upgrading from an older schema
$pdo->exec(
"ALTER TABLE nodes ADD COLUMN IF NOT EXISTS
last_event_at DATETIME(6) NULL COMMENT 'timestamp of the newest ingested event from this node'
AFTER last_fetched_at"
);
// Migration: drop uq_event unique key if upgrading from an older schema
$row = $pdo->query(
"SELECT COUNT(*) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'connections'
AND INDEX_NAME = 'uq_event'"
)->fetchColumn();
if ($row > 0) {
$pdo->exec("ALTER TABLE connections DROP INDEX uq_event");
echo "Dropped legacy uq_event unique key.\n";
}
echo "Database '" . DB_NAME . "' and tables created/migrated successfully.\n";