56 lines
1.9 KiB
PHP
56 lines
1.9 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";
|
|
}
|
|
|
|
// Migration: create settings table and seed default retention if upgrading
|
|
$pdo->exec(
|
|
"CREATE TABLE IF NOT EXISTS settings (
|
|
key_name VARCHAR(64) NOT NULL,
|
|
value TEXT NOT NULL,
|
|
PRIMARY KEY (key_name)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
|
|
);
|
|
$pdo->exec("INSERT IGNORE INTO settings (key_name, value) VALUES ('retention_days', '7')");
|
|
$pdo->exec("INSERT IGNORE INTO settings (key_name, value) VALUES ('frequent_ip_threshold', '5')");
|
|
|
|
echo "Database '" . DB_NAME . "' and tables created/migrated successfully.\n";
|