Singleton Config Table Guarded By CHECK

Enforce a one-row settings table with a CHECK (id = 1) guard so concurrent writers cannot create a second row, and mutate it with ON CONFLICT.

SqlConfig Management

Code

snippet
-- Singleton config table: one row per database; CHECK (id = 1) rejects a second row at the database level
-- More reliable than an application-level "at most one row" convention: concurrent inserts are also blocked by the constraint
CREATE TABLE app_config (
    id int PRIMARY KEY CHECK (id = 1),
    maintenance_mode boolean NOT NULL DEFAULT false,
    max_upload_bytes bigint NOT NULL DEFAULT 10485760,
    updated_at timestamptz NOT NULL DEFAULT now()
);

INSERT INTO app_config (id, maintenance_mode)
VALUES (1, false)
ON CONFLICT (id) DO UPDATE
SET maintenance_mode = EXCLUDED.maintenance_mode,
    updated_at = now();

-- Any write with id=2 is rejected by the CHECK; duplicate id=1 values are caught by the primary key
INSERT INTO app_config (id) VALUES (2);

SELECT maintenance_mode, max_upload_bytes FROM app_config;

What the code does

Several statements share this file — SELECT / INSERT / UPDATE / CREATE, with app_config and set among the objects involved.

What the statements actually assemble: an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement; a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.

Applying it

Run the statement against the app_config table.

Statements that matter

INSERT INTO app_config (id, maintenance_mode)
VALUES (1, false)
ON CONFLICT (id) DO UPDATE
SET maintenance_mode = EXCLUDED.maintenance_mode,
updated_at = now();
CREATE TABLE app_config (
id int PRIMARY KEY CHECK (id = 1),
maintenance_mode boolean NOT NULL DEFAULT false,
max_upload_bytes bigint NOT NULL DEFAULT 10485760,
updated_at timestamptz NOT NULL DEFAULT now()
);
SELECT maintenance_mode, max_upload_bytes FROM app_config;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
The references are `app_config`, `set`.