---
title: Database Schema
slug: database-schema
createdAt: 2025-05-06T07:11:51.999Z
---

This document contains the SQL `CREATE TABLE` statements for the database tables that are directly involved in the CommandIT Auto-Update Service. It includes the core tables the updater client and server will interact with, along with necessary dependencies for context.

```javascript
-- CommandIT Database Schema (Core Tables for Updater Service v1.4)
-- Dialect: PostgreSQL

-- =============================================
-- Core Updater Service Tables
-- =============================================

-- Stores metadata for available agent update packages, including download location,
-- verification info, and target specifics. This table is queried by the update server
-- API (/v1/check) to determine available updates for requesting clients.
-- Assumes the Users table exists for the published_by_user_id foreign key.
CREATE TABLE UpdatePackages (
    package_id          UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Unique ID for this package entry
    component_name      VARCHAR(50) NOT NULL CHECK (component_name IN ('Service', 'UI', 'Probe', 'Updater')), -- Which component this package updates
    version             VARCHAR(50) NOT NULL, -- Semantic Version (e.g., '1.2.3', '2.0.0-beta.1')
    release_channel     VARCHAR(20) NOT NULL CHECK (release_channel IN ('stable', 'beta', 'alpha')), -- Target release channel
    target_os           VARCHAR(20) NOT NULL CHECK (target_os IN ('windows', 'macos', 'linux')), -- Target Operating System
    target_arch         VARCHAR(10) NOT NULL CHECK (target_arch IN ('amd64', 'arm64')), -- Target Architecture
    download_url        TEXT NOT NULL, -- URL to download the package (e.g., DO Spaces URL)
    file_hash_sha256    VARCHAR(64) NOT NULL, -- SHA-256 hash of the package file for integrity check
    signature_base64    TEXT NOT NULL, -- Base64 encoded digital signature of the package hash
    release_notes_url   TEXT NULL, -- Optional URL to release notes
    dependencies        JSONB NULL, -- Optional: Store dependencies, e.g., {"Service": ">=1.2.0"}
    published_at        TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, -- When this package version was made available
    published_by_user_id UUID NULL REFERENCES Users(user_id) ON DELETE SET NULL, -- User who published this package
    is_active           BOOLEAN NOT NULL DEFAULT true, -- Can this package be served?

    -- Ensure only one package per unique combination of component, version, channel, OS, and architecture
    CONSTRAINT updatepackages_unique_version UNIQUE (component_name, version, release_channel, target_os, target_arch)
);

COMMENT ON TABLE UpdatePackages IS 'Stores metadata for available agent update packages, including download location, verification info, and target specifics.';
COMMENT ON COLUMN UpdatePackages.component_name IS 'The specific CommandIT agent component this package updates (Service, UI, Probe, Updater).';
COMMENT ON COLUMN UpdatePackages.version IS 'The semantic version string of the component in this package.';
COMMENT ON COLUMN UpdatePackages.release_channel IS 'The release channel (stable, beta, alpha) this package belongs to.';
COMMENT ON COLUMN UpdatePackages.target_os IS 'The target operating system (windows, macos, linux).';
COMMENT ON COLUMN UpdatePackages.target_arch IS 'The target CPU architecture (amd64, arm64).';
COMMENT ON COLUMN UpdatePackages.download_url IS 'URL where the client updater can download the package file.';
COMMENT ON COLUMN UpdatePackages.file_hash_sha256 IS 'SHA-256 hash of the package file used for integrity verification.';
COMMENT ON COLUMN UpdatePackages.signature_base64 IS 'Base64 encoded digital signature of the package file hash, used for authenticity verification.';
COMMENT ON COLUMN UpdatePackages.dependencies IS 'Optional JSONB defining minimum versions of other components required by this package.';
COMMENT ON COLUMN UpdatePackages.published_at IS 'Timestamp when this package version was published to the server.';
COMMENT ON COLUMN UpdatePackages.is_active IS 'Indicates if this package version should be considered available for deployment.';

-- Indexes for common lookup patterns by the server's /v1/check endpoint
CREATE INDEX idx_updatepackages_lookup ON UpdatePackages(release_channel, target_os, target_arch, component_name, is_active);
CREATE INDEX idx_updatepackages_published ON UpdatePackages(published_at DESC);


-- =============================================
-- Core Device Table (Relevant Columns)
-- =============================================

-- Core Configuration Management Database (CMDB) table storing inventory, status, location,
-- and key details for all managed or discovered assets. The updater client reads/updates
-- agent version fields and potentially health status.
-- Assumes referenced tables like Organizations, Locations, Users, Vendors, Racks, SLAs etc. exist.
CREATE TABLE Devices (
    device_id                       UUID PRIMARY KEY,
    org_id                          UUID NOT NULL REFERENCES Organizations(org_id) ON DELETE CASCADE,
    custodian_org_id                UUID NULL REFERENCES Organizations(org_id) ON DELETE SET NULL,
    assignment_status               VARCHAR(30) NULL CHECK (assignment_status IN ('InStock', 'Reserved', 'LoanedOut', 'RentedOut', 'InTransitToClient', 'InTransitToMsp')),
    related_agreement_addition_id   BIGINT NULL, -- REFERENCES AgreementAdditions(addition_id) ON DELETE SET NULL,
    managed_by_server_device_id     UUID NULL REFERENCES Devices(device_id) ON DELETE SET NULL,
    azure_arc_resource_id           TEXT NULL UNIQUE,
    intune_device_id                TEXT NULL,
    sync_source                     VARCHAR(20) NULL CHECK (sync_source IN ('Agent', 'Intune', 'Manual', 'OtherIntegration')),
    managed_network_record_id       UUID NULL, -- REFERENCES ManagedNetworks(managed_network_record_id) ON DELETE SET NULL,
    floorplan_location_id           UUID NULL REFERENCES Locations(location_id) ON DELETE SET NULL, -- Link to specific Floor/Room location containing floorplan
    floorplan_x_coordinate          REAL NULL, -- X coordinate on the linked floorplan
    floorplan_y_coordinate          REAL NULL, -- Y coordinate on the linked floorplan
    name                            VARCHAR(255) NOT NULL,
    smbios_uuid                     UUID NULL,
    device_type                     VARCHAR(100) NOT NULL,
    is_virtual                      BOOLEAN NOT NULL DEFAULT false,
    status                          VARCHAR(50) NOT NULL DEFAULT 'Active' CHECK (status IN ('Active', 'Inactive', 'InRepair', 'Disposed', 'Archived', 'Lost', 'Stolen', 'PendingMatch')), -- Added 'PendingMatch'
    lifecycle_status                VARCHAR(30) NULL CHECK (lifecycle_status IN ('Active', 'Watch', 'RequiresReview', 'ApprovedForReplacement', 'PendingDisposal', 'EndOfLife')),
    location_id                     UUID REFERENCES Locations(location_id) ON DELETE SET NULL, -- General location (e.g., Building or Site)
    primary_contact_user_id         UUID REFERENCES Users(user_id) ON DELETE SET NULL,
    manufacturer_id                 UUID REFERENCES Manufacturers(manufacturer_id) ON DELETE SET NULL,
    model_number                    VARCHAR(255),
    mfg_part_number                 VARCHAR(255),
    serial_number                   VARCHAR(255),
    asset_tag                       VARCHAR(100),
    imei                            VARCHAR(20),
    meid                            VARCHAR(18),
    iccid                           VARCHAR(22),
    cpu_architecture                VARCHAR(50),
    agent_version                   VARCHAR(50) NULL, -- Legacy/Overall version?
    agent_service_version           VARCHAR(50) NULL, -- Updated by updater
    agent_ui_version                VARCHAR(50) NULL, -- Updated by updater
    agent_probe_version             VARCHAR(50) NULL, -- Updated by updater
    agent_updater_version           VARCHAR(50) NULL, -- Updated by updater (self-update)
    agent_last_full_sync            TIMESTAMPTZ NULL,
    agent_health_status             VARCHAR(20) NULL, -- Potentially updated by updater status reporting
    agent_last_health_check         TIMESTAMPTZ NULL, -- Potentially updated by updater status reporting
    agent_health_details            TEXT NULL, -- Potentially updated by updater status reporting
    is_probe                        BOOLEAN DEFAULT false,
    last_agent_checkin              TIMESTAMPTZ NULL,
    intune_last_checkin_at          TIMESTAMPTZ NULL, -- Populated from Intune sync
    inventory_detail_level          VARCHAR(20) NOT NULL DEFAULT 'Normal',
    enhanced_mode_expires_at        TIMESTAMPTZ,
    install_date                    TIMESTAMPTZ,
    installed_by_user_id            UUID REFERENCES Users(user_id) ON DELETE SET NULL,
    purchase_vendor_id              UUID NULL, -- REFERENCES Vendors(vendor_id) ON DELETE SET NULL,
    purchase_date                   DATE,
    warranty_expiry_date            DATE,
    warranty_provider               VARCHAR(255),
    warranty_status                 VARCHAR(100),
    last_warranty_check_timestamp   TIMESTAMPTZ,
    warranty_details_url            TEXT,
    custom_sla_id                   UUID NULL, -- REFERENCES SLAs(sla_id) ON DELETE SET NULL,
    manual_replacement_date         DATE,
    ip_address                      INET,
    external_ip_address             INET,
    default_gateway                 INET,
    os_type                         VARCHAR(50),
    os_version                      VARCHAR(100),
    firmware_version                VARCHAR(100) NULL, -- New Field
    is_reboot_pending               BOOLEAN NULL,
    rack_id                         UUID NULL REFERENCES Racks(rack_id) ON DELETE SET NULL,
    rack_position_u                 INTEGER NULL,
    rack_units_consumed             INTEGER NULL DEFAULT 1 CHECK (rack_units_consumed IS NULL OR rack_units_consumed >= 1),
    btu_output_standard             INTEGER NULL,
    btu_output_peak                 INTEGER NULL,
    power_consumption_watts_standard INTEGER NULL,
    power_consumption_watts_peak    INTEGER NULL,
    power_draw_amps_peak            NUMERIC(6, 2) NULL,
    last_logged_in_user             VARCHAR(255),
    last_reported_latitude          NUMERIC(9, 6) NULL,
    last_reported_longitude         NUMERIC(9, 6) NULL,
    last_location_accuracy_meters   INTEGER NULL,
    last_location_source            VARCHAR(30) NULL CHECK (last_location_source IN ('OS_GPS', 'OS_WiFi', 'OS_Network', 'IP_Geolocation', 'Unknown')),
    last_location_report_timestamp  TIMESTAMPTZ NULL,
    windows11_compatibility_status  VARCHAR(20) CHECK (windows11_compatibility_status IN ('Compatible', 'NotCompatible', 'Unknown', 'CheckFailed')),
    windows11_incompatibility_reasons TEXT[] NULL,
    windows11_last_check_time       TIMESTAMPTZ NULL,
    configuration                   JSONB,
    scheduled_deletion_date         DATE NULL,
    disposal_date                   DATE NULL,
    disposal_method                 VARCHAR(50) NULL CHECK (disposal_method IN ('Resale', 'Recycle_Certified', 'Recycle_Uncertified', 'Donation', 'Destruction_Physical', 'ReturnToLessor', 'InternalReuse', 'Unknown', 'VmDeleted')),
    sanitization_method             VARCHAR(50) NULL CHECK (sanitization_method IN ('Wipe_NIST_Clear', 'Wipe_NIST_Purge', 'Degauss', 'Physical_Shred', 'Physical_Crush', 'CryptoErase', 'NotApplicable', 'Unknown')),
    disposal_vendor_id              UUID NULL, -- REFERENCES Vendors(vendor_id) ON DELETE SET NULL,
    disposal_certificate_attachment_id UUID NULL, -- REFERENCES Attachments(attachment_id) ON DELETE SET NULL,
    disposal_notes                  TEXT NULL,
    created_at                      TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at                      TIMESTAMPTZ,
    CONSTRAINT devices_org_serial_unique UNIQUE NULLS NOT DISTINCT (org_id, serial_number),
    CONSTRAINT devices_org_asset_tag_unique UNIQUE NULLS NOT DISTINCT (org_id, asset_tag),
    CHECK ((assignment_status = 'LoanedOut' AND custodian_org_id IS NOT NULL) OR assignment_status != 'LoanedOut'),
    CHECK ((assignment_status = 'RentedOut' AND custodian_org_id IS NOT NULL AND related_agreement_addition_id IS NOT NULL) OR assignment_status != 'RentedOut'),
    UNIQUE NULLS NOT DISTINCT (org_id, intune_device_id)
);

COMMENT ON TABLE Devices IS 'Core Configuration Management Database (CMDB) table storing inventory, status, location, and key details for all managed or discovered assets (physical, virtual, cloud devices, network gear, etc.).';
COMMENT ON COLUMN Devices.agent_service_version IS 'Version of the core background service component.';
COMMENT ON COLUMN Devices.agent_ui_version IS 'Version of the user interface component.';
COMMENT ON COLUMN Devices.agent_probe_version IS 'Version of the network probe component.';
COMMENT ON COLUMN Devices.agent_updater_version IS 'Version of the standalone updater component.';
COMMENT ON COLUMN Devices.agent_health_status IS 'Overall health status reported by the agent or updater.';
COMMENT ON COLUMN Devices.agent_last_health_check IS 'Timestamp of the last health check performed or reported.';
COMMENT ON COLUMN Devices.agent_health_details IS 'Additional details regarding agent health or last error.';

-- Indexes for Devices (Copied from provided schema for relevant columns)
CREATE INDEX idx_devices_org_id ON Devices(org_id);
CREATE INDEX idx_devices_location_id ON Devices(location_id);
CREATE INDEX idx_devices_last_checkin ON Devices(last_agent_checkin);
CREATE INDEX idx_devices_status ON Devices(status);
CREATE INDEX idx_devices_intune_id ON Devices(intune_device_id) WHERE intune_device_id IS NOT NULL;


-- =============================================
-- Agent Update Logging
-- =============================================

-- Logs the status and outcome of agent component update attempts on devices.
-- The client updater writes records to this table.
CREATE TABLE AgentUpdateStatusLog (
    update_log_id         BIGSERIAL PRIMARY KEY,
    device_id             UUID NOT NULL REFERENCES Devices(device_id) ON DELETE CASCADE,
    component_name        VARCHAR(50) NOT NULL CHECK (component_name IN ('Service', 'UI', 'Probe', 'Updater', 'AgentBundle')), -- Component being updated
    trigger_source        VARCHAR(50) NULL, -- e.g., 'ScheduledPolicy', 'ManualCommand', 'InitialInstall'
    requested_version     VARCHAR(50) NOT NULL, -- The version the update process aimed for
    current_version       VARCHAR(50) NULL, -- Version before the update attempt started
    status                VARCHAR(20) NOT NULL CHECK (status IN ('Pending', 'Downloading', 'Installing', 'Success', 'Failed', 'Cancelled', 'Skipped')),
    attempt_timestamp     TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, -- When the update process started
    completion_timestamp  TIMESTAMPTZ NULL, -- When the update process finished (successfully or not)
    error_message         TEXT NULL, -- Details if status is 'Failed'
    details               JSONB NULL -- Additional details (e.g., download size, exit code)
);

COMMENT ON TABLE AgentUpdateStatusLog IS 'Logs the status and outcome of agent component update attempts on devices.';
COMMENT ON COLUMN AgentUpdateStatusLog.component_name IS 'The specific agent component targeted by the update.';
COMMENT ON COLUMN AgentUpdateStatusLog.status IS 'The final status of the update attempt for this component.';
COMMENT ON COLUMN AgentUpdateStatusLog.error_message IS 'Error details if the update attempt failed.';

-- Indexes for AgentUpdateStatusLog (Copied from provided schema)
CREATE INDEX idx_agentupdatelog_device_time ON AgentUpdateStatusLog(device_id, attempt_timestamp DESC);
CREATE INDEX idx_agentupdatelog_status ON AgentUpdateStatusLog(status);


```

