IoT Device Telemetry ER diagram and database schema
The IoT Device Telemetry database schema is a DB Planner template with 25 tables, 216 columns and 51 relationships, free to use. Core tables include alert_events, alert_rule_targets, alert_rules, alerts. It can be opened as an interactive ER diagram or exported as PostgreSQL, MySQL, or SQL Server DDL.
- Tables
- 25
- Columns
- 216
- Relationships
- 51
- Category
- IoT
- Exports
- DBML, SQL, Prisma, C#
- Price
- Free
What this schema models
A complete IoT device telemetry database design, built for fleets that report millions of readings a day: 25 tables, 20 enums and 51 relationships covering tenants, sites and users, device models, devices, gateways and rotating credentials, device groups, per-device sensor channels, raw telemetry and hourly rollups, connection events and heartbeats, cloud-to-device commands, alert rules, alerts and their timelines, and firmware releases with staged rollouts. THE FOUR DESIGN RULES 1. Telemetry is narrow and append-only. One row per channel per instant (channel, time, value, quality), keyed on (channel_id, recorded_at) with no surrogate id. The table is partitioned by time with a BRIN index on recorded_at, retention is DROP PARTITION, and a gateway replaying its offline buffer is deduplicated by the key. 2. Charts read rollups, never raw rows. telemetry_hourly stores count, min, max, sum, first and last per channel per hour. Sums and counts (not averages) roll up to days exactly, and a late reading recomputes only the hour it belongs to. 3. Commands are a state machine with an expiry. Queued, sent, delivered, acknowledged, or failed, or expired, each with its own timestamp, plus a message id echoed back so a duplicate ack is recognised. A reboot queued for an offline device never fires three days later. 4. Reported is not desired. devices.current_firmware_id is what the device says it runs; a rollout is the intent, with canary stages, a soak time, an automatic pause past a failure threshold, and per-device status that counts as success only when the device reports the new version. DETAILS WORTH STEALING - A gateway is a device (with a one-to-one gateways subtype), so credentials, heartbeats, commands and firmware rollouts apply to gateways unchanged. - Channels are templated per device model and instantiated per device, with per-sensor calibration offset and scale applied at ingest. - Credential rotation overlaps: the new certificate is issued and seen in use before the old one is revoked, and only fingerprints and public certificates are stored. - Alert rules have hysteresis (a separate clear threshold) and a hold time, and a partial unique index allows one live alert per rule per sensor, so a flapping sensor never opens hundreds. - Offline detection is a no-data rule measured in missed heartbeat intervals for the device model, not one fixed timeout. - Escalation is just a second notification target with a delay. WHAT YOU GET Clean DBML that imports directly into DB Planner, and a laid-out board with zones color-coded and framed: tenants and sites, firmware, device fleet, channels and telemetry, connectivity and commands, and alerting. Every table carries a note. Written for Postgres: device labels, command payloads and results, alert details and rollout maintenance windows are jsonb (JSON in MySQL, NVARCHAR(MAX) in SQL Server), and the time-partitioning advice for readings uses Postgres features, so plan the equivalent on other engines. Useful for developers building an IoT platform or fleet monitoring product, and for students who need a realistic IoT ER diagram for a DBMS project. This is a schema design reference; at very high ingest rates raw readings often move to a dedicated time-series database while the rest stays relational.
Tables (25)
| Table | Columns |
|---|---|
| alert_events | 8 |
| alert_rule_targets | 3 |
| alert_rules | 14 |
| alerts | 15 |
| channels | 8 |
| connection_events | 9 |
| device_commands | 17 |
| device_credentials | 11 |
| device_group_members | 3 |
| device_groups | 4 |
| device_heartbeats | 7 |
| device_models | 8 |
| devices | 13 |
| firmware_releases | 13 |
| firmware_rollouts | 12 |
| gateways | 5 |
| model_channels | 9 |
| notification_targets | 6 |
| rollout_devices | 9 |
| rollout_stages | 7 |
| sites | 7 |
| telemetry_hourly | 9 |
| telemetry_readings | 5 |
| tenants | 7 |
| users | 7 |
Every table and its columns
tenants
Customer organizations. Every device, rule and rollout belongs to exactly one, and row-level security keys on tenant_id.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| name | varchar(200) | not null | ||
| slug | varchar(60) | unique, not null | ||
| plan | tenant_plan | not null | ||
| rollup_retention_days | integer | not null, default 730 | How long hourly rollups are kept. Raw readings follow the global partition retention | |
| timezone | varchar(64) | not null | IANA zone; daily reports bucket by it | |
| created_at | timestamptz | not null, default `now()` |
sites
Physical places devices are installed: a plant, a building, a farm.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| tenant_id | uuid | FK, not null | tenants.id | |
| name | varchar(200) | not null | ||
| address | varchar(300) | |||
| latitude | numeric(9,6) | |||
| longitude | numeric(9,6) | |||
| timezone | varchar(64) | not null | Maintenance windows are in site local time |
Indexes: (tenant_id, name) unique
users
People in a tenant: who acknowledges alerts, sends commands and starts rollouts.
| Column | Type | Constraints | References |
|---|---|---|---|
| id | uuid | PK | |
| tenant_id | uuid | FK, not null | tenants.id |
| varchar(254) | unique, not null | ||
| name | varchar(200) | not null | |
| role | user_role | not null | |
| created_at | timestamptz | not null, default `now()` | |
| disabled_at | timestamptz |
device_models
Hardware types. A model defines which channels its devices have and which firmware they can run.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| manufacturer | varchar(120) | not null | ||
| model_number | varchar(60) | not null | ||
| name | varchar(200) | not null | ||
| kind | device_kind | not null | ||
| connectivity | connectivity | not null | ||
| battery_powered | boolean | not null, default false | ||
| heartbeat_interval_s | integer | not null, default 60 | Expected check-in interval. Offline means "no heartbeat for 3 intervals", not one fixed timeout |
Indexes: (manufacturer, model_number) unique
devices
One physical unit in the field. Gateways are devices too, so credentials, heartbeats, commands and firmware rollouts all apply to them unchanged.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| tenant_id | uuid | FK, not null | tenants.id | |
| site_id | uuid | FK | sites.id | Null while in stock or in transit |
| device_model_id | uuid | FK, not null | device_models.id | |
| serial_number | varchar(64) | not null | ||
| name | varchar(200) | |||
| gateway_device_id | uuid | FK | gateways.device_id | The gateway it reports through; null for devices that connect directly |
| current_firmware_id | uuid | FK | firmware_releases.id | REPORTED by the device on connect. What it should run is decided by rollouts |
| status | device_status | not null, default 'provisioned' | ||
| last_seen_at | timestamptz | CACHE of the latest heartbeat or reading | ||
| installed_at | timestamptz | |||
| decommissioned_at | timestamptz | |||
| labels | jsonb | Free-form key values, e.g. {"line": "3", "floor": "B2"} |
Indexes: (device_model_id, serial_number) unique, (tenant_id, site_id)
gateways
Extra attributes for the devices that are gateways: a one-to-one subtype of devices. Child devices point here.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| device_id | uuid | PK, FK | devices.id | |
| backhaul | backhaul | not null | How the gateway itself reaches the cloud | |
| buffer_capacity_hours | integer | not null | How long it can hold readings while offline. Buffered readings arrive late, with their original recorded_at | |
| max_child_devices | integer | |||
| lan_ip | inet |
device_credentials
Certificates and keys a device authenticates with. Rotation overlaps: the new credential is issued and seen in use before the old one is revoked, so a device is never locked out mid-rotation.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| device_id | uuid | FK, not null | devices.id | |
| kind | credential_kind | not null | ||
| fingerprint | char(64) | unique, not null | SHA-256 of the certificate or public key; what the broker looks up on connect | |
| certificate_pem | text | Public certificate only. Private keys never leave the device | ||
| issued_at | timestamptz | not null, default `now()` | ||
| not_before | timestamptz | not null | ||
| expires_at | timestamptz | not null | ||
| revoked_at | timestamptz | |||
| revoke_reason | varchar(200) | |||
| replaces_credential_id | uuid | FK | device_credentials.id | Rotation chain: the credential this one supersedes |
Indexes: (device_id, expires_at), (expires_at)
device_groups
Named sets of devices, e.g. "pilot line" or "cold rooms", used to target rollouts and scope alert rules.
| Column | Type | Constraints | References |
|---|---|---|---|
| id | uuid | PK | |
| tenant_id | uuid | FK, not null | tenants.id |
| name | varchar(120) | not null | |
| description | varchar(500) |
Indexes: (tenant_id, name) unique
device_group_members
Group membership. A device can be in many groups.
| Column | Type | Constraints | References |
|---|---|---|---|
| device_group_id | uuid | FK, not null | device_groups.id |
| device_id | uuid | FK, not null | devices.id |
| added_at | timestamptz | not null, default `now()` |
model_channels
The channels a model has: the template every device of that model is created with.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| device_model_id | uuid | FK, not null | device_models.id | |
| key | varchar(60) | not null | Stable identifier in the payload, e.g. temp_c, rh_pct, door_open | |
| name | varchar(120) | not null | ||
| unit | varchar(20) | not null | UCUM unit code, e.g. Cel, %, kW.h. Values are always stored in this unit | |
| value_kind | value_kind | not null | ||
| min_valid | float8 | Physical range of the sensor. Outside it a reading is flagged, not dropped | ||
| max_valid | float8 | |||
| sample_interval_s | integer |
Indexes: (device_model_id, key) unique
channels
One sensor on one physical device, and the key every reading is filed under. Calibration lives here because two sensors of the same model never read identically.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| device_id | uuid | FK, not null | devices.id | |
| model_channel_id | uuid | FK, not null | model_channels.id | |
| calibration_offset | float8 | not null, default 0 | ||
| calibration_scale | float8 | not null, default 1 | Stored value = raw * scale + offset, applied at ingest | |
| is_enabled | boolean | not null, default true | ||
| last_value | float8 | CACHE of the newest reading, for device lists and map pins | ||
| last_recorded_at | timestamptz |
Indexes: (device_id, model_channel_id) unique
telemetry_readings
Raw readings: narrow, append-only, never updated. PARTITION BY RANGE (recorded_at), one partition per day or week, created ahead of time by a job. Retention is DROP PARTITION, which is instant, instead of a DELETE that bloats the table. No surrogate id: at billions of rows a uuid per reading costs more than the reading itself.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| channel_id | uuid | FK, not null | channels.id | |
| recorded_at | timestamptz | not null | Device clock, when it was measured. The partition key | |
| received_at | timestamptz | not null, default `now()` | Server clock. A large gap means it was buffered offline | |
| value | float8 | not null | Booleans are 0 or 1; enumerated states use their numeric code | |
| quality | reading_quality | not null, default 'good' |
Indexes: (recorded_at)
telemetry_hourly
Hourly rollup per channel. Every chart wider than a few hours reads here, never from raw readings.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| channel_id | uuid | FK, not null | channels.id | |
| hour_start | timestamptz | not null | ||
| sample_count | integer | not null | ||
| min_value | float8 | not null | ||
| max_value | float8 | not null | ||
| sum_value | float8 | not null | A sum, not an average: averages of averages are wrong, while sums and counts roll up to days exactly | |
| first_value | float8 | |||
| last_value | float8 | |||
| computed_at | timestamptz | not null | Late readings for this hour (received_at after this) trigger a recompute of just this row |
connection_events
Connects, disconnects and failed authentications, from the broker. Uptime reports are computed from these.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| device_id | uuid | FK, not null | devices.id | |
| kind | connection_event_kind | not null | ||
| occurred_at | timestamptz | not null | ||
| via_gateway_id | uuid | FK | gateways.device_id | |
| credential_id | uuid | FK | device_credentials.id | Which credential it presented. Repeated failures with a revoked one deserve an alert |
| remote_ip | inet | |||
| protocol | varchar(20) | e.g. mqtt, coap, https | ||
| reason | varchar(200) | Disconnect or failure reason as reported by the broker |
Indexes: (device_id, occurred_at)
device_heartbeats
Periodic health check-ins. Partitioned by time like readings, with shorter retention; devices.last_seen_at caches the latest.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| device_id | uuid | FK, not null | devices.id | |
| received_at | timestamptz | not null | ||
| battery_pct | smallint | |||
| signal_dbm | smallint | Received signal strength. Trending it finds devices about to drop off | ||
| uptime_s | bigint | Seconds since boot. A drop to near zero means an unplanned reboot | ||
| free_memory_kb | integer | |||
| firmware_version | varchar(40) | As reported; devices.current_firmware_id is updated from it |
device_commands
Cloud-to-device commands as a state machine: queued, sent, delivered, acknowledged, or failed, or expired. Each transition stamps its own column, so where a command stalled is visible. Devices are often asleep or offline, which is why queued and expired exist at all.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| device_id | uuid | FK, not null | devices.id | |
| command | varchar(60) | not null | e.g. reboot, set_sample_interval, open_valve | |
| payload | jsonb | |||
| status | command_status | not null, default 'queued' | ||
| issued_by | uuid | FK | users.id | Null for commands issued by automation |
| alert_id | uuid | FK | alerts.id | Set when an alert triggered it |
| message_id | uuid | unique, not null | Sent with the command and echoed back in the ack, so a duplicate ack is recognised | |
| attempts | smallint | not null, default 0 | ||
| created_at | timestamptz | not null, default `now()` | ||
| sent_at | timestamptz | |||
| delivered_at | timestamptz | |||
| acknowledged_at | timestamptz | |||
| failed_at | timestamptz | |||
| expires_at | timestamptz | not null | Never sent after this. A reboot queued for an offline device must not fire three days later | |
| result | jsonb | What the device reported back | ||
| error_message | varchar(500) |
Indexes: (device_id, status, created_at)
notification_targets
Where alerts can be sent: email, SMS, webhooks, on-call tools.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| tenant_id | uuid | FK, not null | tenants.id | |
| kind | notification_target_kind | not null | ||
| address | varchar(500) | not null | Email address, phone number, or webhook URL | |
| user_id | uuid | FK | users.id | Set when the target is a person rather than a shared channel |
| verified_at | timestamptz |
alert_rules
Thresholds, rate-of-change and no-data rules (the offline detector). Written once against a model channel, evaluated on every matching device.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| tenant_id | uuid | FK, not null | tenants.id | |
| name | varchar(200) | not null | ||
| kind | alert_rule_kind | not null | ||
| model_channel_id | uuid | FK, not null | model_channels.id | Which channel type the rule watches, e.g. temp_c on one model |
| device_group_id | uuid | FK | device_groups.id | Scope; null for every matching device in the tenant |
| operator | comparison_operator | Threshold rules only | ||
| threshold | float8 | Threshold rules only, in the channel unit | ||
| clear_threshold | float8 | Hysteresis: the alert resolves only past this value, so a reading hovering at the threshold does not flap | ||
| for_seconds | integer | not null, default 0 | The condition must hold this long before an alert opens | |
| severity | alert_severity | not null | ||
| is_enabled | boolean | not null, default true | ||
| created_by | uuid | FK | users.id | |
| created_at | timestamptz | not null, default `now()` |
alert_rule_targets
Who hears about which rule, and when. Escalation is just a second target with a delay.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| alert_rule_id | uuid | FK, not null | alert_rules.id | |
| notification_target_id | uuid | FK, not null | notification_targets.id | |
| escalate_after_minutes | integer | Null notifies at once; a value notifies only if still unacknowledged after that long |
alerts
Incidents: open, then acknowledged, then resolved.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| alert_rule_id | uuid | FK, not null | alert_rules.id | |
| device_id | uuid | FK, not null | devices.id | |
| channel_id | uuid | FK | channels.id | Null for device-level rules such as no data |
| status | alert_status | not null, default 'open' | ||
| severity | alert_severity | not null | Copied from the rule when opened, so editing the rule never rewrites history | |
| trigger_value | float8 | |||
| peak_value | float8 | Worst value seen while open | ||
| opened_at | timestamptz | not null | ||
| last_triggered_at | timestamptz | not null | ||
| acknowledged_at | timestamptz | |||
| acknowledged_by | uuid | FK | users.id | |
| resolved_at | timestamptz | |||
| resolved_by | uuid | FK | users.id | Null when it cleared automatically |
| resolution_comment | varchar(1000) |
Indexes: (alert_rule_id, device_id, channel_id), (status, opened_at)
alert_events
The timeline of an alert. alerts holds its current state; this holds how it got there, for the postmortem.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| alert_id | uuid | FK, not null | alerts.id | |
| kind | alert_event_kind | not null | ||
| occurred_at | timestamptz | not null, default `now()` | ||
| user_id | uuid | FK | users.id | |
| notification_target_id | uuid | FK | notification_targets.id | For notified and escalated events: where it was sent |
| value | float8 | |||
| details | jsonb |
Indexes: (alert_id, occurred_at)
firmware_releases
Firmware images, per hardware model.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| device_model_id | uuid | FK, not null | device_models.id | |
| version | varchar(40) | not null | Semantic version, e.g. 2.4.1 | |
| build_number | integer | not null | Monotonic. Ordering by it is safe where ordering version strings is not | |
| release_channel | release_channel | not null | ||
| storage_key | varchar(300) | not null | Object storage key of the image. Devices download it through a short-lived signed URL | |
| size_bytes | bigint | not null | ||
| sha256 | char(64) | not null | The device verifies the image before flashing it | |
| signature | text | not null | Signed by the build pipeline; the bootloader refuses unsigned images | |
| min_from_build | integer | Oldest build that can upgrade straight to this one; older devices need a stepping-stone release | ||
| release_notes | text | |||
| released_at | timestamptz | |||
| revoked_at | timestamptz | Pulled after release. Running rollouts of it are aborted |
Indexes: (device_model_id, version) unique, (device_model_id, build_number) unique
firmware_rollouts
A planned upgrade of many devices to one release, in stages. This is the intent; rollout_devices records what actually happened on each unit.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| tenant_id | uuid | FK, not null | tenants.id | |
| firmware_release_id | uuid | FK, not null | firmware_releases.id | |
| device_group_id | uuid | FK | device_groups.id | Target; null for every eligible device of the model in the tenant |
| name | varchar(200) | not null | ||
| status | rollout_status | not null, default 'draft' | ||
| max_failure_pct | numeric(5,2) | not null, default 2 | Pause automatically when a stage fails more than this | |
| maintenance_window | jsonb | Site-local hours devices may install in, e.g. {"days": [1,2,3,4,5], "from": "02:00", "to": "04:00"} | ||
| created_by | uuid | FK, not null | users.id | |
| created_at | timestamptz | not null, default `now()` | ||
| started_at | timestamptz | |||
| completed_at | timestamptz |
rollout_stages
Canary first, then wider. A stage starts only after the previous one soaked without crossing the failure threshold.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| id | uuid | PK | ||
| rollout_id | uuid | FK, not null | firmware_rollouts.id | |
| stage_number | smallint | not null | ||
| target_pct | numeric(5,2) | not null | Cumulative share of the target devices, e.g. 1, 10, 50, 100 | |
| soak_minutes | integer | not null, default 1440 | How long to watch a stage before the next may start | |
| started_at | timestamptz | |||
| completed_at | timestamptz |
Indexes: (rollout_id, stage_number) unique
rollout_devices
Per-device progress of a rollout. Success is confirmed by the device reporting the new version on reconnect, not by the download finishing.
| Column | Type | Constraints | References | Description |
|---|---|---|---|---|
| rollout_id | uuid | FK, not null | firmware_rollouts.id | |
| device_id | uuid | FK, not null | devices.id | |
| rollout_stage_id | uuid | FK, not null | rollout_stages.id | |
| from_firmware_id | uuid | FK | firmware_releases.id | What it ran before, for rollback |
| status | rollout_device_status | not null, default 'pending' | ||
| attempts | smallint | not null, default 0 | ||
| last_attempt_at | timestamptz | |||
| completed_at | timestamptz | |||
| error_code | varchar(60) |
Indexes: (rollout_stage_id, status)
Enums (20)
- tenant_plan
- starter, professional, enterprise
- user_role
- viewer, operator, admin
- device_kind
- sensor, actuator, meter, controller, gateway
- connectivity
- wifi, ethernet, cellular, lpwan, mesh_radio, via_gateway
- backhaul
- ethernet, wifi, cellular, satellite
- device_status
- provisioned, active, inactive, maintenance, decommissioned
- credential_kind
- x509_certificate, raw_public_key, symmetric_key
- value_kind
- gauge, counter, boolean, state
- reading_quality
- good, out_of_range, estimated, sensor_fault
- connection_event_kind
- connected, disconnected, keepalive_timeout, auth_failed
- command_status
- queued, sent, delivered, acknowledged, failed, expired
- notification_target_kind
- email, sms, webhook, on_call
- alert_rule_kind
- threshold, rate_of_change, no_data
- comparison_operator
- gt, gte, lt, lte, eq, neq
- alert_severity
- info, warning, critical
- alert_status
- open, acknowledged, resolved
- alert_event_kind
- opened, retriggered, notified, escalated, acknowledged, resolved, auto_resolved
- release_channel
- development, beta, stable
- rollout_status
- draft, running, paused, completed, aborted
- rollout_device_status
- pending, downloading, installing, succeeded, failed, rolled_back, skipped
Relationships (51)
alert_events.alert_id references alerts.idmany to onealert_events.notification_target_id references notification_targets.idmany to onealert_events.user_id references users.idmany to onealert_rule_targets.alert_rule_id references alert_rules.idmany to onealert_rule_targets.notification_target_id references notification_targets.idmany to onealert_rules.created_by references users.idmany to onealert_rules.device_group_id references device_groups.idmany to onealert_rules.model_channel_id references model_channels.idmany to onealert_rules.tenant_id references tenants.idmany to onealerts.acknowledged_by references users.idmany to onealerts.alert_rule_id references alert_rules.idmany to onealerts.channel_id references channels.idmany to onealerts.device_id references devices.idmany to onealerts.resolved_by references users.idmany to onechannels.device_id references devices.idmany to onechannels.model_channel_id references model_channels.idmany to oneconnection_events.credential_id references device_credentials.idmany to oneconnection_events.device_id references devices.idmany to oneconnection_events.via_gateway_id references gateways.device_idmany to onedevice_commands.alert_id references alerts.idmany to onedevice_commands.device_id references devices.idmany to onedevice_commands.issued_by references users.idmany to onedevice_credentials.device_id references devices.idmany to onedevice_credentials.replaces_credential_id references device_credentials.idmany to onedevice_group_members.device_group_id references device_groups.idmany to onedevice_group_members.device_id references devices.idmany to onedevice_groups.tenant_id references tenants.idmany to onedevice_heartbeats.device_id references devices.idmany to onedevices.current_firmware_id references firmware_releases.idmany to onedevices.device_model_id references device_models.idmany to onedevices.gateway_device_id references gateways.device_idmany to onedevices.id references gateways.device_idone to onedevices.site_id references sites.idmany to onedevices.tenant_id references tenants.idmany to onefirmware_releases.device_model_id references device_models.idmany to onefirmware_rollouts.created_by references users.idmany to onefirmware_rollouts.device_group_id references device_groups.idmany to onefirmware_rollouts.firmware_release_id references firmware_releases.idmany to onefirmware_rollouts.tenant_id references tenants.idmany to onemodel_channels.device_model_id references device_models.idmany to onenotification_targets.tenant_id references tenants.idmany to onenotification_targets.user_id references users.idmany to onerollout_devices.device_id references devices.idmany to onerollout_devices.from_firmware_id references firmware_releases.idmany to onerollout_devices.rollout_id references firmware_rollouts.idmany to onerollout_devices.rollout_stage_id references rollout_stages.idmany to onerollout_stages.rollout_id references firmware_rollouts.idmany to onesites.tenant_id references tenants.idmany to onetelemetry_hourly.channel_id references channels.idmany to onetelemetry_readings.channel_id references channels.idmany to oneusers.tenant_id references tenants.idmany to one
IoT Device Telemetry database schema in DBML
The schema as it is written: DBML, the text format DB Planner draws its diagrams from. Copy it into any DBML tool, or open it in the diagram above.
// IoT Device Telemetry
// Zones (header colors): tenants and sites (gray), device fleet (blue),
// channels and telemetry (teal), connectivity and commands (green),
// alerting (amber), firmware (purple).
// ---------------------------------------------------------------------------
// TENANTS AND SITES
// ---------------------------------------------------------------------------
Table tenants [headercolor: #90a4ae] {
id uuid [pk]
name varchar(200) [not null]
slug varchar(60) [not null, unique]
plan tenant_plan [not null]
rollup_retention_days integer [not null, default: 730, note: 'How long hourly rollups are kept. Raw readings follow the global partition retention']
timezone varchar(64) [not null, note: 'IANA zone; daily reports bucket by it']
created_at timestamptz [not null, default: `now()`]
Note: 'Customer organizations. Every device, rule and rollout belongs to exactly one, and row-level security keys on tenant_id.'
}
Table sites [headercolor: #90a4ae] {
id uuid [pk]
tenant_id uuid [not null, ref: > tenants.id]
name varchar(200) [not null]
address varchar(300)
latitude numeric(9,6)
longitude numeric(9,6)
timezone varchar(64) [not null, note: 'Maintenance windows are in site local time']
indexes {
(tenant_id, name) [unique]
}
Note: 'Physical places devices are installed: a plant, a building, a farm.'
}
Table users [headercolor: #90a4ae] {
id uuid [pk]
tenant_id uuid [not null, ref: > tenants.id]
email varchar(254) [not null, unique]
name varchar(200) [not null]
role user_role [not null]
created_at timestamptz [not null, default: `now()`]
disabled_at timestamptz
Note: 'People in a tenant: who acknowledges alerts, sends commands and starts rollouts.'
}
// ---------------------------------------------------------------------------
// DEVICE FLEET: models, units, gateways, credentials
// ---------------------------------------------------------------------------
Table device_models [headercolor: #4c8bf5] {
id uuid [pk]
manufacturer varchar(120) [not null]
model_number varchar(60) [not null]
name varchar(200) [not null]
kind device_kind [not null]
connectivity connectivity [not null]
battery_powered boolean [not null, default: false]
heartbeat_interval_s integer [not null, default: 60, note: 'Expected check-in interval. Offline means "no heartbeat for 3 intervals", not one fixed timeout']
indexes {
(manufacturer, model_number) [unique]
}
Note: 'Hardware types. A model defines which channels its devices have and which firmware they can run.'
}
Table devices [headercolor: #4c8bf5] {
id uuid [pk]
tenant_id uuid [not null, ref: > tenants.id]
site_id uuid [ref: > sites.id, note: 'Null while in stock or in transit']
device_model_id uuid [not null, ref: > device_models.id]
serial_number varchar(64) [not null]
name varchar(200)
gateway_device_id uuid [ref: > gateways.device_id, note: 'The gateway it reports through; null for devices that connect directly']
current_firmware_id uuid [ref: > firmware_releases.id, note: 'REPORTED by the device on connect. What it should run is decided by rollouts']
status device_status [not null, default: 'provisioned']
last_seen_at timestamptz [note: 'CACHE of the latest heartbeat or reading']
installed_at timestamptz
decommissioned_at timestamptz
labels jsonb [note: 'Free-form key values, e.g. {"line": "3", "floor": "B2"}']
indexes {
(device_model_id, serial_number) [unique, note: 'Serials are only unique per model']
(tenant_id, site_id)
}
Note: 'One physical unit in the field. Gateways are devices too, so credentials, heartbeats, commands and firmware rollouts all apply to them unchanged.'
}
Table gateways [headercolor: #4c8bf5] {
device_id uuid [pk, ref: - devices.id]
backhaul backhaul [not null, note: 'How the gateway itself reaches the cloud']
buffer_capacity_hours integer [not null, note: 'How long it can hold readings while offline. Buffered readings arrive late, with their original recorded_at']
max_child_devices integer
lan_ip inet
Note: 'Extra attributes for the devices that are gateways: a one-to-one subtype of devices. Child devices point here.'
}
Table device_credentials [headercolor: #4c8bf5] {
id uuid [pk]
device_id uuid [not null, ref: > devices.id]
kind credential_kind [not null]
fingerprint char(64) [not null, unique, note: 'SHA-256 of the certificate or public key; what the broker looks up on connect']
certificate_pem text [note: 'Public certificate only. Private keys never leave the device']
issued_at timestamptz [not null, default: `now()`]
not_before timestamptz [not null]
expires_at timestamptz [not null]
revoked_at timestamptz
revoke_reason varchar(200)
replaces_credential_id uuid [ref: > device_credentials.id, note: 'Rotation chain: the credential this one supersedes']
indexes {
(device_id, expires_at)
expires_at [note: 'Find credentials due for rotation']
}
Note: 'Certificates and keys a device authenticates with. Rotation overlaps: the new credential is issued and seen in use before the old one is revoked, so a device is never locked out mid-rotation.'
}
Table device_groups [headercolor: #4c8bf5] {
id uuid [pk]
tenant_id uuid [not null, ref: > tenants.id]
name varchar(120) [not null]
description varchar(500)
indexes {
(tenant_id, name) [unique]
}
Note: 'Named sets of devices, e.g. "pilot line" or "cold rooms", used to target rollouts and scope alert rules.'
}
Table device_group_members [headercolor: #4c8bf5] {
device_group_id uuid [not null, ref: > device_groups.id]
device_id uuid [not null, ref: > devices.id]
added_at timestamptz [not null, default: `now()`]
indexes {
(device_group_id, device_id) [pk]
}
Note: 'Group membership. A device can be in many groups.'
}
// ---------------------------------------------------------------------------
// CHANNELS AND TELEMETRY: narrow, append-only, rolled up
// ---------------------------------------------------------------------------
Table model_channels [headercolor: #4cd0b0] {
id uuid [pk]
device_model_id uuid [not null, ref: > device_models.id]
key varchar(60) [not null, note: 'Stable identifier in the payload, e.g. temp_c, rh_pct, door_open']
name varchar(120) [not null]
unit varchar(20) [not null, note: 'UCUM unit code, e.g. Cel, %, kW.h. Values are always stored in this unit']
value_kind value_kind [not null]
min_valid float8 [note: 'Physical range of the sensor. Outside it a reading is flagged, not dropped']
max_valid float8
sample_interval_s integer
indexes {
(device_model_id, key) [unique]
}
Note: 'The channels a model has: the template every device of that model is created with.'
}
Table channels [headercolor: #4cd0b0] {
id uuid [pk]
device_id uuid [not null, ref: > devices.id]
model_channel_id uuid [not null, ref: > model_channels.id]
calibration_offset float8 [not null, default: 0]
calibration_scale float8 [not null, default: 1, note: 'Stored value = raw * scale + offset, applied at ingest']
is_enabled boolean [not null, default: true]
last_value float8 [note: 'CACHE of the newest reading, for device lists and map pins']
last_recorded_at timestamptz
indexes {
(device_id, model_channel_id) [unique]
}
Note: 'One sensor on one physical device, and the key every reading is filed under. Calibration lives here because two sensors of the same model never read identically.'
}
Table telemetry_readings [headercolor: #4cd0b0] {
channel_id uuid [not null, ref: > channels.id]
recorded_at timestamptz [not null, note: 'Device clock, when it was measured. The partition key']
received_at timestamptz [not null, default: `now()`, note: 'Server clock. A large gap means it was buffered offline']
value float8 [not null, note: 'Booleans are 0 or 1; enumerated states use their numeric code']
quality reading_quality [not null, default: 'good']
indexes {
(channel_id, recorded_at) [pk, note: 'Also the dedupe key: a gateway that replays its buffer inserts ON CONFLICT DO NOTHING']
recorded_at [note: 'Create as BRIN: rows arrive in time order, so a block-range index is tiny and still prunes time scans']
}
Note: '''Raw readings: narrow, append-only, never updated.
PARTITION BY RANGE (recorded_at), one partition per day or week, created ahead of time by a job. Retention is DROP PARTITION, which is instant, instead of a DELETE that bloats the table.
No surrogate id: at billions of rows a uuid per reading costs more than the reading itself.'''
}
Table telemetry_hourly [headercolor: #4cd0b0] {
channel_id uuid [not null, ref: > channels.id]
hour_start timestamptz [not null]
sample_count integer [not null]
min_value float8 [not null]
max_value float8 [not null]
sum_value float8 [not null, note: 'A sum, not an average: averages of averages are wrong, while sums and counts roll up to days exactly']
first_value float8
last_value float8
computed_at timestamptz [not null, note: 'Late readings for this hour (received_at after this) trigger a recompute of just this row']
indexes {
(channel_id, hour_start) [pk]
}
Note: 'Hourly rollup per channel. Every chart wider than a few hours reads here, never from raw readings.'
}
// ---------------------------------------------------------------------------
// CONNECTIVITY AND COMMANDS
// ---------------------------------------------------------------------------
Table connection_events [headercolor: #8bc34a] {
id uuid [pk]
device_id uuid [not null, ref: > devices.id]
kind connection_event_kind [not null]
occurred_at timestamptz [not null]
via_gateway_id uuid [ref: > gateways.device_id]
credential_id uuid [ref: > device_credentials.id, note: 'Which credential it presented. Repeated failures with a revoked one deserve an alert']
remote_ip inet
protocol varchar(20) [note: 'e.g. mqtt, coap, https']
reason varchar(200) [note: 'Disconnect or failure reason as reported by the broker']
indexes {
(device_id, occurred_at)
}
Note: 'Connects, disconnects and failed authentications, from the broker. Uptime reports are computed from these.'
}
Table device_heartbeats [headercolor: #8bc34a] {
device_id uuid [not null, ref: > devices.id]
received_at timestamptz [not null]
battery_pct smallint
signal_dbm smallint [note: 'Received signal strength. Trending it finds devices about to drop off']
uptime_s bigint [note: 'Seconds since boot. A drop to near zero means an unplanned reboot']
free_memory_kb integer
firmware_version varchar(40) [note: 'As reported; devices.current_firmware_id is updated from it']
indexes {
(device_id, received_at) [pk]
}
Note: 'Periodic health check-ins. Partitioned by time like readings, with shorter retention; devices.last_seen_at caches the latest.'
}
Table device_commands [headercolor: #8bc34a] {
id uuid [pk]
device_id uuid [not null, ref: > devices.id]
command varchar(60) [not null, note: 'e.g. reboot, set_sample_interval, open_valve']
payload jsonb
status command_status [not null, default: 'queued']
issued_by uuid [ref: > users.id, note: 'Null for commands issued by automation']
alert_id uuid [ref: > alerts.id, note: 'Set when an alert triggered it']
message_id uuid [not null, unique, note: 'Sent with the command and echoed back in the ack, so a duplicate ack is recognised']
attempts smallint [not null, default: 0]
created_at timestamptz [not null, default: `now()`]
sent_at timestamptz
delivered_at timestamptz
acknowledged_at timestamptz
failed_at timestamptz
expires_at timestamptz [not null, note: 'Never sent after this. A reboot queued for an offline device must not fire three days later']
result jsonb [note: 'What the device reported back']
error_message varchar(500)
indexes {
(device_id, status, created_at) [note: 'On reconnect: deliver queued, unexpired commands in order']
}
Note: '''Cloud-to-device commands as a state machine: queued, sent, delivered, acknowledged, or failed, or expired.
Each transition stamps its own column, so where a command stalled is visible. Devices are often asleep or offline, which is why queued and expired exist at all.'''
}
// ---------------------------------------------------------------------------
// ALERTING: rules, incidents, timeline
// ---------------------------------------------------------------------------
Table notification_targets [headercolor: #f5b74c] {
id uuid [pk]
tenant_id uuid [not null, ref: > tenants.id]
kind notification_target_kind [not null]
address varchar(500) [not null, note: 'Email address, phone number, or webhook URL']
user_id uuid [ref: > users.id, note: 'Set when the target is a person rather than a shared channel']
verified_at timestamptz
Note: 'Where alerts can be sent: email, SMS, webhooks, on-call tools.'
}
Table alert_rules [headercolor: #f5b74c] {
id uuid [pk]
tenant_id uuid [not null, ref: > tenants.id]
name varchar(200) [not null]
kind alert_rule_kind [not null]
model_channel_id uuid [not null, ref: > model_channels.id, note: 'Which channel type the rule watches, e.g. temp_c on one model']
device_group_id uuid [ref: > device_groups.id, note: 'Scope; null for every matching device in the tenant']
operator comparison_operator [note: 'Threshold rules only']
threshold float8 [note: 'Threshold rules only, in the channel unit']
clear_threshold float8 [note: 'Hysteresis: the alert resolves only past this value, so a reading hovering at the threshold does not flap']
for_seconds integer [not null, default: 0, note: 'The condition must hold this long before an alert opens']
severity alert_severity [not null]
is_enabled boolean [not null, default: true]
created_by uuid [ref: > users.id]
created_at timestamptz [not null, default: `now()`]
Note: 'Thresholds, rate-of-change and no-data rules (the offline detector). Written once against a model channel, evaluated on every matching device.'
}
Table alert_rule_targets [headercolor: #f5b74c] {
alert_rule_id uuid [not null, ref: > alert_rules.id]
notification_target_id uuid [not null, ref: > notification_targets.id]
escalate_after_minutes integer [note: 'Null notifies at once; a value notifies only if still unacknowledged after that long']
indexes {
(alert_rule_id, notification_target_id) [pk]
}
Note: 'Who hears about which rule, and when. Escalation is just a second target with a delay.'
}
Table alerts [headercolor: #f5b74c] {
id uuid [pk]
alert_rule_id uuid [not null, ref: > alert_rules.id]
device_id uuid [not null, ref: > devices.id]
channel_id uuid [ref: > channels.id, note: 'Null for device-level rules such as no data']
status alert_status [not null, default: 'open']
severity alert_severity [not null, note: 'Copied from the rule when opened, so editing the rule never rewrites history']
trigger_value float8
peak_value float8 [note: 'Worst value seen while open']
opened_at timestamptz [not null]
last_triggered_at timestamptz [not null]
acknowledged_at timestamptz
acknowledged_by uuid [ref: > users.id]
resolved_at timestamptz
resolved_by uuid [ref: > users.id, note: 'Null when it cleared automatically']
resolution_comment varchar(1000)
indexes {
(alert_rule_id, device_id, channel_id) [note: 'Partial unique NULLS NOT DISTINCT WHERE status <> resolved: one live alert per rule per sensor. A flapping sensor updates it instead of opening hundreds']
(status, opened_at)
}
Note: 'Incidents: open, then acknowledged, then resolved.'
}
Table alert_events [headercolor: #f5b74c] {
id uuid [pk]
alert_id uuid [not null, ref: > alerts.id]
kind alert_event_kind [not null]
occurred_at timestamptz [not null, default: `now()`]
user_id uuid [ref: > users.id]
notification_target_id uuid [ref: > notification_targets.id, note: 'For notified and escalated events: where it was sent']
value float8
details jsonb
indexes {
(alert_id, occurred_at)
}
Note: 'The timeline of an alert. alerts holds its current state; this holds how it got there, for the postmortem.'
}
// ---------------------------------------------------------------------------
// FIRMWARE: releases and staged rollouts
// ---------------------------------------------------------------------------
Table firmware_releases [headercolor: #b98cf0] {
id uuid [pk]
device_model_id uuid [not null, ref: > device_models.id]
version varchar(40) [not null, note: 'Semantic version, e.g. 2.4.1']
build_number integer [not null, note: 'Monotonic. Ordering by it is safe where ordering version strings is not']
release_channel release_channel [not null]
storage_key varchar(300) [not null, note: 'Object storage key of the image. Devices download it through a short-lived signed URL']
size_bytes bigint [not null]
sha256 char(64) [not null, note: 'The device verifies the image before flashing it']
signature text [not null, note: 'Signed by the build pipeline; the bootloader refuses unsigned images']
min_from_build integer [note: 'Oldest build that can upgrade straight to this one; older devices need a stepping-stone release']
release_notes text
released_at timestamptz
revoked_at timestamptz [note: 'Pulled after release. Running rollouts of it are aborted']
indexes {
(device_model_id, version) [unique]
(device_model_id, build_number) [unique]
}
Note: 'Firmware images, per hardware model.'
}
Table firmware_rollouts [headercolor: #b98cf0] {
id uuid [pk]
tenant_id uuid [not null, ref: > tenants.id]
firmware_release_id uuid [not null, ref: > firmware_releases.id]
device_group_id uuid [ref: > device_groups.id, note: 'Target; null for every eligible device of the model in the tenant']
name varchar(200) [not null]
status rollout_status [not null, default: 'draft']
max_failure_pct numeric(5,2) [not null, default: 2, note: 'Pause automatically when a stage fails more than this']
maintenance_window jsonb [note: 'Site-local hours devices may install in, e.g. {"days": [1,2,3,4,5], "from": "02:00", "to": "04:00"}']
created_by uuid [not null, ref: > users.id]
created_at timestamptz [not null, default: `now()`]
started_at timestamptz
completed_at timestamptz
Note: 'A planned upgrade of many devices to one release, in stages. This is the intent; rollout_devices records what actually happened on each unit.'
}
Table rollout_stages [headercolor: #b98cf0] {
id uuid [pk]
rollout_id uuid [not null, ref: > firmware_rollouts.id]
stage_number smallint [not null]
target_pct numeric(5,2) [not null, note: 'Cumulative share of the target devices, e.g. 1, 10, 50, 100']
soak_minutes integer [not null, default: 1440, note: 'How long to watch a stage before the next may start']
started_at timestamptz
completed_at timestamptz
indexes {
(rollout_id, stage_number) [unique]
}
Note: 'Canary first, then wider. A stage starts only after the previous one soaked without crossing the failure threshold.'
}
Table rollout_devices [headercolor: #b98cf0] {
rollout_id uuid [not null, ref: > firmware_rollouts.id]
device_id uuid [not null, ref: > devices.id]
rollout_stage_id uuid [not null, ref: > rollout_stages.id]
from_firmware_id uuid [ref: > firmware_releases.id, note: 'What it ran before, for rollback']
status rollout_device_status [not null, default: 'pending']
attempts smallint [not null, default: 0]
last_attempt_at timestamptz
completed_at timestamptz
error_code varchar(60)
indexes {
(rollout_id, device_id) [pk]
(rollout_stage_id, status) [note: 'Stage health: the failed share of this stage']
}
Note: 'Per-device progress of a rollout. Success is confirmed by the device reporting the new version on reconnect, not by the download finishing.'
}
// ---------------------------------------------------------------------------
// ENUMS
// ---------------------------------------------------------------------------
Enum tenant_plan {
starter
professional
enterprise
}
Enum user_role {
viewer
operator
admin
}
Enum device_kind {
sensor
actuator
meter
controller
gateway
}
Enum connectivity {
wifi
ethernet
cellular
lpwan
mesh_radio
via_gateway
}
Enum backhaul {
ethernet
wifi
cellular
satellite
}
Enum device_status {
provisioned
active
inactive
maintenance
decommissioned
}
Enum credential_kind {
x509_certificate
raw_public_key
symmetric_key
}
Enum value_kind {
gauge [note: 'A level at an instant, e.g. temperature']
counter [note: 'Monotonic total, e.g. energy used. Rates come from differences']
boolean
state
}
Enum reading_quality {
good
out_of_range
estimated
sensor_fault
}
Enum connection_event_kind {
connected
disconnected
keepalive_timeout
auth_failed
}
Enum command_status {
queued
sent
delivered
acknowledged
failed
expired
}
Enum notification_target_kind {
email
sms
webhook
on_call
}
Enum alert_rule_kind {
threshold
rate_of_change
no_data
}
Enum comparison_operator {
gt
gte
lt
lte
eq
neq
}
Enum alert_severity {
info
warning
critical
}
Enum alert_status {
open
acknowledged
resolved
}
Enum alert_event_kind {
opened
retriggered
notified
escalated
acknowledged
resolved
auto_resolved
}
Enum release_channel {
development
beta
stable
}
Enum rollout_status {
draft
running
paused
completed
aborted
}
Enum rollout_device_status {
pending
downloading
installing
succeeded
failed
rolled_back
skipped
}IoT Device Telemetry database schema as SQL
The same schema as CREATE TABLE statements, exported by DB Planner.
PostgreSQL is shown first; MySQL and SQL Server are below it.
PostgreSQL
CREATE TYPE "tenant_plan" AS ENUM (
'starter',
'professional',
'enterprise'
);
CREATE TYPE "user_role" AS ENUM (
'viewer',
'operator',
'admin'
);
CREATE TYPE "device_kind" AS ENUM (
'sensor',
'actuator',
'meter',
'controller',
'gateway'
);
CREATE TYPE "connectivity" AS ENUM (
'wifi',
'ethernet',
'cellular',
'lpwan',
'mesh_radio',
'via_gateway'
);
CREATE TYPE "backhaul" AS ENUM (
'ethernet',
'wifi',
'cellular',
'satellite'
);
CREATE TYPE "device_status" AS ENUM (
'provisioned',
'active',
'inactive',
'maintenance',
'decommissioned'
);
CREATE TYPE "credential_kind" AS ENUM (
'x509_certificate',
'raw_public_key',
'symmetric_key'
);
CREATE TYPE "value_kind" AS ENUM (
'gauge',
'counter',
'boolean',
'state'
);
CREATE TYPE "reading_quality" AS ENUM (
'good',
'out_of_range',
'estimated',
'sensor_fault'
);
CREATE TYPE "connection_event_kind" AS ENUM (
'connected',
'disconnected',
'keepalive_timeout',
'auth_failed'
);
CREATE TYPE "command_status" AS ENUM (
'queued',
'sent',
'delivered',
'acknowledged',
'failed',
'expired'
);
CREATE TYPE "notification_target_kind" AS ENUM (
'email',
'sms',
'webhook',
'on_call'
);
CREATE TYPE "alert_rule_kind" AS ENUM (
'threshold',
'rate_of_change',
'no_data'
);
CREATE TYPE "comparison_operator" AS ENUM (
'gt',
'gte',
'lt',
'lte',
'eq',
'neq'
);
CREATE TYPE "alert_severity" AS ENUM (
'info',
'warning',
'critical'
);
CREATE TYPE "alert_status" AS ENUM (
'open',
'acknowledged',
'resolved'
);
CREATE TYPE "alert_event_kind" AS ENUM (
'opened',
'retriggered',
'notified',
'escalated',
'acknowledged',
'resolved',
'auto_resolved'
);
CREATE TYPE "release_channel" AS ENUM (
'development',
'beta',
'stable'
);
CREATE TYPE "rollout_status" AS ENUM (
'draft',
'running',
'paused',
'completed',
'aborted'
);
CREATE TYPE "rollout_device_status" AS ENUM (
'pending',
'downloading',
'installing',
'succeeded',
'failed',
'rolled_back',
'skipped'
);
CREATE TABLE "tenants" (
"id" uuid PRIMARY KEY,
"name" varchar(200) NOT NULL,
"slug" varchar(60) UNIQUE NOT NULL,
"plan" tenant_plan NOT NULL,
"rollup_retention_days" integer NOT NULL DEFAULT 730,
"timezone" varchar(64) NOT NULL,
"created_at" timestamptz NOT NULL DEFAULT (now())
);
CREATE TABLE "sites" (
"id" uuid PRIMARY KEY,
"tenant_id" uuid NOT NULL,
"name" varchar(200) NOT NULL,
"address" varchar(300),
"latitude" numeric(9,6),
"longitude" numeric(9,6),
"timezone" varchar(64) NOT NULL
);
CREATE TABLE "users" (
"id" uuid PRIMARY KEY,
"tenant_id" uuid NOT NULL,
"email" varchar(254) UNIQUE NOT NULL,
"name" varchar(200) NOT NULL,
"role" user_role NOT NULL,
"created_at" timestamptz NOT NULL DEFAULT (now()),
"disabled_at" timestamptz
);
CREATE TABLE "device_models" (
"id" uuid PRIMARY KEY,
"manufacturer" varchar(120) NOT NULL,
"model_number" varchar(60) NOT NULL,
"name" varchar(200) NOT NULL,
"kind" device_kind NOT NULL,
"connectivity" connectivity NOT NULL,
"battery_powered" boolean NOT NULL DEFAULT false,
"heartbeat_interval_s" integer NOT NULL DEFAULT 60
);
CREATE TABLE "devices" (
"id" uuid PRIMARY KEY,
"tenant_id" uuid NOT NULL,
"site_id" uuid,
"device_model_id" uuid NOT NULL,
"serial_number" varchar(64) NOT NULL,
"name" varchar(200),
"gateway_device_id" uuid,
"current_firmware_id" uuid,
"status" device_status NOT NULL DEFAULT 'provisioned',
"last_seen_at" timestamptz,
"installed_at" timestamptz,
"decommissioned_at" timestamptz,
"labels" jsonb
);
CREATE TABLE "gateways" (
"device_id" uuid PRIMARY KEY,
"backhaul" backhaul NOT NULL,
"buffer_capacity_hours" integer NOT NULL,
"max_child_devices" integer,
"lan_ip" inet
);
CREATE TABLE "device_credentials" (
"id" uuid PRIMARY KEY,
"device_id" uuid NOT NULL,
"kind" credential_kind NOT NULL,
"fingerprint" char(64) UNIQUE NOT NULL,
"certificate_pem" text,
"issued_at" timestamptz NOT NULL DEFAULT (now()),
"not_before" timestamptz NOT NULL,
"expires_at" timestamptz NOT NULL,
"revoked_at" timestamptz,
"revoke_reason" varchar(200),
"replaces_credential_id" uuid
);
CREATE TABLE "device_groups" (
"id" uuid PRIMARY KEY,
"tenant_id" uuid NOT NULL,
"name" varchar(120) NOT NULL,
"description" varchar(500)
);
CREATE TABLE "device_group_members" (
"device_group_id" uuid NOT NULL,
"device_id" uuid NOT NULL,
"added_at" timestamptz NOT NULL DEFAULT (now()),
PRIMARY KEY ("device_group_id", "device_id")
);
CREATE TABLE "model_channels" (
"id" uuid PRIMARY KEY,
"device_model_id" uuid NOT NULL,
"key" varchar(60) NOT NULL,
"name" varchar(120) NOT NULL,
"unit" varchar(20) NOT NULL,
"value_kind" value_kind NOT NULL,
"min_valid" float8,
"max_valid" float8,
"sample_interval_s" integer
);
CREATE TABLE "channels" (
"id" uuid PRIMARY KEY,
"device_id" uuid NOT NULL,
"model_channel_id" uuid NOT NULL,
"calibration_offset" float8 NOT NULL DEFAULT 0,
"calibration_scale" float8 NOT NULL DEFAULT 1,
"is_enabled" boolean NOT NULL DEFAULT true,
"last_value" float8,
"last_recorded_at" timestamptz
);
CREATE TABLE "telemetry_readings" (
"channel_id" uuid NOT NULL,
"recorded_at" timestamptz NOT NULL,
"received_at" timestamptz NOT NULL DEFAULT (now()),
"value" float8 NOT NULL,
"quality" reading_quality NOT NULL DEFAULT 'good',
PRIMARY KEY ("channel_id", "recorded_at")
);
CREATE TABLE "telemetry_hourly" (
"channel_id" uuid NOT NULL,
"hour_start" timestamptz NOT NULL,
"sample_count" integer NOT NULL,
"min_value" float8 NOT NULL,
"max_value" float8 NOT NULL,
"sum_value" float8 NOT NULL,
"first_value" float8,
"last_value" float8,
"computed_at" timestamptz NOT NULL,
PRIMARY KEY ("channel_id", "hour_start")
);
CREATE TABLE "connection_events" (
"id" uuid PRIMARY KEY,
"device_id" uuid NOT NULL,
"kind" connection_event_kind NOT NULL,
"occurred_at" timestamptz NOT NULL,
"via_gateway_id" uuid,
"credential_id" uuid,
"remote_ip" inet,
"protocol" varchar(20),
"reason" varchar(200)
);
CREATE TABLE "device_heartbeats" (
"device_id" uuid NOT NULL,
"received_at" timestamptz NOT NULL,
"battery_pct" smallint,
"signal_dbm" smallint,
"uptime_s" bigint,
"free_memory_kb" integer,
"firmware_version" varchar(40),
PRIMARY KEY ("device_id", "received_at")
);
CREATE TABLE "device_commands" (
"id" uuid PRIMARY KEY,
"device_id" uuid NOT NULL,
"command" varchar(60) NOT NULL,
"payload" jsonb,
"status" command_status NOT NULL DEFAULT 'queued',
"issued_by" uuid,
"alert_id" uuid,
"message_id" uuid UNIQUE NOT NULL,
"attempts" smallint NOT NULL DEFAULT 0,
"created_at" timestamptz NOT NULL DEFAULT (now()),
"sent_at" timestamptz,
"delivered_at" timestamptz,
"acknowledged_at" timestamptz,
"failed_at" timestamptz,
"expires_at" timestamptz NOT NULL,
"result" jsonb,
"error_message" varchar(500)
);
CREATE TABLE "notification_targets" (
"id" uuid PRIMARY KEY,
"tenant_id" uuid NOT NULL,
"kind" notification_target_kind NOT NULL,
"address" varchar(500) NOT NULL,
"user_id" uuid,
"verified_at" timestamptz
);
CREATE TABLE "alert_rules" (
"id" uuid PRIMARY KEY,
"tenant_id" uuid NOT NULL,
"name" varchar(200) NOT NULL,
"kind" alert_rule_kind NOT NULL,
"model_channel_id" uuid NOT NULL,
"device_group_id" uuid,
"operator" comparison_operator,
"threshold" float8,
"clear_threshold" float8,
"for_seconds" integer NOT NULL DEFAULT 0,
"severity" alert_severity NOT NULL,
"is_enabled" boolean NOT NULL DEFAULT true,
"created_by" uuid,
"created_at" timestamptz NOT NULL DEFAULT (now())
);
CREATE TABLE "alert_rule_targets" (
"alert_rule_id" uuid NOT NULL,
"notification_target_id" uuid NOT NULL,
"escalate_after_minutes" integer,
PRIMARY KEY ("alert_rule_id", "notification_target_id")
);
CREATE TABLE "alerts" (
"id" uuid PRIMARY KEY,
"alert_rule_id" uuid NOT NULL,
"device_id" uuid NOT NULL,
"channel_id" uuid,
"status" alert_status NOT NULL DEFAULT 'open',
"severity" alert_severity NOT NULL,
"trigger_value" float8,
"peak_value" float8,
"opened_at" timestamptz NOT NULL,
"last_triggered_at" timestamptz NOT NULL,
"acknowledged_at" timestamptz,
"acknowledged_by" uuid,
"resolved_at" timestamptz,
"resolved_by" uuid,
"resolution_comment" varchar(1000)
);
CREATE TABLE "alert_events" (
"id" uuid PRIMARY KEY,
"alert_id" uuid NOT NULL,
"kind" alert_event_kind NOT NULL,
"occurred_at" timestamptz NOT NULL DEFAULT (now()),
"user_id" uuid,
"notification_target_id" uuid,
"value" float8,
"details" jsonb
);
CREATE TABLE "firmware_releases" (
"id" uuid PRIMARY KEY,
"device_model_id" uuid NOT NULL,
"version" varchar(40) NOT NULL,
"build_number" integer NOT NULL,
"release_channel" release_channel NOT NULL,
"storage_key" varchar(300) NOT NULL,
"size_bytes" bigint NOT NULL,
"sha256" char(64) NOT NULL,
"signature" text NOT NULL,
"min_from_build" integer,
"release_notes" text,
"released_at" timestamptz,
"revoked_at" timestamptz
);
CREATE TABLE "firmware_rollouts" (
"id" uuid PRIMARY KEY,
"tenant_id" uuid NOT NULL,
"firmware_release_id" uuid NOT NULL,
"device_group_id" uuid,
"name" varchar(200) NOT NULL,
"status" rollout_status NOT NULL DEFAULT 'draft',
"max_failure_pct" numeric(5,2) NOT NULL DEFAULT 2,
"maintenance_window" jsonb,
"created_by" uuid NOT NULL,
"created_at" timestamptz NOT NULL DEFAULT (now()),
"started_at" timestamptz,
"completed_at" timestamptz
);
CREATE TABLE "rollout_stages" (
"id" uuid PRIMARY KEY,
"rollout_id" uuid NOT NULL,
"stage_number" smallint NOT NULL,
"target_pct" numeric(5,2) NOT NULL,
"soak_minutes" integer NOT NULL DEFAULT 1440,
"started_at" timestamptz,
"completed_at" timestamptz
);
CREATE TABLE "rollout_devices" (
"rollout_id" uuid NOT NULL,
"device_id" uuid NOT NULL,
"rollout_stage_id" uuid NOT NULL,
"from_firmware_id" uuid,
"status" rollout_device_status NOT NULL DEFAULT 'pending',
"attempts" smallint NOT NULL DEFAULT 0,
"last_attempt_at" timestamptz,
"completed_at" timestamptz,
"error_code" varchar(60),
PRIMARY KEY ("rollout_id", "device_id")
);
CREATE UNIQUE INDEX ON "sites" ("tenant_id", "name");
CREATE UNIQUE INDEX ON "device_models" ("manufacturer", "model_number");
CREATE UNIQUE INDEX ON "devices" ("device_model_id", "serial_number");
CREATE INDEX ON "devices" ("tenant_id", "site_id");
CREATE INDEX ON "device_credentials" ("device_id", "expires_at");
CREATE INDEX ON "device_credentials" ("expires_at");
CREATE UNIQUE INDEX ON "device_groups" ("tenant_id", "name");
CREATE UNIQUE INDEX ON "model_channels" ("device_model_id", "key");
CREATE UNIQUE INDEX ON "channels" ("device_id", "model_channel_id");
CREATE INDEX ON "telemetry_readings" ("recorded_at");
CREATE INDEX ON "connection_events" ("device_id", "occurred_at");
CREATE INDEX ON "device_commands" ("device_id", "status", "created_at");
CREATE INDEX ON "alerts" ("alert_rule_id", "device_id", "channel_id");
CREATE INDEX ON "alerts" ("status", "opened_at");
CREATE INDEX ON "alert_events" ("alert_id", "occurred_at");
CREATE UNIQUE INDEX ON "firmware_releases" ("device_model_id", "version");
CREATE UNIQUE INDEX ON "firmware_releases" ("device_model_id", "build_number");
CREATE UNIQUE INDEX ON "rollout_stages" ("rollout_id", "stage_number");
CREATE INDEX ON "rollout_devices" ("rollout_stage_id", "status");
COMMENT ON TABLE "tenants" IS 'Customer organizations. Every device, rule and rollout belongs to exactly one, and row-level security keys on tenant_id.';
COMMENT ON COLUMN "tenants"."rollup_retention_days" IS 'How long hourly rollups are kept. Raw readings follow the global partition retention';
COMMENT ON COLUMN "tenants"."timezone" IS 'IANA zone; daily reports bucket by it';
COMMENT ON TABLE "sites" IS 'Physical places devices are installed: a plant, a building, a farm.';
COMMENT ON COLUMN "sites"."timezone" IS 'Maintenance windows are in site local time';
COMMENT ON TABLE "users" IS 'People in a tenant: who acknowledges alerts, sends commands and starts rollouts.';
COMMENT ON TABLE "device_models" IS 'Hardware types. A model defines which channels its devices have and which firmware they can run.';
COMMENT ON COLUMN "device_models"."heartbeat_interval_s" IS 'Expected check-in interval. Offline means "no heartbeat for 3 intervals", not one fixed timeout';
COMMENT ON TABLE "devices" IS 'One physical unit in the field. Gateways are devices too, so credentials, heartbeats, commands and firmware rollouts all apply to them unchanged.';
COMMENT ON COLUMN "devices"."site_id" IS 'Null while in stock or in transit';
COMMENT ON COLUMN "devices"."gateway_device_id" IS 'The gateway it reports through; null for devices that connect directly';
COMMENT ON COLUMN "devices"."current_firmware_id" IS 'REPORTED by the device on connect. What it should run is decided by rollouts';
COMMENT ON COLUMN "devices"."last_seen_at" IS 'CACHE of the latest heartbeat or reading';
COMMENT ON COLUMN "devices"."labels" IS 'Free-form key values, e.g. {"line": "3", "floor": "B2"}';
COMMENT ON TABLE "gateways" IS 'Extra attributes for the devices that are gateways: a one-to-one subtype of devices. Child devices point here.';
COMMENT ON COLUMN "gateways"."backhaul" IS 'How the gateway itself reaches the cloud';
COMMENT ON COLUMN "gateways"."buffer_capacity_hours" IS 'How long it can hold readings while offline. Buffered readings arrive late, with their original recorded_at';
COMMENT ON TABLE "device_credentials" IS 'Certificates and keys a device authenticates with. Rotation overlaps: the new credential is issued and seen in use before the old one is revoked, so a device is never locked out mid-rotation.';
COMMENT ON COLUMN "device_credentials"."fingerprint" IS 'SHA-256 of the certificate or public key; what the broker looks up on connect';
COMMENT ON COLUMN "device_credentials"."certificate_pem" IS 'Public certificate only. Private keys never leave the device';
COMMENT ON COLUMN "device_credentials"."replaces_credential_id" IS 'Rotation chain: the credential this one supersedes';
COMMENT ON TABLE "device_groups" IS 'Named sets of devices, e.g. "pilot line" or "cold rooms", used to target rollouts and scope alert rules.';
COMMENT ON TABLE "device_group_members" IS 'Group membership. A device can be in many groups.';
COMMENT ON TABLE "model_channels" IS 'The channels a model has: the template every device of that model is created with.';
COMMENT ON COLUMN "model_channels"."key" IS 'Stable identifier in the payload, e.g. temp_c, rh_pct, door_open';
COMMENT ON COLUMN "model_channels"."unit" IS 'UCUM unit code, e.g. Cel, %, kW.h. Values are always stored in this unit';
COMMENT ON COLUMN "model_channels"."min_valid" IS 'Physical range of the sensor. Outside it a reading is flagged, not dropped';
COMMENT ON TABLE "channels" IS 'One sensor on one physical device, and the key every reading is filed under. Calibration lives here because two sensors of the same model never read identically.';
COMMENT ON COLUMN "channels"."calibration_scale" IS 'Stored value = raw * scale + offset, applied at ingest';
COMMENT ON COLUMN "channels"."last_value" IS 'CACHE of the newest reading, for device lists and map pins';
COMMENT ON TABLE "telemetry_readings" IS 'Raw readings: narrow, append-only, never updated.
PARTITION BY RANGE (recorded_at), one partition per day or week, created ahead of time by a job. Retention is DROP PARTITION, which is instant, instead of a DELETE that bloats the table.
No surrogate id: at billions of rows a uuid per reading costs more than the reading itself.';
COMMENT ON COLUMN "telemetry_readings"."recorded_at" IS 'Device clock, when it was measured. The partition key';
COMMENT ON COLUMN "telemetry_readings"."received_at" IS 'Server clock. A large gap means it was buffered offline';
COMMENT ON COLUMN "telemetry_readings"."value" IS 'Booleans are 0 or 1; enumerated states use their numeric code';
COMMENT ON TABLE "telemetry_hourly" IS 'Hourly rollup per channel. Every chart wider than a few hours reads here, never from raw readings.';
COMMENT ON COLUMN "telemetry_hourly"."sum_value" IS 'A sum, not an average: averages of averages are wrong, while sums and counts roll up to days exactly';
COMMENT ON COLUMN "telemetry_hourly"."computed_at" IS 'Late readings for this hour (received_at after this) trigger a recompute of just this row';
COMMENT ON TABLE "connection_events" IS 'Connects, disconnects and failed authentications, from the broker. Uptime reports are computed from these.';
COMMENT ON COLUMN "connection_events"."credential_id" IS 'Which credential it presented. Repeated failures with a revoked one deserve an alert';
COMMENT ON COLUMN "connection_events"."protocol" IS 'e.g. mqtt, coap, https';
COMMENT ON COLUMN "connection_events"."reason" IS 'Disconnect or failure reason as reported by the broker';
COMMENT ON TABLE "device_heartbeats" IS 'Periodic health check-ins. Partitioned by time like readings, with shorter retention; devices.last_seen_at caches the latest.';
COMMENT ON COLUMN "device_heartbeats"."signal_dbm" IS 'Received signal strength. Trending it finds devices about to drop off';
COMMENT ON COLUMN "device_heartbeats"."uptime_s" IS 'Seconds since boot. A drop to near zero means an unplanned reboot';
COMMENT ON COLUMN "device_heartbeats"."firmware_version" IS 'As reported; devices.current_firmware_id is updated from it';
COMMENT ON TABLE "device_commands" IS 'Cloud-to-device commands as a state machine: queued, sent, delivered, acknowledged, or failed, or expired.
Each transition stamps its own column, so where a command stalled is visible. Devices are often asleep or offline, which is why queued and expired exist at all.';
COMMENT ON COLUMN "device_commands"."command" IS 'e.g. reboot, set_sample_interval, open_valve';
COMMENT ON COLUMN "device_commands"."issued_by" IS 'Null for commands issued by automation';
COMMENT ON COLUMN "device_commands"."alert_id" IS 'Set when an alert triggered it';
COMMENT ON COLUMN "device_commands"."message_id" IS 'Sent with the command and echoed back in the ack, so a duplicate ack is recognised';
COMMENT ON COLUMN "device_commands"."expires_at" IS 'Never sent after this. A reboot queued for an offline device must not fire three days later';
COMMENT ON COLUMN "device_commands"."result" IS 'What the device reported back';
COMMENT ON TABLE "notification_targets" IS 'Where alerts can be sent: email, SMS, webhooks, on-call tools.';
COMMENT ON COLUMN "notification_targets"."address" IS 'Email address, phone number, or webhook URL';
COMMENT ON COLUMN "notification_targets"."user_id" IS 'Set when the target is a person rather than a shared channel';
COMMENT ON TABLE "alert_rules" IS 'Thresholds, rate-of-change and no-data rules (the offline detector). Written once against a model channel, evaluated on every matching device.';
COMMENT ON COLUMN "alert_rules"."model_channel_id" IS 'Which channel type the rule watches, e.g. temp_c on one model';
COMMENT ON COLUMN "alert_rules"."device_group_id" IS 'Scope; null for every matching device in the tenant';
COMMENT ON COLUMN "alert_rules"."operator" IS 'Threshold rules only';
COMMENT ON COLUMN "alert_rules"."threshold" IS 'Threshold rules only, in the channel unit';
COMMENT ON COLUMN "alert_rules"."clear_threshold" IS 'Hysteresis: the alert resolves only past this value, so a reading hovering at the threshold does not flap';
COMMENT ON COLUMN "alert_rules"."for_seconds" IS 'The condition must hold this long before an alert opens';
COMMENT ON TABLE "alert_rule_targets" IS 'Who hears about which rule, and when. Escalation is just a second target with a delay.';
COMMENT ON COLUMN "alert_rule_targets"."escalate_after_minutes" IS 'Null notifies at once; a value notifies only if still unacknowledged after that long';
COMMENT ON TABLE "alerts" IS 'Incidents: open, then acknowledged, then resolved.';
COMMENT ON COLUMN "alerts"."channel_id" IS 'Null for device-level rules such as no data';
COMMENT ON COLUMN "alerts"."severity" IS 'Copied from the rule when opened, so editing the rule never rewrites history';
COMMENT ON COLUMN "alerts"."peak_value" IS 'Worst value seen while open';
COMMENT ON COLUMN "alerts"."resolved_by" IS 'Null when it cleared automatically';
COMMENT ON TABLE "alert_events" IS 'The timeline of an alert. alerts holds its current state; this holds how it got there, for the postmortem.';
COMMENT ON COLUMN "alert_events"."notification_target_id" IS 'For notified and escalated events: where it was sent';
COMMENT ON TABLE "firmware_releases" IS 'Firmware images, per hardware model.';
COMMENT ON COLUMN "firmware_releases"."version" IS 'Semantic version, e.g. 2.4.1';
COMMENT ON COLUMN "firmware_releases"."build_number" IS 'Monotonic. Ordering by it is safe where ordering version strings is not';
COMMENT ON COLUMN "firmware_releases"."storage_key" IS 'Object storage key of the image. Devices download it through a short-lived signed URL';
COMMENT ON COLUMN "firmware_releases"."sha256" IS 'The device verifies the image before flashing it';
COMMENT ON COLUMN "firmware_releases"."signature" IS 'Signed by the build pipeline; the bootloader refuses unsigned images';
COMMENT ON COLUMN "firmware_releases"."min_from_build" IS 'Oldest build that can upgrade straight to this one; older devices need a stepping-stone release';
COMMENT ON COLUMN "firmware_releases"."revoked_at" IS 'Pulled after release. Running rollouts of it are aborted';
COMMENT ON TABLE "firmware_rollouts" IS 'A planned upgrade of many devices to one release, in stages. This is the intent; rollout_devices records what actually happened on each unit.';
COMMENT ON COLUMN "firmware_rollouts"."device_group_id" IS 'Target; null for every eligible device of the model in the tenant';
COMMENT ON COLUMN "firmware_rollouts"."max_failure_pct" IS 'Pause automatically when a stage fails more than this';
COMMENT ON COLUMN "firmware_rollouts"."maintenance_window" IS 'Site-local hours devices may install in, e.g. {"days": [1,2,3,4,5], "from": "02:00", "to": "04:00"}';
COMMENT ON TABLE "rollout_stages" IS 'Canary first, then wider. A stage starts only after the previous one soaked without crossing the failure threshold.';
COMMENT ON COLUMN "rollout_stages"."target_pct" IS 'Cumulative share of the target devices, e.g. 1, 10, 50, 100';
COMMENT ON COLUMN "rollout_stages"."soak_minutes" IS 'How long to watch a stage before the next may start';
COMMENT ON TABLE "rollout_devices" IS 'Per-device progress of a rollout. Success is confirmed by the device reporting the new version on reconnect, not by the download finishing.';
COMMENT ON COLUMN "rollout_devices"."from_firmware_id" IS 'What it ran before, for rollback';
ALTER TABLE "sites" ADD FOREIGN KEY ("tenant_id") REFERENCES "tenants" ("id");
ALTER TABLE "users" ADD FOREIGN KEY ("tenant_id") REFERENCES "tenants" ("id");
ALTER TABLE "devices" ADD FOREIGN KEY ("tenant_id") REFERENCES "tenants" ("id");
ALTER TABLE "devices" ADD FOREIGN KEY ("site_id") REFERENCES "sites" ("id");
ALTER TABLE "devices" ADD FOREIGN KEY ("device_model_id") REFERENCES "device_models" ("id");
ALTER TABLE "devices" ADD FOREIGN KEY ("gateway_device_id") REFERENCES "gateways" ("device_id");
ALTER TABLE "devices" ADD FOREIGN KEY ("current_firmware_id") REFERENCES "firmware_releases" ("id");
ALTER TABLE "gateways" ADD FOREIGN KEY ("device_id") REFERENCES "devices" ("id");
ALTER TABLE "device_credentials" ADD FOREIGN KEY ("device_id") REFERENCES "devices" ("id");
ALTER TABLE "device_credentials" ADD FOREIGN KEY ("replaces_credential_id") REFERENCES "device_credentials" ("id");
ALTER TABLE "device_groups" ADD FOREIGN KEY ("tenant_id") REFERENCES "tenants" ("id");
ALTER TABLE "device_group_members" ADD FOREIGN KEY ("device_group_id") REFERENCES "device_groups" ("id");
ALTER TABLE "device_group_members" ADD FOREIGN KEY ("device_id") REFERENCES "devices" ("id");
ALTER TABLE "model_channels" ADD FOREIGN KEY ("device_model_id") REFERENCES "device_models" ("id");
ALTER TABLE "channels" ADD FOREIGN KEY ("device_id") REFERENCES "devices" ("id");
ALTER TABLE "channels" ADD FOREIGN KEY ("model_channel_id") REFERENCES "model_channels" ("id");
ALTER TABLE "telemetry_readings" ADD FOREIGN KEY ("channel_id") REFERENCES "channels" ("id");
ALTER TABLE "telemetry_hourly" ADD FOREIGN KEY ("channel_id") REFERENCES "channels" ("id");
ALTER TABLE "connection_events" ADD FOREIGN KEY ("device_id") REFERENCES "devices" ("id");
ALTER TABLE "connection_events" ADD FOREIGN KEY ("via_gateway_id") REFERENCES "gateways" ("device_id");
ALTER TABLE "connection_events" ADD FOREIGN KEY ("credential_id") REFERENCES "device_credentials" ("id");
ALTER TABLE "device_heartbeats" ADD FOREIGN KEY ("device_id") REFERENCES "devices" ("id");
ALTER TABLE "device_commands" ADD FOREIGN KEY ("device_id") REFERENCES "devices" ("id");
ALTER TABLE "device_commands" ADD FOREIGN KEY ("issued_by") REFERENCES "users" ("id");
ALTER TABLE "device_commands" ADD FOREIGN KEY ("alert_id") REFERENCES "alerts" ("id");
ALTER TABLE "notification_targets" ADD FOREIGN KEY ("tenant_id") REFERENCES "tenants" ("id");
ALTER TABLE "notification_targets" ADD FOREIGN KEY ("user_id") REFERENCES "users" ("id");
ALTER TABLE "alert_rules" ADD FOREIGN KEY ("tenant_id") REFERENCES "tenants" ("id");
ALTER TABLE "alert_rules" ADD FOREIGN KEY ("model_channel_id") REFERENCES "model_channels" ("id");
ALTER TABLE "alert_rules" ADD FOREIGN KEY ("device_group_id") REFERENCES "device_groups" ("id");
ALTER TABLE "alert_rules" ADD FOREIGN KEY ("created_by") REFERENCES "users" ("id");
ALTER TABLE "alert_rule_targets" ADD FOREIGN KEY ("alert_rule_id") REFERENCES "alert_rules" ("id");
ALTER TABLE "alert_rule_targets" ADD FOREIGN KEY ("notification_target_id") REFERENCES "notification_targets" ("id");
ALTER TABLE "alerts" ADD FOREIGN KEY ("alert_rule_id") REFERENCES "alert_rules" ("id");
ALTER TABLE "alerts" ADD FOREIGN KEY ("device_id") REFERENCES "devices" ("id");
ALTER TABLE "alerts" ADD FOREIGN KEY ("channel_id") REFERENCES "channels" ("id");
ALTER TABLE "alerts" ADD FOREIGN KEY ("acknowledged_by") REFERENCES "users" ("id");
ALTER TABLE "alerts" ADD FOREIGN KEY ("resolved_by") REFERENCES "users" ("id");
ALTER TABLE "alert_events" ADD FOREIGN KEY ("alert_id") REFERENCES "alerts" ("id");
ALTER TABLE "alert_events" ADD FOREIGN KEY ("user_id") REFERENCES "users" ("id");
ALTER TABLE "alert_events" ADD FOREIGN KEY ("notification_target_id") REFERENCES "notification_targets" ("id");
ALTER TABLE "firmware_releases" ADD FOREIGN KEY ("device_model_id") REFERENCES "device_models" ("id");
ALTER TABLE "firmware_rollouts" ADD FOREIGN KEY ("tenant_id") REFERENCES "tenants" ("id");
ALTER TABLE "firmware_rollouts" ADD FOREIGN KEY ("firmware_release_id") REFERENCES "firmware_releases" ("id");
ALTER TABLE "firmware_rollouts" ADD FOREIGN KEY ("device_group_id") REFERENCES "device_groups" ("id");
ALTER TABLE "firmware_rollouts" ADD FOREIGN KEY ("created_by") REFERENCES "users" ("id");
ALTER TABLE "rollout_stages" ADD FOREIGN KEY ("rollout_id") REFERENCES "firmware_rollouts" ("id");
ALTER TABLE "rollout_devices" ADD FOREIGN KEY ("rollout_id") REFERENCES "firmware_rollouts" ("id");
ALTER TABLE "rollout_devices" ADD FOREIGN KEY ("device_id") REFERENCES "devices" ("id");
ALTER TABLE "rollout_devices" ADD FOREIGN KEY ("rollout_stage_id") REFERENCES "rollout_stages" ("id");
ALTER TABLE "rollout_devices" ADD FOREIGN KEY ("from_firmware_id") REFERENCES "firmware_releases" ("id");MySQL
CREATE TABLE `tenants` (
`id` uuid PRIMARY KEY,
`name` varchar(200) NOT NULL,
`slug` varchar(60) UNIQUE NOT NULL,
`plan` ENUM ('starter', 'professional', 'enterprise') NOT NULL,
`rollup_retention_days` integer NOT NULL DEFAULT 730 COMMENT 'How long hourly rollups are kept. Raw readings follow the global partition retention',
`timezone` varchar(64) NOT NULL COMMENT 'IANA zone; daily reports bucket by it',
`created_at` timestamptz NOT NULL DEFAULT (now())
);
CREATE TABLE `sites` (
`id` uuid PRIMARY KEY,
`tenant_id` uuid NOT NULL,
`name` varchar(200) NOT NULL,
`address` varchar(300),
`latitude` numeric(9,6),
`longitude` numeric(9,6),
`timezone` varchar(64) NOT NULL COMMENT 'Maintenance windows are in site local time'
);
CREATE TABLE `users` (
`id` uuid PRIMARY KEY,
`tenant_id` uuid NOT NULL,
`email` varchar(254) UNIQUE NOT NULL,
`name` varchar(200) NOT NULL,
`role` ENUM ('viewer', 'operator', 'admin') NOT NULL,
`created_at` timestamptz NOT NULL DEFAULT (now()),
`disabled_at` timestamptz
);
CREATE TABLE `device_models` (
`id` uuid PRIMARY KEY,
`manufacturer` varchar(120) NOT NULL,
`model_number` varchar(60) NOT NULL,
`name` varchar(200) NOT NULL,
`kind` ENUM ('sensor', 'actuator', 'meter', 'controller', 'gateway') NOT NULL,
`connectivity` ENUM ('wifi', 'ethernet', 'cellular', 'lpwan', 'mesh_radio', 'via_gateway') NOT NULL,
`battery_powered` boolean NOT NULL DEFAULT false,
`heartbeat_interval_s` integer NOT NULL DEFAULT 60 COMMENT 'Expected check-in interval. Offline means "no heartbeat for 3 intervals", not one fixed timeout'
);
CREATE TABLE `devices` (
`id` uuid PRIMARY KEY,
`tenant_id` uuid NOT NULL,
`site_id` uuid COMMENT 'Null while in stock or in transit',
`device_model_id` uuid NOT NULL,
`serial_number` varchar(64) NOT NULL,
`name` varchar(200),
`gateway_device_id` uuid COMMENT 'The gateway it reports through; null for devices that connect directly',
`current_firmware_id` uuid COMMENT 'REPORTED by the device on connect. What it should run is decided by rollouts',
`status` ENUM ('provisioned', 'active', 'inactive', 'maintenance', 'decommissioned') NOT NULL DEFAULT 'provisioned',
`last_seen_at` timestamptz COMMENT 'CACHE of the latest heartbeat or reading',
`installed_at` timestamptz,
`decommissioned_at` timestamptz,
`labels` jsonb COMMENT 'Free-form key values, e.g. {"line": "3", "floor": "B2"}'
);
CREATE TABLE `gateways` (
`device_id` uuid PRIMARY KEY,
`backhaul` ENUM ('ethernet', 'wifi', 'cellular', 'satellite') NOT NULL COMMENT 'How the gateway itself reaches the cloud',
`buffer_capacity_hours` integer NOT NULL COMMENT 'How long it can hold readings while offline. Buffered readings arrive late, with their original recorded_at',
`max_child_devices` integer,
`lan_ip` inet
);
CREATE TABLE `device_credentials` (
`id` uuid PRIMARY KEY,
`device_id` uuid NOT NULL,
`kind` ENUM ('x509_certificate', 'raw_public_key', 'symmetric_key') NOT NULL,
`fingerprint` char(64) UNIQUE NOT NULL COMMENT 'SHA-256 of the certificate or public key; what the broker looks up on connect',
`certificate_pem` text COMMENT 'Public certificate only. Private keys never leave the device',
`issued_at` timestamptz NOT NULL DEFAULT (now()),
`not_before` timestamptz NOT NULL,
`expires_at` timestamptz NOT NULL,
`revoked_at` timestamptz,
`revoke_reason` varchar(200),
`replaces_credential_id` uuid COMMENT 'Rotation chain: the credential this one supersedes'
);
CREATE TABLE `device_groups` (
`id` uuid PRIMARY KEY,
`tenant_id` uuid NOT NULL,
`name` varchar(120) NOT NULL,
`description` varchar(500)
);
CREATE TABLE `device_group_members` (
`device_group_id` uuid NOT NULL,
`device_id` uuid NOT NULL,
`added_at` timestamptz NOT NULL DEFAULT (now()),
PRIMARY KEY (`device_group_id`, `device_id`)
);
CREATE TABLE `model_channels` (
`id` uuid PRIMARY KEY,
`device_model_id` uuid NOT NULL,
`key` varchar(60) NOT NULL COMMENT 'Stable identifier in the payload, e.g. temp_c, rh_pct, door_open',
`name` varchar(120) NOT NULL,
`unit` varchar(20) NOT NULL COMMENT 'UCUM unit code, e.g. Cel, %, kW.h. Values are always stored in this unit',
`value_kind` ENUM ('gauge', 'counter', 'boolean', 'state') NOT NULL,
`min_valid` float8 COMMENT 'Physical range of the sensor. Outside it a reading is flagged, not dropped',
`max_valid` float8,
`sample_interval_s` integer
);
CREATE TABLE `channels` (
`id` uuid PRIMARY KEY,
`device_id` uuid NOT NULL,
`model_channel_id` uuid NOT NULL,
`calibration_offset` float8 NOT NULL DEFAULT 0,
`calibration_scale` float8 NOT NULL DEFAULT 1 COMMENT 'Stored value = raw * scale + offset, applied at ingest',
`is_enabled` boolean NOT NULL DEFAULT true,
`last_value` float8 COMMENT 'CACHE of the newest reading, for device lists and map pins',
`last_recorded_at` timestamptz
);
CREATE TABLE `telemetry_readings` (
`channel_id` uuid NOT NULL,
`recorded_at` timestamptz NOT NULL COMMENT 'Device clock, when it was measured. The partition key',
`received_at` timestamptz NOT NULL DEFAULT (now()) COMMENT 'Server clock. A large gap means it was buffered offline',
`value` float8 NOT NULL COMMENT 'Booleans are 0 or 1; enumerated states use their numeric code',
`quality` ENUM ('good', 'out_of_range', 'estimated', 'sensor_fault') NOT NULL DEFAULT 'good',
PRIMARY KEY (`channel_id`, `recorded_at`)
);
CREATE TABLE `telemetry_hourly` (
`channel_id` uuid NOT NULL,
`hour_start` timestamptz NOT NULL,
`sample_count` integer NOT NULL,
`min_value` float8 NOT NULL,
`max_value` float8 NOT NULL,
`sum_value` float8 NOT NULL COMMENT 'A sum, not an average: averages of averages are wrong, while sums and counts roll up to days exactly',
`first_value` float8,
`last_value` float8,
`computed_at` timestamptz NOT NULL COMMENT 'Late readings for this hour (received_at after this) trigger a recompute of just this row',
PRIMARY KEY (`channel_id`, `hour_start`)
);
CREATE TABLE `connection_events` (
`id` uuid PRIMARY KEY,
`device_id` uuid NOT NULL,
`kind` ENUM ('connected', 'disconnected', 'keepalive_timeout', 'auth_failed') NOT NULL,
`occurred_at` timestamptz NOT NULL,
`via_gateway_id` uuid,
`credential_id` uuid COMMENT 'Which credential it presented. Repeated failures with a revoked one deserve an alert',
`remote_ip` inet,
`protocol` varchar(20) COMMENT 'e.g. mqtt, coap, https',
`reason` varchar(200) COMMENT 'Disconnect or failure reason as reported by the broker'
);
CREATE TABLE `device_heartbeats` (
`device_id` uuid NOT NULL,
`received_at` timestamptz NOT NULL,
`battery_pct` smallint,
`signal_dbm` smallint COMMENT 'Received signal strength. Trending it finds devices about to drop off',
`uptime_s` bigint COMMENT 'Seconds since boot. A drop to near zero means an unplanned reboot',
`free_memory_kb` integer,
`firmware_version` varchar(40) COMMENT 'As reported; devices.current_firmware_id is updated from it',
PRIMARY KEY (`device_id`, `received_at`)
);
CREATE TABLE `device_commands` (
`id` uuid PRIMARY KEY,
`device_id` uuid NOT NULL,
`command` varchar(60) NOT NULL COMMENT 'e.g. reboot, set_sample_interval, open_valve',
`payload` jsonb,
`status` ENUM ('queued', 'sent', 'delivered', 'acknowledged', 'failed', 'expired') NOT NULL DEFAULT 'queued',
`issued_by` uuid COMMENT 'Null for commands issued by automation',
`alert_id` uuid COMMENT 'Set when an alert triggered it',
`message_id` uuid UNIQUE NOT NULL COMMENT 'Sent with the command and echoed back in the ack, so a duplicate ack is recognised',
`attempts` smallint NOT NULL DEFAULT 0,
`created_at` timestamptz NOT NULL DEFAULT (now()),
`sent_at` timestamptz,
`delivered_at` timestamptz,
`acknowledged_at` timestamptz,
`failed_at` timestamptz,
`expires_at` timestamptz NOT NULL COMMENT 'Never sent after this. A reboot queued for an offline device must not fire three days later',
`result` jsonb COMMENT 'What the device reported back',
`error_message` varchar(500)
);
CREATE TABLE `notification_targets` (
`id` uuid PRIMARY KEY,
`tenant_id` uuid NOT NULL,
`kind` ENUM ('email', 'sms', 'webhook', 'on_call') NOT NULL,
`address` varchar(500) NOT NULL COMMENT 'Email address, phone number, or webhook URL',
`user_id` uuid COMMENT 'Set when the target is a person rather than a shared channel',
`verified_at` timestamptz
);
CREATE TABLE `alert_rules` (
`id` uuid PRIMARY KEY,
`tenant_id` uuid NOT NULL,
`name` varchar(200) NOT NULL,
`kind` ENUM ('threshold', 'rate_of_change', 'no_data') NOT NULL,
`model_channel_id` uuid NOT NULL COMMENT 'Which channel type the rule watches, e.g. temp_c on one model',
`device_group_id` uuid COMMENT 'Scope; null for every matching device in the tenant',
`operator` ENUM ('gt', 'gte', 'lt', 'lte', 'eq', 'neq') COMMENT 'Threshold rules only',
`threshold` float8 COMMENT 'Threshold rules only, in the channel unit',
`clear_threshold` float8 COMMENT 'Hysteresis: the alert resolves only past this value, so a reading hovering at the threshold does not flap',
`for_seconds` integer NOT NULL DEFAULT 0 COMMENT 'The condition must hold this long before an alert opens',
`severity` ENUM ('info', 'warning', 'critical') NOT NULL,
`is_enabled` boolean NOT NULL DEFAULT true,
`created_by` uuid,
`created_at` timestamptz NOT NULL DEFAULT (now())
);
CREATE TABLE `alert_rule_targets` (
`alert_rule_id` uuid NOT NULL,
`notification_target_id` uuid NOT NULL,
`escalate_after_minutes` integer COMMENT 'Null notifies at once; a value notifies only if still unacknowledged after that long',
PRIMARY KEY (`alert_rule_id`, `notification_target_id`)
);
CREATE TABLE `alerts` (
`id` uuid PRIMARY KEY,
`alert_rule_id` uuid NOT NULL,
`device_id` uuid NOT NULL,
`channel_id` uuid COMMENT 'Null for device-level rules such as no data',
`status` ENUM ('open', 'acknowledged', 'resolved') NOT NULL DEFAULT 'open',
`severity` ENUM ('info', 'warning', 'critical') NOT NULL COMMENT 'Copied from the rule when opened, so editing the rule never rewrites history',
`trigger_value` float8,
`peak_value` float8 COMMENT 'Worst value seen while open',
`opened_at` timestamptz NOT NULL,
`last_triggered_at` timestamptz NOT NULL,
`acknowledged_at` timestamptz,
`acknowledged_by` uuid,
`resolved_at` timestamptz,
`resolved_by` uuid COMMENT 'Null when it cleared automatically',
`resolution_comment` varchar(1000)
);
CREATE TABLE `alert_events` (
`id` uuid PRIMARY KEY,
`alert_id` uuid NOT NULL,
`kind` ENUM ('opened', 'retriggered', 'notified', 'escalated', 'acknowledged', 'resolved', 'auto_resolved') NOT NULL,
`occurred_at` timestamptz NOT NULL DEFAULT (now()),
`user_id` uuid,
`notification_target_id` uuid COMMENT 'For notified and escalated events: where it was sent',
`value` float8,
`details` jsonb
);
CREATE TABLE `firmware_releases` (
`id` uuid PRIMARY KEY,
`device_model_id` uuid NOT NULL,
`version` varchar(40) NOT NULL COMMENT 'Semantic version, e.g. 2.4.1',
`build_number` integer NOT NULL COMMENT 'Monotonic. Ordering by it is safe where ordering version strings is not',
`release_channel` ENUM ('development', 'beta', 'stable') NOT NULL,
`storage_key` varchar(300) NOT NULL COMMENT 'Object storage key of the image. Devices download it through a short-lived signed URL',
`size_bytes` bigint NOT NULL,
`sha256` char(64) NOT NULL COMMENT 'The device verifies the image before flashing it',
`signature` text NOT NULL COMMENT 'Signed by the build pipeline; the bootloader refuses unsigned images',
`min_from_build` integer COMMENT 'Oldest build that can upgrade straight to this one; older devices need a stepping-stone release',
`release_notes` text,
`released_at` timestamptz,
`revoked_at` timestamptz COMMENT 'Pulled after release. Running rollouts of it are aborted'
);
CREATE TABLE `firmware_rollouts` (
`id` uuid PRIMARY KEY,
`tenant_id` uuid NOT NULL,
`firmware_release_id` uuid NOT NULL,
`device_group_id` uuid COMMENT 'Target; null for every eligible device of the model in the tenant',
`name` varchar(200) NOT NULL,
`status` ENUM ('draft', 'running', 'paused', 'completed', 'aborted') NOT NULL DEFAULT 'draft',
`max_failure_pct` numeric(5,2) NOT NULL DEFAULT 2 COMMENT 'Pause automatically when a stage fails more than this',
`maintenance_window` jsonb COMMENT 'Site-local hours devices may install in, e.g. {"days": [1,2,3,4,5], "from": "02:00", "to": "04:00"}',
`created_by` uuid NOT NULL,
`created_at` timestamptz NOT NULL DEFAULT (now()),
`started_at` timestamptz,
`completed_at` timestamptz
);
CREATE TABLE `rollout_stages` (
`id` uuid PRIMARY KEY,
`rollout_id` uuid NOT NULL,
`stage_number` smallint NOT NULL,
`target_pct` numeric(5,2) NOT NULL COMMENT 'Cumulative share of the target devices, e.g. 1, 10, 50, 100',
`soak_minutes` integer NOT NULL DEFAULT 1440 COMMENT 'How long to watch a stage before the next may start',
`started_at` timestamptz,
`completed_at` timestamptz
);
CREATE TABLE `rollout_devices` (
`rollout_id` uuid NOT NULL,
`device_id` uuid NOT NULL,
`rollout_stage_id` uuid NOT NULL,
`from_firmware_id` uuid COMMENT 'What it ran before, for rollback',
`status` ENUM ('pending', 'downloading', 'installing', 'succeeded', 'failed', 'rolled_back', 'skipped') NOT NULL DEFAULT 'pending',
`attempts` smallint NOT NULL DEFAULT 0,
`last_attempt_at` timestamptz,
`completed_at` timestamptz,
`error_code` varchar(60),
PRIMARY KEY (`rollout_id`, `device_id`)
);
CREATE UNIQUE INDEX `sites_index_0` ON `sites` (`tenant_id`, `name`);
CREATE UNIQUE INDEX `device_models_index_1` ON `device_models` (`manufacturer`, `model_number`);
CREATE UNIQUE INDEX `devices_index_2` ON `devices` (`device_model_id`, `serial_number`);
CREATE INDEX `devices_index_3` ON `devices` (`tenant_id`, `site_id`);
CREATE INDEX `device_credentials_index_4` ON `device_credentials` (`device_id`, `expires_at`);
CREATE INDEX `device_credentials_index_5` ON `device_credentials` (`expires_at`);
CREATE UNIQUE INDEX `device_groups_index_6` ON `device_groups` (`tenant_id`, `name`);
CREATE UNIQUE INDEX `model_channels_index_7` ON `model_channels` (`device_model_id`, `key`);
CREATE UNIQUE INDEX `channels_index_8` ON `channels` (`device_id`, `model_channel_id`);
CREATE INDEX `telemetry_readings_index_9` ON `telemetry_readings` (`recorded_at`);
CREATE INDEX `connection_events_index_10` ON `connection_events` (`device_id`, `occurred_at`);
CREATE INDEX `device_commands_index_11` ON `device_commands` (`device_id`, `status`, `created_at`);
CREATE INDEX `alerts_index_12` ON `alerts` (`alert_rule_id`, `device_id`, `channel_id`);
CREATE INDEX `alerts_index_13` ON `alerts` (`status`, `opened_at`);
CREATE INDEX `alert_events_index_14` ON `alert_events` (`alert_id`, `occurred_at`);
CREATE UNIQUE INDEX `firmware_releases_index_15` ON `firmware_releases` (`device_model_id`, `version`);
CREATE UNIQUE INDEX `firmware_releases_index_16` ON `firmware_releases` (`device_model_id`, `build_number`);
CREATE UNIQUE INDEX `rollout_stages_index_17` ON `rollout_stages` (`rollout_id`, `stage_number`);
CREATE INDEX `rollout_devices_index_18` ON `rollout_devices` (`rollout_stage_id`, `status`);
ALTER TABLE `tenants` COMMENT = 'Customer organizations. Every device, rule and rollout belongs to exactly one, and row-level security keys on tenant_id.';
ALTER TABLE `sites` COMMENT = 'Physical places devices are installed: a plant, a building, a farm.';
ALTER TABLE `users` COMMENT = 'People in a tenant: who acknowledges alerts, sends commands and starts rollouts.';
ALTER TABLE `device_models` COMMENT = 'Hardware types. A model defines which channels its devices have and which firmware they can run.';
ALTER TABLE `devices` COMMENT = 'One physical unit in the field. Gateways are devices too, so credentials, heartbeats, commands and firmware rollouts all apply to them unchanged.';
ALTER TABLE `gateways` COMMENT = 'Extra attributes for the devices that are gateways: a one-to-one subtype of devices. Child devices point here.';
ALTER TABLE `device_credentials` COMMENT = 'Certificates and keys a device authenticates with. Rotation overlaps: the new credential is issued and seen in use before the old one is revoked, so a device is never locked out mid-rotation.';
ALTER TABLE `device_groups` COMMENT = 'Named sets of devices, e.g. "pilot line" or "cold rooms", used to target rollouts and scope alert rules.';
ALTER TABLE `device_group_members` COMMENT = 'Group membership. A device can be in many groups.';
ALTER TABLE `model_channels` COMMENT = 'The channels a model has: the template every device of that model is created with.';
ALTER TABLE `channels` COMMENT = 'One sensor on one physical device, and the key every reading is filed under. Calibration lives here because two sensors of the same model never read identically.';
ALTER TABLE `telemetry_readings` COMMENT = 'Raw readings: narrow, append-only, never updated.
PARTITION BY RANGE (recorded_at), one partition per day or week, created ahead of time by a job. Retention is DROP PARTITION, which is instant, instead of a DELETE that bloats the table.
No surrogate id: at billions of rows a uuid per reading costs more than the reading itself.';
ALTER TABLE `telemetry_hourly` COMMENT = 'Hourly rollup per channel. Every chart wider than a few hours reads here, never from raw readings.';
ALTER TABLE `connection_events` COMMENT = 'Connects, disconnects and failed authentications, from the broker. Uptime reports are computed from these.';
ALTER TABLE `device_heartbeats` COMMENT = 'Periodic health check-ins. Partitioned by time like readings, with shorter retention; devices.last_seen_at caches the latest.';
ALTER TABLE `device_commands` COMMENT = 'Cloud-to-device commands as a state machine: queued, sent, delivered, acknowledged, or failed, or expired.
Each transition stamps its own column, so where a command stalled is visible. Devices are often asleep or offline, which is why queued and expired exist at all.';
ALTER TABLE `notification_targets` COMMENT = 'Where alerts can be sent: email, SMS, webhooks, on-call tools.';
ALTER TABLE `alert_rules` COMMENT = 'Thresholds, rate-of-change and no-data rules (the offline detector). Written once against a model channel, evaluated on every matching device.';
ALTER TABLE `alert_rule_targets` COMMENT = 'Who hears about which rule, and when. Escalation is just a second target with a delay.';
ALTER TABLE `alerts` COMMENT = 'Incidents: open, then acknowledged, then resolved.';
ALTER TABLE `alert_events` COMMENT = 'The timeline of an alert. alerts holds its current state; this holds how it got there, for the postmortem.';
ALTER TABLE `firmware_releases` COMMENT = 'Firmware images, per hardware model.';
ALTER TABLE `firmware_rollouts` COMMENT = 'A planned upgrade of many devices to one release, in stages. This is the intent; rollout_devices records what actually happened on each unit.';
ALTER TABLE `rollout_stages` COMMENT = 'Canary first, then wider. A stage starts only after the previous one soaked without crossing the failure threshold.';
ALTER TABLE `rollout_devices` COMMENT = 'Per-device progress of a rollout. Success is confirmed by the device reporting the new version on reconnect, not by the download finishing.';
ALTER TABLE `sites` ADD FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`);
ALTER TABLE `users` ADD FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`);
ALTER TABLE `devices` ADD FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`);
ALTER TABLE `devices` ADD FOREIGN KEY (`site_id`) REFERENCES `sites` (`id`);
ALTER TABLE `devices` ADD FOREIGN KEY (`device_model_id`) REFERENCES `device_models` (`id`);
ALTER TABLE `devices` ADD FOREIGN KEY (`gateway_device_id`) REFERENCES `gateways` (`device_id`);
ALTER TABLE `devices` ADD FOREIGN KEY (`current_firmware_id`) REFERENCES `firmware_releases` (`id`);
ALTER TABLE `gateways` ADD FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`);
ALTER TABLE `device_credentials` ADD FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`);
ALTER TABLE `device_credentials` ADD FOREIGN KEY (`replaces_credential_id`) REFERENCES `device_credentials` (`id`);
ALTER TABLE `device_groups` ADD FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`);
ALTER TABLE `device_group_members` ADD FOREIGN KEY (`device_group_id`) REFERENCES `device_groups` (`id`);
ALTER TABLE `device_group_members` ADD FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`);
ALTER TABLE `model_channels` ADD FOREIGN KEY (`device_model_id`) REFERENCES `device_models` (`id`);
ALTER TABLE `channels` ADD FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`);
ALTER TABLE `channels` ADD FOREIGN KEY (`model_channel_id`) REFERENCES `model_channels` (`id`);
ALTER TABLE `telemetry_readings` ADD FOREIGN KEY (`channel_id`) REFERENCES `channels` (`id`);
ALTER TABLE `telemetry_hourly` ADD FOREIGN KEY (`channel_id`) REFERENCES `channels` (`id`);
ALTER TABLE `connection_events` ADD FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`);
ALTER TABLE `connection_events` ADD FOREIGN KEY (`via_gateway_id`) REFERENCES `gateways` (`device_id`);
ALTER TABLE `connection_events` ADD FOREIGN KEY (`credential_id`) REFERENCES `device_credentials` (`id`);
ALTER TABLE `device_heartbeats` ADD FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`);
ALTER TABLE `device_commands` ADD FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`);
ALTER TABLE `device_commands` ADD FOREIGN KEY (`issued_by`) REFERENCES `users` (`id`);
ALTER TABLE `device_commands` ADD FOREIGN KEY (`alert_id`) REFERENCES `alerts` (`id`);
ALTER TABLE `notification_targets` ADD FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`);
ALTER TABLE `notification_targets` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
ALTER TABLE `alert_rules` ADD FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`);
ALTER TABLE `alert_rules` ADD FOREIGN KEY (`model_channel_id`) REFERENCES `model_channels` (`id`);
ALTER TABLE `alert_rules` ADD FOREIGN KEY (`device_group_id`) REFERENCES `device_groups` (`id`);
ALTER TABLE `alert_rules` ADD FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);
ALTER TABLE `alert_rule_targets` ADD FOREIGN KEY (`alert_rule_id`) REFERENCES `alert_rules` (`id`);
ALTER TABLE `alert_rule_targets` ADD FOREIGN KEY (`notification_target_id`) REFERENCES `notification_targets` (`id`);
ALTER TABLE `alerts` ADD FOREIGN KEY (`alert_rule_id`) REFERENCES `alert_rules` (`id`);
ALTER TABLE `alerts` ADD FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`);
ALTER TABLE `alerts` ADD FOREIGN KEY (`channel_id`) REFERENCES `channels` (`id`);
ALTER TABLE `alerts` ADD FOREIGN KEY (`acknowledged_by`) REFERENCES `users` (`id`);
ALTER TABLE `alerts` ADD FOREIGN KEY (`resolved_by`) REFERENCES `users` (`id`);
ALTER TABLE `alert_events` ADD FOREIGN KEY (`alert_id`) REFERENCES `alerts` (`id`);
ALTER TABLE `alert_events` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
ALTER TABLE `alert_events` ADD FOREIGN KEY (`notification_target_id`) REFERENCES `notification_targets` (`id`);
ALTER TABLE `firmware_releases` ADD FOREIGN KEY (`device_model_id`) REFERENCES `device_models` (`id`);
ALTER TABLE `firmware_rollouts` ADD FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`);
ALTER TABLE `firmware_rollouts` ADD FOREIGN KEY (`firmware_release_id`) REFERENCES `firmware_releases` (`id`);
ALTER TABLE `firmware_rollouts` ADD FOREIGN KEY (`device_group_id`) REFERENCES `device_groups` (`id`);
ALTER TABLE `firmware_rollouts` ADD FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);
ALTER TABLE `rollout_stages` ADD FOREIGN KEY (`rollout_id`) REFERENCES `firmware_rollouts` (`id`);
ALTER TABLE `rollout_devices` ADD FOREIGN KEY (`rollout_id`) REFERENCES `firmware_rollouts` (`id`);
ALTER TABLE `rollout_devices` ADD FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`);
ALTER TABLE `rollout_devices` ADD FOREIGN KEY (`rollout_stage_id`) REFERENCES `rollout_stages` (`id`);
ALTER TABLE `rollout_devices` ADD FOREIGN KEY (`from_firmware_id`) REFERENCES `firmware_releases` (`id`);SQL Server
CREATE TABLE [tenants] (
[id] uuid PRIMARY KEY,
[name] varchar(200) NOT NULL,
[slug] varchar(60) UNIQUE NOT NULL,
[plan] nvarchar(255) NOT NULL CHECK ([plan] IN ('starter', 'professional', 'enterprise')),
[rollup_retention_days] integer NOT NULL DEFAULT (730),
[timezone] varchar(64) NOT NULL,
[created_at] timestamptz NOT NULL DEFAULT (now())
)
GO
CREATE TABLE [sites] (
[id] uuid PRIMARY KEY,
[tenant_id] uuid NOT NULL,
[name] varchar(200) NOT NULL,
[address] varchar(300),
[latitude] numeric(9,6),
[longitude] numeric(9,6),
[timezone] varchar(64) NOT NULL
)
GO
CREATE TABLE [users] (
[id] uuid PRIMARY KEY,
[tenant_id] uuid NOT NULL,
[email] varchar(254) UNIQUE NOT NULL,
[name] varchar(200) NOT NULL,
[role] nvarchar(255) NOT NULL CHECK ([role] IN ('viewer', 'operator', 'admin')),
[created_at] timestamptz NOT NULL DEFAULT (now()),
[disabled_at] timestamptz
)
GO
CREATE TABLE [device_models] (
[id] uuid PRIMARY KEY,
[manufacturer] varchar(120) NOT NULL,
[model_number] varchar(60) NOT NULL,
[name] varchar(200) NOT NULL,
[kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('sensor', 'actuator', 'meter', 'controller', 'gateway')),
[connectivity] nvarchar(255) NOT NULL CHECK ([connectivity] IN ('wifi', 'ethernet', 'cellular', 'lpwan', 'mesh_radio', 'via_gateway')),
[battery_powered] boolean NOT NULL DEFAULT (false),
[heartbeat_interval_s] integer NOT NULL DEFAULT (60)
)
GO
CREATE TABLE [devices] (
[id] uuid PRIMARY KEY,
[tenant_id] uuid NOT NULL,
[site_id] uuid,
[device_model_id] uuid NOT NULL,
[serial_number] varchar(64) NOT NULL,
[name] varchar(200),
[gateway_device_id] uuid,
[current_firmware_id] uuid,
[status] nvarchar(255) NOT NULL CHECK ([status] IN ('provisioned', 'active', 'inactive', 'maintenance', 'decommissioned')) DEFAULT 'provisioned',
[last_seen_at] timestamptz,
[installed_at] timestamptz,
[decommissioned_at] timestamptz,
[labels] jsonb
)
GO
CREATE TABLE [gateways] (
[device_id] uuid PRIMARY KEY,
[backhaul] nvarchar(255) NOT NULL CHECK ([backhaul] IN ('ethernet', 'wifi', 'cellular', 'satellite')),
[buffer_capacity_hours] integer NOT NULL,
[max_child_devices] integer,
[lan_ip] inet
)
GO
CREATE TABLE [device_credentials] (
[id] uuid PRIMARY KEY,
[device_id] uuid NOT NULL,
[kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('x509_certificate', 'raw_public_key', 'symmetric_key')),
[fingerprint] char(64) UNIQUE NOT NULL,
[certificate_pem] text,
[issued_at] timestamptz NOT NULL DEFAULT (now()),
[not_before] timestamptz NOT NULL,
[expires_at] timestamptz NOT NULL,
[revoked_at] timestamptz,
[revoke_reason] varchar(200),
[replaces_credential_id] uuid
)
GO
CREATE TABLE [device_groups] (
[id] uuid PRIMARY KEY,
[tenant_id] uuid NOT NULL,
[name] varchar(120) NOT NULL,
[description] varchar(500)
)
GO
CREATE TABLE [device_group_members] (
[device_group_id] uuid NOT NULL,
[device_id] uuid NOT NULL,
[added_at] timestamptz NOT NULL DEFAULT (now()),
PRIMARY KEY ([device_group_id], [device_id])
)
GO
CREATE TABLE [model_channels] (
[id] uuid PRIMARY KEY,
[device_model_id] uuid NOT NULL,
[key] varchar(60) NOT NULL,
[name] varchar(120) NOT NULL,
[unit] varchar(20) NOT NULL,
[value_kind] nvarchar(255) NOT NULL CHECK ([value_kind] IN ('gauge', 'counter', 'boolean', 'state')),
[min_valid] float8,
[max_valid] float8,
[sample_interval_s] integer
)
GO
CREATE TABLE [channels] (
[id] uuid PRIMARY KEY,
[device_id] uuid NOT NULL,
[model_channel_id] uuid NOT NULL,
[calibration_offset] float8 NOT NULL DEFAULT (0),
[calibration_scale] float8 NOT NULL DEFAULT (1),
[is_enabled] boolean NOT NULL DEFAULT (true),
[last_value] float8,
[last_recorded_at] timestamptz
)
GO
CREATE TABLE [telemetry_readings] (
[channel_id] uuid NOT NULL,
[recorded_at] timestamptz NOT NULL,
[received_at] timestamptz NOT NULL DEFAULT (now()),
[value] float8 NOT NULL,
[quality] nvarchar(255) NOT NULL CHECK ([quality] IN ('good', 'out_of_range', 'estimated', 'sensor_fault')) DEFAULT 'good',
PRIMARY KEY ([channel_id], [recorded_at])
)
GO
CREATE TABLE [telemetry_hourly] (
[channel_id] uuid NOT NULL,
[hour_start] timestamptz NOT NULL,
[sample_count] integer NOT NULL,
[min_value] float8 NOT NULL,
[max_value] float8 NOT NULL,
[sum_value] float8 NOT NULL,
[first_value] float8,
[last_value] float8,
[computed_at] timestamptz NOT NULL,
PRIMARY KEY ([channel_id], [hour_start])
)
GO
CREATE TABLE [connection_events] (
[id] uuid PRIMARY KEY,
[device_id] uuid NOT NULL,
[kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('connected', 'disconnected', 'keepalive_timeout', 'auth_failed')),
[occurred_at] timestamptz NOT NULL,
[via_gateway_id] uuid,
[credential_id] uuid,
[remote_ip] inet,
[protocol] varchar(20),
[reason] varchar(200)
)
GO
CREATE TABLE [device_heartbeats] (
[device_id] uuid NOT NULL,
[received_at] timestamptz NOT NULL,
[battery_pct] smallint,
[signal_dbm] smallint,
[uptime_s] bigint,
[free_memory_kb] integer,
[firmware_version] varchar(40),
PRIMARY KEY ([device_id], [received_at])
)
GO
CREATE TABLE [device_commands] (
[id] uuid PRIMARY KEY,
[device_id] uuid NOT NULL,
[command] varchar(60) NOT NULL,
[payload] jsonb,
[status] nvarchar(255) NOT NULL CHECK ([status] IN ('queued', 'sent', 'delivered', 'acknowledged', 'failed', 'expired')) DEFAULT 'queued',
[issued_by] uuid,
[alert_id] uuid,
[message_id] uuid UNIQUE NOT NULL,
[attempts] smallint NOT NULL DEFAULT (0),
[created_at] timestamptz NOT NULL DEFAULT (now()),
[sent_at] timestamptz,
[delivered_at] timestamptz,
[acknowledged_at] timestamptz,
[failed_at] timestamptz,
[expires_at] timestamptz NOT NULL,
[result] jsonb,
[error_message] varchar(500)
)
GO
CREATE TABLE [notification_targets] (
[id] uuid PRIMARY KEY,
[tenant_id] uuid NOT NULL,
[kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('email', 'sms', 'webhook', 'on_call')),
[address] varchar(500) NOT NULL,
[user_id] uuid,
[verified_at] timestamptz
)
GO
CREATE TABLE [alert_rules] (
[id] uuid PRIMARY KEY,
[tenant_id] uuid NOT NULL,
[name] varchar(200) NOT NULL,
[kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('threshold', 'rate_of_change', 'no_data')),
[model_channel_id] uuid NOT NULL,
[device_group_id] uuid,
[operator] nvarchar(255) CHECK ([operator] IN ('gt', 'gte', 'lt', 'lte', 'eq', 'neq')),
[threshold] float8,
[clear_threshold] float8,
[for_seconds] integer NOT NULL DEFAULT (0),
[severity] nvarchar(255) NOT NULL CHECK ([severity] IN ('info', 'warning', 'critical')),
[is_enabled] boolean NOT NULL DEFAULT (true),
[created_by] uuid,
[created_at] timestamptz NOT NULL DEFAULT (now())
)
GO
CREATE TABLE [alert_rule_targets] (
[alert_rule_id] uuid NOT NULL,
[notification_target_id] uuid NOT NULL,
[escalate_after_minutes] integer,
PRIMARY KEY ([alert_rule_id], [notification_target_id])
)
GO
CREATE TABLE [alerts] (
[id] uuid PRIMARY KEY,
[alert_rule_id] uuid NOT NULL,
[device_id] uuid NOT NULL,
[channel_id] uuid,
[status] nvarchar(255) NOT NULL CHECK ([status] IN ('open', 'acknowledged', 'resolved')) DEFAULT 'open',
[severity] nvarchar(255) NOT NULL CHECK ([severity] IN ('info', 'warning', 'critical')),
[trigger_value] float8,
[peak_value] float8,
[opened_at] timestamptz NOT NULL,
[last_triggered_at] timestamptz NOT NULL,
[acknowledged_at] timestamptz,
[acknowledged_by] uuid,
[resolved_at] timestamptz,
[resolved_by] uuid,
[resolution_comment] varchar(1000)
)
GO
CREATE TABLE [alert_events] (
[id] uuid PRIMARY KEY,
[alert_id] uuid NOT NULL,
[kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('opened', 'retriggered', 'notified', 'escalated', 'acknowledged', 'resolved', 'auto_resolved')),
[occurred_at] timestamptz NOT NULL DEFAULT (now()),
[user_id] uuid,
[notification_target_id] uuid,
[value] float8,
[details] jsonb
)
GO
CREATE TABLE [firmware_releases] (
[id] uuid PRIMARY KEY,
[device_model_id] uuid NOT NULL,
[version] varchar(40) NOT NULL,
[build_number] integer NOT NULL,
[release_channel] nvarchar(255) NOT NULL CHECK ([release_channel] IN ('development', 'beta', 'stable')),
[storage_key] varchar(300) NOT NULL,
[size_bytes] bigint NOT NULL,
[sha256] char(64) NOT NULL,
[signature] text NOT NULL,
[min_from_build] integer,
[release_notes] text,
[released_at] timestamptz,
[revoked_at] timestamptz
)
GO
CREATE TABLE [firmware_rollouts] (
[id] uuid PRIMARY KEY,
[tenant_id] uuid NOT NULL,
[firmware_release_id] uuid NOT NULL,
[device_group_id] uuid,
[name] varchar(200) NOT NULL,
[status] nvarchar(255) NOT NULL CHECK ([status] IN ('draft', 'running', 'paused', 'completed', 'aborted')) DEFAULT 'draft',
[max_failure_pct] numeric(5,2) NOT NULL DEFAULT (2),
[maintenance_window] jsonb,
[created_by] uuid NOT NULL,
[created_at] timestamptz NOT NULL DEFAULT (now()),
[started_at] timestamptz,
[completed_at] timestamptz
)
GO
CREATE TABLE [rollout_stages] (
[id] uuid PRIMARY KEY,
[rollout_id] uuid NOT NULL,
[stage_number] smallint NOT NULL,
[target_pct] numeric(5,2) NOT NULL,
[soak_minutes] integer NOT NULL DEFAULT (1440),
[started_at] timestamptz,
[completed_at] timestamptz
)
GO
CREATE TABLE [rollout_devices] (
[rollout_id] uuid NOT NULL,
[device_id] uuid NOT NULL,
[rollout_stage_id] uuid NOT NULL,
[from_firmware_id] uuid,
[status] nvarchar(255) NOT NULL CHECK ([status] IN ('pending', 'downloading', 'installing', 'succeeded', 'failed', 'rolled_back', 'skipped')) DEFAULT 'pending',
[attempts] smallint NOT NULL DEFAULT (0),
[last_attempt_at] timestamptz,
[completed_at] timestamptz,
[error_code] varchar(60),
PRIMARY KEY ([rollout_id], [device_id])
)
GO
CREATE UNIQUE INDEX [sites_index_0] ON [sites] ("tenant_id", "name")
GO
CREATE UNIQUE INDEX [device_models_index_1] ON [device_models] ("manufacturer", "model_number")
GO
CREATE UNIQUE INDEX [devices_index_2] ON [devices] ("device_model_id", "serial_number")
GO
CREATE INDEX [devices_index_3] ON [devices] ("tenant_id", "site_id")
GO
CREATE INDEX [device_credentials_index_4] ON [device_credentials] ("device_id", "expires_at")
GO
CREATE INDEX [device_credentials_index_5] ON [device_credentials] ("expires_at")
GO
CREATE UNIQUE INDEX [device_groups_index_6] ON [device_groups] ("tenant_id", "name")
GO
CREATE UNIQUE INDEX [model_channels_index_7] ON [model_channels] ("device_model_id", "key")
GO
CREATE UNIQUE INDEX [channels_index_8] ON [channels] ("device_id", "model_channel_id")
GO
CREATE INDEX [telemetry_readings_index_9] ON [telemetry_readings] ("recorded_at")
GO
CREATE INDEX [connection_events_index_10] ON [connection_events] ("device_id", "occurred_at")
GO
CREATE INDEX [device_commands_index_11] ON [device_commands] ("device_id", "status", "created_at")
GO
CREATE INDEX [alerts_index_12] ON [alerts] ("alert_rule_id", "device_id", "channel_id")
GO
CREATE INDEX [alerts_index_13] ON [alerts] ("status", "opened_at")
GO
CREATE INDEX [alert_events_index_14] ON [alert_events] ("alert_id", "occurred_at")
GO
CREATE UNIQUE INDEX [firmware_releases_index_15] ON [firmware_releases] ("device_model_id", "version")
GO
CREATE UNIQUE INDEX [firmware_releases_index_16] ON [firmware_releases] ("device_model_id", "build_number")
GO
CREATE UNIQUE INDEX [rollout_stages_index_17] ON [rollout_stages] ("rollout_id", "stage_number")
GO
CREATE INDEX [rollout_devices_index_18] ON [rollout_devices] ("rollout_stage_id", "status")
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Customer organizations. Every device, rule and rollout belongs to exactly one, and row-level security keys on tenant_id.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'tenants';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'How long hourly rollups are kept. Raw readings follow the global partition retention',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'tenants',
@level2type = N'Column', @level2name = 'rollup_retention_days';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'IANA zone; daily reports bucket by it',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'tenants',
@level2type = N'Column', @level2name = 'timezone';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Physical places devices are installed: a plant, a building, a farm.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'sites';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Maintenance windows are in site local time',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'sites',
@level2type = N'Column', @level2name = 'timezone';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'People in a tenant: who acknowledges alerts, sends commands and starts rollouts.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'users';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Hardware types. A model defines which channels its devices have and which firmware they can run.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_models';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Expected check-in interval. Offline means "no heartbeat for 3 intervals", not one fixed timeout',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_models',
@level2type = N'Column', @level2name = 'heartbeat_interval_s';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'One physical unit in the field. Gateways are devices too, so credentials, heartbeats, commands and firmware rollouts all apply to them unchanged.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'devices';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null while in stock or in transit',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'devices',
@level2type = N'Column', @level2name = 'site_id';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The gateway it reports through; null for devices that connect directly',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'devices',
@level2type = N'Column', @level2name = 'gateway_device_id';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'REPORTED by the device on connect. What it should run is decided by rollouts',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'devices',
@level2type = N'Column', @level2name = 'current_firmware_id';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'CACHE of the latest heartbeat or reading',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'devices',
@level2type = N'Column', @level2name = 'last_seen_at';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Free-form key values, e.g. {"line": "3", "floor": "B2"}',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'devices',
@level2type = N'Column', @level2name = 'labels';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Extra attributes for the devices that are gateways: a one-to-one subtype of devices. Child devices point here.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'gateways';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'How the gateway itself reaches the cloud',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'gateways',
@level2type = N'Column', @level2name = 'backhaul';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'How long it can hold readings while offline. Buffered readings arrive late, with their original recorded_at',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'gateways',
@level2type = N'Column', @level2name = 'buffer_capacity_hours';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Certificates and keys a device authenticates with. Rotation overlaps: the new credential is issued and seen in use before the old one is revoked, so a device is never locked out mid-rotation.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_credentials';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'SHA-256 of the certificate or public key; what the broker looks up on connect',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_credentials',
@level2type = N'Column', @level2name = 'fingerprint';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Public certificate only. Private keys never leave the device',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_credentials',
@level2type = N'Column', @level2name = 'certificate_pem';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Rotation chain: the credential this one supersedes',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_credentials',
@level2type = N'Column', @level2name = 'replaces_credential_id';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Named sets of devices, e.g. "pilot line" or "cold rooms", used to target rollouts and scope alert rules.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_groups';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Group membership. A device can be in many groups.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_group_members';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The channels a model has: the template every device of that model is created with.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'model_channels';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Stable identifier in the payload, e.g. temp_c, rh_pct, door_open',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'model_channels',
@level2type = N'Column', @level2name = 'key';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'UCUM unit code, e.g. Cel, %, kW.h. Values are always stored in this unit',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'model_channels',
@level2type = N'Column', @level2name = 'unit';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Physical range of the sensor. Outside it a reading is flagged, not dropped',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'model_channels',
@level2type = N'Column', @level2name = 'min_valid';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'One sensor on one physical device, and the key every reading is filed under. Calibration lives here because two sensors of the same model never read identically.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'channels';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Stored value = raw * scale + offset, applied at ingest',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'channels',
@level2type = N'Column', @level2name = 'calibration_scale';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'CACHE of the newest reading, for device lists and map pins',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'channels',
@level2type = N'Column', @level2name = 'last_value';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Raw readings: narrow, append-only, never updated.
PARTITION BY RANGE (recorded_at), one partition per day or week, created ahead of time by a job. Retention is DROP PARTITION, which is instant, instead of a DELETE that bloats the table.
No surrogate id: at billions of rows a uuid per reading costs more than the reading itself.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'telemetry_readings';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Device clock, when it was measured. The partition key',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'telemetry_readings',
@level2type = N'Column', @level2name = 'recorded_at';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Server clock. A large gap means it was buffered offline',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'telemetry_readings',
@level2type = N'Column', @level2name = 'received_at';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Booleans are 0 or 1; enumerated states use their numeric code',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'telemetry_readings',
@level2type = N'Column', @level2name = 'value';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Hourly rollup per channel. Every chart wider than a few hours reads here, never from raw readings.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'telemetry_hourly';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'A sum, not an average: averages of averages are wrong, while sums and counts roll up to days exactly',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'telemetry_hourly',
@level2type = N'Column', @level2name = 'sum_value';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Late readings for this hour (received_at after this) trigger a recompute of just this row',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'telemetry_hourly',
@level2type = N'Column', @level2name = 'computed_at';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Connects, disconnects and failed authentications, from the broker. Uptime reports are computed from these.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'connection_events';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Which credential it presented. Repeated failures with a revoked one deserve an alert',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'connection_events',
@level2type = N'Column', @level2name = 'credential_id';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. mqtt, coap, https',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'connection_events',
@level2type = N'Column', @level2name = 'protocol';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Disconnect or failure reason as reported by the broker',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'connection_events',
@level2type = N'Column', @level2name = 'reason';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Periodic health check-ins. Partitioned by time like readings, with shorter retention; devices.last_seen_at caches the latest.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_heartbeats';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Received signal strength. Trending it finds devices about to drop off',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_heartbeats',
@level2type = N'Column', @level2name = 'signal_dbm';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Seconds since boot. A drop to near zero means an unplanned reboot',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_heartbeats',
@level2type = N'Column', @level2name = 'uptime_s';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'As reported; devices.current_firmware_id is updated from it',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_heartbeats',
@level2type = N'Column', @level2name = 'firmware_version';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Cloud-to-device commands as a state machine: queued, sent, delivered, acknowledged, or failed, or expired.
Each transition stamps its own column, so where a command stalled is visible. Devices are often asleep or offline, which is why queued and expired exist at all.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_commands';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. reboot, set_sample_interval, open_valve',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_commands',
@level2type = N'Column', @level2name = 'command';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for commands issued by automation',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_commands',
@level2type = N'Column', @level2name = 'issued_by';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set when an alert triggered it',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_commands',
@level2type = N'Column', @level2name = 'alert_id';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Sent with the command and echoed back in the ack, so a duplicate ack is recognised',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_commands',
@level2type = N'Column', @level2name = 'message_id';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Never sent after this. A reboot queued for an offline device must not fire three days later',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_commands',
@level2type = N'Column', @level2name = 'expires_at';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'What the device reported back',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'device_commands',
@level2type = N'Column', @level2name = 'result';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Where alerts can be sent: email, SMS, webhooks, on-call tools.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'notification_targets';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Email address, phone number, or webhook URL',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'notification_targets',
@level2type = N'Column', @level2name = 'address';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set when the target is a person rather than a shared channel',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'notification_targets',
@level2type = N'Column', @level2name = 'user_id';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Thresholds, rate-of-change and no-data rules (the offline detector). Written once against a model channel, evaluated on every matching device.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alert_rules';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Which channel type the rule watches, e.g. temp_c on one model',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alert_rules',
@level2type = N'Column', @level2name = 'model_channel_id';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Scope; null for every matching device in the tenant',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alert_rules',
@level2type = N'Column', @level2name = 'device_group_id';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Threshold rules only',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alert_rules',
@level2type = N'Column', @level2name = 'operator';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Threshold rules only, in the channel unit',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alert_rules',
@level2type = N'Column', @level2name = 'threshold';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Hysteresis: the alert resolves only past this value, so a reading hovering at the threshold does not flap',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alert_rules',
@level2type = N'Column', @level2name = 'clear_threshold';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The condition must hold this long before an alert opens',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alert_rules',
@level2type = N'Column', @level2name = 'for_seconds';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Who hears about which rule, and when. Escalation is just a second target with a delay.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alert_rule_targets';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null notifies at once; a value notifies only if still unacknowledged after that long',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alert_rule_targets',
@level2type = N'Column', @level2name = 'escalate_after_minutes';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Incidents: open, then acknowledged, then resolved.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alerts';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for device-level rules such as no data',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alerts',
@level2type = N'Column', @level2name = 'channel_id';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Copied from the rule when opened, so editing the rule never rewrites history',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alerts',
@level2type = N'Column', @level2name = 'severity';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Worst value seen while open',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alerts',
@level2type = N'Column', @level2name = 'peak_value';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null when it cleared automatically',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alerts',
@level2type = N'Column', @level2name = 'resolved_by';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The timeline of an alert. alerts holds its current state; this holds how it got there, for the postmortem.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alert_events';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'For notified and escalated events: where it was sent',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'alert_events',
@level2type = N'Column', @level2name = 'notification_target_id';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Firmware images, per hardware model.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'firmware_releases';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Semantic version, e.g. 2.4.1',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'firmware_releases',
@level2type = N'Column', @level2name = 'version';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Monotonic. Ordering by it is safe where ordering version strings is not',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'firmware_releases',
@level2type = N'Column', @level2name = 'build_number';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Object storage key of the image. Devices download it through a short-lived signed URL',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'firmware_releases',
@level2type = N'Column', @level2name = 'storage_key';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The device verifies the image before flashing it',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'firmware_releases',
@level2type = N'Column', @level2name = 'sha256';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Signed by the build pipeline; the bootloader refuses unsigned images',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'firmware_releases',
@level2type = N'Column', @level2name = 'signature';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Oldest build that can upgrade straight to this one; older devices need a stepping-stone release',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'firmware_releases',
@level2type = N'Column', @level2name = 'min_from_build';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Pulled after release. Running rollouts of it are aborted',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'firmware_releases',
@level2type = N'Column', @level2name = 'revoked_at';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A planned upgrade of many devices to one release, in stages. This is the intent; rollout_devices records what actually happened on each unit.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'firmware_rollouts';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Target; null for every eligible device of the model in the tenant',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'firmware_rollouts',
@level2type = N'Column', @level2name = 'device_group_id';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Pause automatically when a stage fails more than this',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'firmware_rollouts',
@level2type = N'Column', @level2name = 'max_failure_pct';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Site-local hours devices may install in, e.g. {"days": [1,2,3,4,5], "from": "02:00", "to": "04:00"}',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'firmware_rollouts',
@level2type = N'Column', @level2name = 'maintenance_window';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Canary first, then wider. A stage starts only after the previous one soaked without crossing the failure threshold.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'rollout_stages';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Cumulative share of the target devices, e.g. 1, 10, 50, 100',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'rollout_stages',
@level2type = N'Column', @level2name = 'target_pct';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'How long to watch a stage before the next may start',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'rollout_stages',
@level2type = N'Column', @level2name = 'soak_minutes';
GO
EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Per-device progress of a rollout. Success is confirmed by the device reporting the new version on reconnect, not by the download finishing.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'rollout_devices';
GO
EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'What it ran before, for rollback',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table', @level1name = 'rollout_devices',
@level2type = N'Column', @level2name = 'from_firmware_id';
GO
ALTER TABLE [sites] ADD FOREIGN KEY ([tenant_id]) REFERENCES [tenants] ([id])
GO
ALTER TABLE [users] ADD FOREIGN KEY ([tenant_id]) REFERENCES [tenants] ([id])
GO
ALTER TABLE [devices] ADD FOREIGN KEY ([tenant_id]) REFERENCES [tenants] ([id])
GO
ALTER TABLE [devices] ADD FOREIGN KEY ([site_id]) REFERENCES [sites] ([id])
GO
ALTER TABLE [devices] ADD FOREIGN KEY ([device_model_id]) REFERENCES [device_models] ([id])
GO
ALTER TABLE [devices] ADD FOREIGN KEY ([gateway_device_id]) REFERENCES [gateways] ([device_id])
GO
ALTER TABLE [devices] ADD FOREIGN KEY ([current_firmware_id]) REFERENCES [firmware_releases] ([id])
GO
ALTER TABLE [gateways] ADD FOREIGN KEY ([device_id]) REFERENCES [devices] ([id])
GO
ALTER TABLE [device_credentials] ADD FOREIGN KEY ([device_id]) REFERENCES [devices] ([id])
GO
ALTER TABLE [device_credentials] ADD FOREIGN KEY ([replaces_credential_id]) REFERENCES [device_credentials] ([id])
GO
ALTER TABLE [device_groups] ADD FOREIGN KEY ([tenant_id]) REFERENCES [tenants] ([id])
GO
ALTER TABLE [device_group_members] ADD FOREIGN KEY ([device_group_id]) REFERENCES [device_groups] ([id])
GO
ALTER TABLE [device_group_members] ADD FOREIGN KEY ([device_id]) REFERENCES [devices] ([id])
GO
ALTER TABLE [model_channels] ADD FOREIGN KEY ([device_model_id]) REFERENCES [device_models] ([id])
GO
ALTER TABLE [channels] ADD FOREIGN KEY ([device_id]) REFERENCES [devices] ([id])
GO
ALTER TABLE [channels] ADD FOREIGN KEY ([model_channel_id]) REFERENCES [model_channels] ([id])
GO
ALTER TABLE [telemetry_readings] ADD FOREIGN KEY ([channel_id]) REFERENCES [channels] ([id])
GO
ALTER TABLE [telemetry_hourly] ADD FOREIGN KEY ([channel_id]) REFERENCES [channels] ([id])
GO
ALTER TABLE [connection_events] ADD FOREIGN KEY ([device_id]) REFERENCES [devices] ([id])
GO
ALTER TABLE [connection_events] ADD FOREIGN KEY ([via_gateway_id]) REFERENCES [gateways] ([device_id])
GO
ALTER TABLE [connection_events] ADD FOREIGN KEY ([credential_id]) REFERENCES [device_credentials] ([id])
GO
ALTER TABLE [device_heartbeats] ADD FOREIGN KEY ([device_id]) REFERENCES [devices] ([id])
GO
ALTER TABLE [device_commands] ADD FOREIGN KEY ([device_id]) REFERENCES [devices] ([id])
GO
ALTER TABLE [device_commands] ADD FOREIGN KEY ([issued_by]) REFERENCES [users] ([id])
GO
ALTER TABLE [device_commands] ADD FOREIGN KEY ([alert_id]) REFERENCES [alerts] ([id])
GO
ALTER TABLE [notification_targets] ADD FOREIGN KEY ([tenant_id]) REFERENCES [tenants] ([id])
GO
ALTER TABLE [notification_targets] ADD FOREIGN KEY ([user_id]) REFERENCES [users] ([id])
GO
ALTER TABLE [alert_rules] ADD FOREIGN KEY ([tenant_id]) REFERENCES [tenants] ([id])
GO
ALTER TABLE [alert_rules] ADD FOREIGN KEY ([model_channel_id]) REFERENCES [model_channels] ([id])
GO
ALTER TABLE [alert_rules] ADD FOREIGN KEY ([device_group_id]) REFERENCES [device_groups] ([id])
GO
ALTER TABLE [alert_rules] ADD FOREIGN KEY ([created_by]) REFERENCES [users] ([id])
GO
ALTER TABLE [alert_rule_targets] ADD FOREIGN KEY ([alert_rule_id]) REFERENCES [alert_rules] ([id])
GO
ALTER TABLE [alert_rule_targets] ADD FOREIGN KEY ([notification_target_id]) REFERENCES [notification_targets] ([id])
GO
ALTER TABLE [alerts] ADD FOREIGN KEY ([alert_rule_id]) REFERENCES [alert_rules] ([id])
GO
ALTER TABLE [alerts] ADD FOREIGN KEY ([device_id]) REFERENCES [devices] ([id])
GO
ALTER TABLE [alerts] ADD FOREIGN KEY ([channel_id]) REFERENCES [channels] ([id])
GO
ALTER TABLE [alerts] ADD FOREIGN KEY ([acknowledged_by]) REFERENCES [users] ([id])
GO
ALTER TABLE [alerts] ADD FOREIGN KEY ([resolved_by]) REFERENCES [users] ([id])
GO
ALTER TABLE [alert_events] ADD FOREIGN KEY ([alert_id]) REFERENCES [alerts] ([id])
GO
ALTER TABLE [alert_events] ADD FOREIGN KEY ([user_id]) REFERENCES [users] ([id])
GO
ALTER TABLE [alert_events] ADD FOREIGN KEY ([notification_target_id]) REFERENCES [notification_targets] ([id])
GO
ALTER TABLE [firmware_releases] ADD FOREIGN KEY ([device_model_id]) REFERENCES [device_models] ([id])
GO
ALTER TABLE [firmware_rollouts] ADD FOREIGN KEY ([tenant_id]) REFERENCES [tenants] ([id])
GO
ALTER TABLE [firmware_rollouts] ADD FOREIGN KEY ([firmware_release_id]) REFERENCES [firmware_releases] ([id])
GO
ALTER TABLE [firmware_rollouts] ADD FOREIGN KEY ([device_group_id]) REFERENCES [device_groups] ([id])
GO
ALTER TABLE [firmware_rollouts] ADD FOREIGN KEY ([created_by]) REFERENCES [users] ([id])
GO
ALTER TABLE [rollout_stages] ADD FOREIGN KEY ([rollout_id]) REFERENCES [firmware_rollouts] ([id])
GO
ALTER TABLE [rollout_devices] ADD FOREIGN KEY ([rollout_id]) REFERENCES [firmware_rollouts] ([id])
GO
ALTER TABLE [rollout_devices] ADD FOREIGN KEY ([device_id]) REFERENCES [devices] ([id])
GO
ALTER TABLE [rollout_devices] ADD FOREIGN KEY ([rollout_stage_id]) REFERENCES [rollout_stages] ([id])
GO
ALTER TABLE [rollout_devices] ADD FOREIGN KEY ([from_firmware_id]) REFERENCES [firmware_releases] ([id])
GOHow to use this template
- Open the ER diagram to see the tables and how they relate.
- Copy it into your workspace. You get your own editable copy, in DBML.
- Export it as PostgreSQL, MySQL, or SQL Server DDL, or as Prisma, Drizzle, SQLAlchemy, TypeScript, Zod or C# models.
The copy opens in DB Planner’s ER diagram tool, with the schema as text in the DBML editor beside it. Have a database already? Turn its SQL into an ER diagram instead.
Frequently asked questions
- Which table is at the centre of the IoT Device Telemetry database schema?
- devices. It is referenced by 8 other tables: alerts, channels, connection_events, device_commands, device_credentials and 3 more.
- How is alerts related to devices?
- alerts.device_id references devices.id, a many to one relationship. All 51 relationships in the schema are listed on this page.
- Which table in the IoT Device Telemetry database schema has the most columns?
- device_commands, with 17 columns, followed by alerts (15) and alert_rules (14). The schema has 216 columns across 25 tables.
- Can I export it to PostgreSQL or MySQL?
- Yes. Every DB Planner template exports as DBML, as PostgreSQL, MySQL, or SQL Server DDL, and as C# models.
- Is this template free?
- Yes. You can open it in the browser without an account, and copy it into your own workspace with a free DB Planner account.
- Can I change it after copying it?
- Yes. A copy is yours: you can rename tables, add columns, and export it. Changes the author makes later do not affect your copy.