-- =============================================
-- 智慧水务管理系统 - TDengine 建表脚本
-- 用于物联网设备遥测数据存储
-- =============================================

-- 创建数据库
CREATE DATABASE IF NOT EXISTS water_iot
  KEEP 365
  DURATION 30
  BUFFER 256
  PAGES 256
  PAGESIZE 4
  WAL_LEVEL 1;

USE water_iot;

-- 遥测数据超级表
CREATE STABLE IF NOT EXISTS iot_telemetry (
    ts TIMESTAMP,
    device_sn NCHAR(100),
    metric_key NCHAR(50),
    metric_value DOUBLE,
    quality TINYINT
) TAGS (
    device_type NCHAR(30),
    area NCHAR(50),
    station NCHAR(100)
);

-- 按设备类型创建子表（模板，实际运行时动态创建）
CREATE TABLE IF NOT EXISTS telemetry_flow_meter    USING iot_telemetry TAGS('flow_meter', 'default', 'default');
CREATE TABLE IF NOT EXISTS telemetry_pressure      USING iot_telemetry TAGS('pressure_sensor', 'default', 'default');
CREATE TABLE IF NOT EXISTS telemetry_valve         USING iot_telemetry TAGS('valve', 'default', 'default');
CREATE TABLE IF NOT EXISTS telemetry_water_quality USING iot_telemetry TAGS('water_quality', 'default', 'default');
CREATE TABLE IF NOT EXISTS telemetry_level         USING iot_telemetry TAGS('level_sensor', 'default', 'default');
CREATE TABLE IF NOT EXISTS telemetry_pump          USING iot_telemetry TAGS('pump', 'default', 'default');

-- 设备事件超级表
CREATE STABLE IF NOT EXISTS iot_device_event (
    ts TIMESTAMP,
    device_sn NCHAR(100),
    event_type NCHAR(30),
    event_data NCHAR(2000)
) TAGS (
    device_type NCHAR(30),
    area NCHAR(50)
);

-- 小时聚合超级表（自动聚合）
CREATE STABLE IF NOT EXISTS iot_telemetry_hourly (
    ts TIMESTAMP,
    device_sn NCHAR(100),
    metric_key NCHAR(50),
    min_value DOUBLE,
    max_value DOUBLE,
    avg_value DOUBLE,
    count_value INT
) TAGS (
    device_type NCHAR(30),
    area NCHAR(50)
);

-- 日聚合视图（示例）
-- CREATE STREAM IF NOT EXISTS hourly_stream INTO iot_telemetry_hourly AS
-- SELECT _wstart as ts, device_sn, metric_key,
--        MIN(metric_value), MAX(metric_value), AVG(metric_value), COUNT(*)
-- FROM iot_telemetry
-- INTERVAL(1h);
