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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which tables or CTEs does it reference?
- The references are `app_config`, `set`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.