using Gateway.Api.Options; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Options; namespace Gateway.Api.Services; public sealed class GatewayDatabase { private readonly string _connectionString; public string DataDirectory { get; } public GatewayDatabase(IOptions options) { DataDirectory = Path.GetFullPath(options.Value.DataDirectory); Directory.CreateDirectory(DataDirectory); _connectionString = new SqliteConnectionStringBuilder { DataSource = Path.Combine(DataDirectory, "seiugw.db"), Mode = SqliteOpenMode.ReadWriteCreate, Cache = SqliteCacheMode.Shared }.ToString(); } public SqliteConnection OpenConnection() { var connection = new SqliteConnection(_connectionString); connection.Open(); using var command = connection.CreateCommand(); command.CommandText = "PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;"; command.ExecuteNonQuery(); return connection; } public void Initialize() { using var connection = OpenConnection(); using var command = connection.CreateCommand(); command.CommandText = """ PRAGMA journal_mode = WAL; CREATE TABLE IF NOT EXISTS bacnet_commands ( id INTEGER PRIMARY KEY AUTOINCREMENT, point_id TEXT NOT NULL, value_json TEXT NOT NULL, priority INTEGER NOT NULL, created_ms INTEGER NOT NULL, state TEXT NOT NULL DEFAULT 'pending', result TEXT NULL ); CREATE TABLE IF NOT EXISTS bacnet_properties ( id INTEGER PRIMARY KEY AUTOINCREMENT, point_id TEXT NOT NULL, property INTEGER NOT NULL, array_index INTEGER NOT NULL, priority INTEGER NOT NULL, payload BLOB NOT NULL, UNIQUE(point_id, property, array_index, priority) ); CREATE TABLE IF NOT EXISTS bacnet_observations ( id INTEGER PRIMARY KEY AUTOINCREMENT, point_id TEXT NOT NULL, value_json TEXT NOT NULL, status TEXT NOT NULL, observed_ms INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS bacnet_runtime ( id INTEGER PRIMARY KEY CHECK(id=1), heartbeat_ms INTEGER NOT NULL, state TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS bacnet_discovery ( id INTEGER PRIMARY KEY CHECK(id=1), scan_id TEXT NOT NULL, target TEXT, port INTEGER NOT NULL, expires_ms INTEGER NOT NULL, sent INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS bacnet_discovered_devices ( scan_id TEXT NOT NULL, device_instance INTEGER NOT NULL, address TEXT NOT NULL, port INTEGER NOT NULL, vendor INTEGER NOT NULL, max_apdu INTEGER NOT NULL, network INTEGER NOT NULL DEFAULT 0, mac TEXT, PRIMARY KEY(scan_id, device_instance, address, port) ); CREATE TABLE IF NOT EXISTS settings ( key TEXT NOT NULL PRIMARY KEY, value TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS alarm_rules ( id TEXT PRIMARY KEY, point_id TEXT NOT NULL REFERENCES points(id), enabled INTEGER NOT NULL, configuration_json TEXT NOT NULL, active INTEGER NULL, observed_at_utc TEXT NULL ); CREATE TABLE IF NOT EXISTS notification_outbox ( id INTEGER PRIMARY KEY AUTOINCREMENT, rule_id TEXT NOT NULL, title TEXT NOT NULL, message TEXT NOT NULL, destination_json TEXT NOT NULL, state TEXT NOT NULL, created_at_utc TEXT NOT NULL, result TEXT NULL ); CREATE INDEX IF NOT EXISTS idx_notification_pending ON notification_outbox(state, id); CREATE TABLE IF NOT EXISTS admin_account ( id INTEGER NOT NULL PRIMARY KEY CHECK(id = 1), username TEXT NOT NULL UNIQUE CHECK(username = 'admin'), password_hash BLOB NOT NULL, password_salt BLOB NOT NULL, password_iterations INTEGER NOT NULL, changed_at_utc TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS app_roles ( name TEXT NOT NULL PRIMARY KEY, label TEXT NOT NULL, permissions_json TEXT NOT NULL, is_system INTEGER NOT NULL, updated_at_utc TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS app_users ( id TEXT NOT NULL PRIMARY KEY, username TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL, email TEXT NULL UNIQUE, password_hash BLOB NOT NULL, password_salt BLOB NOT NULL, password_iterations INTEGER NOT NULL, role_name TEXT NOT NULL REFERENCES app_roles(name) ON UPDATE CASCADE ON DELETE RESTRICT, active INTEGER NOT NULL, created_at_utc TEXT NOT NULL, updated_at_utc TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS app_user_preferences ( user_id TEXT NOT NULL PRIMARY KEY REFERENCES app_users(id) ON DELETE CASCADE, theme TEXT NOT NULL DEFAULT 'system', csv_delimiter TEXT NOT NULL DEFAULT ';', sidebar_pinned INTEGER NOT NULL DEFAULT 1, trend_line_width REAL NOT NULL DEFAULT 1.8, updated_at_utc TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS points ( id TEXT NOT NULL PRIMARY KEY, display_name TEXT NOT NULL, protocol TEXT NOT NULL, scope TEXT NOT NULL, value_type TEXT NOT NULL, readable INTEGER NOT NULL, writable INTEGER NOT NULL, external_identity TEXT NULL, address_json TEXT NOT NULL, created_at_utc TEXT NOT NULL, bacnet_object_kind TEXT NULL, bacnet_object_instance INTEGER NULL, deleted_at_utc TEXT NULL ); CREATE UNIQUE INDEX IF NOT EXISTS idx_points_external_identity ON points(protocol, external_identity) WHERE external_identity IS NOT NULL; CREATE TABLE IF NOT EXISTS mappings ( id TEXT NOT NULL PRIMARY KEY, source_point_id TEXT NOT NULL REFERENCES points(id) ON DELETE RESTRICT, target_point_id TEXT NOT NULL REFERENCES points(id) ON DELETE RESTRICT, direction TEXT NOT NULL, enabled INTEGER NOT NULL, bacnet_priority INTEGER NULL, acknowledge_multiple_external_writers INTEGER NOT NULL, transform_json TEXT NOT NULL, created_at_utc TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS mqtt_mappings ( id TEXT NOT NULL PRIMARY KEY, point_id TEXT NOT NULL REFERENCES points(id) ON DELETE RESTRICT, format TEXT NOT NULL, direction TEXT NOT NULL, quality_of_service TEXT NOT NULL, retain INTEGER NOT NULL, project_year INTEGER NULL, project_number TEXT NULL, isp_number TEXT NULL, se_category TEXT NULL, topic_name TEXT NULL, json_topic TEXT NULL, json_property TEXT NULL, created_at_utc TEXT NOT NULL ); CREATE UNIQUE INDEX IF NOT EXISTS idx_mqtt_mapping_point_topic ON mqtt_mappings(point_id, format, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property); CREATE TABLE IF NOT EXISTS point_values ( point_id TEXT NOT NULL PRIMARY KEY REFERENCES points(id) ON DELETE CASCADE, value_json TEXT NOT NULL, source_protocol TEXT NOT NULL, updated_at_utc TEXT NOT NULL, status TEXT NULL ); CREATE TABLE IF NOT EXISTS audit_log ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, occurred_at_utc TEXT NOT NULL, category TEXT NOT NULL, message TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS trend_logs ( id TEXT NOT NULL PRIMARY KEY, source_point_id TEXT NOT NULL REFERENCES points(id) ON DELETE RESTRICT, name TEXT NOT NULL, bacnet_object_instance INTEGER NOT NULL UNIQUE, interval_seconds INTEGER NOT NULL, max_records INTEGER NOT NULL, enabled INTEGER NOT NULL, public_access INTEGER NOT NULL DEFAULT 0, created_at_utc TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS trend_records ( trend_log_id TEXT NOT NULL REFERENCES trend_logs(id) ON DELETE CASCADE, sequence_number INTEGER NOT NULL, timestamp_utc TEXT NOT NULL, value_json TEXT NOT NULL, source_protocol TEXT NOT NULL, status TEXT NULL, PRIMARY KEY(trend_log_id, sequence_number) ); CREATE INDEX IF NOT EXISTS idx_trend_records_query ON trend_records(trend_log_id, sequence_number DESC); CREATE TABLE IF NOT EXISTS trend_selections ( id TEXT NOT NULL PRIMARY KEY, name TEXT NOT NULL, description TEXT NULL, owner_id TEXT NOT NULL REFERENCES app_users(id) ON DELETE CASCADE, shared INTEGER NOT NULL, trend_log_ids_json TEXT NOT NULL, created_at_utc TEXT NOT NULL, updated_at_utc TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS csv_runner_jobs ( id TEXT NOT NULL PRIMARY KEY, name TEXT NOT NULL, selection_id TEXT NOT NULL REFERENCES trend_selections(id) ON DELETE RESTRICT, time TEXT NOT NULL, range_hours INTEGER NOT NULL, delimiter TEXT NOT NULL, enabled INTEGER NOT NULL, mail_enabled INTEGER NOT NULL, mail_to TEXT NULL, mail_subject TEXT NOT NULL, mail_message TEXT NOT NULL, last_run_local_date TEXT NULL, last_result_json TEXT NULL, created_at_utc TEXT NOT NULL, updated_at_utc TEXT NOT NULL ); """; command.ExecuteNonQuery(); EnsureColumn(connection, "points", "bacnet_object_kind", "TEXT NULL"); EnsureColumn(connection, "points", "bacnet_object_instance", "INTEGER NULL"); EnsureColumn(connection, "points", "deleted_at_utc", "TEXT NULL"); EnsureColumn(connection, "trend_logs", "public_access", "INTEGER NOT NULL DEFAULT 0"); EnsureColumn(connection, "bacnet_discovered_devices", "network", "INTEGER NOT NULL DEFAULT 0"); EnsureColumn(connection, "bacnet_discovered_devices", "mac", "TEXT NULL"); using var indexMigration = connection.BeginTransaction(); using var pointIndexes = connection.CreateCommand(); pointIndexes.Transaction = indexMigration; pointIndexes.CommandText = """ DROP INDEX IF EXISTS idx_points_external_identity; CREATE UNIQUE INDEX idx_points_external_identity ON points(protocol, external_identity) WHERE external_identity IS NOT NULL AND deleted_at_utc IS NULL; DROP INDEX IF EXISTS idx_points_bacnet_object; CREATE UNIQUE INDEX idx_points_bacnet_object ON points(bacnet_object_kind, bacnet_object_instance) WHERE scope = 'Gateway' AND bacnet_object_kind IS NOT NULL AND bacnet_object_instance IS NOT NULL AND deleted_at_utc IS NULL; """; pointIndexes.ExecuteNonQuery(); indexMigration.Commit(); } private static void EnsureColumn(SqliteConnection connection, string tableName, string columnName, string definition) { using var pragma = connection.CreateCommand(); pragma.CommandText = $"PRAGMA table_info({tableName});"; using var reader = pragma.ExecuteReader(); while (reader.Read()) { if (string.Equals(reader.GetString(1), columnName, StringComparison.OrdinalIgnoreCase)) { return; } } using var alter = connection.CreateCommand(); alter.CommandText = $"ALTER TABLE {tableName} ADD COLUMN {columnName} {definition};"; alter.ExecuteNonQuery(); } }