CHECK Constraint Text Hygiene btrim Length
Enforce text hygiene with CHECK constraints: btrim equality rejects padded strings, char_length bounds the size, status accepts known values only.
Code
-- 文本卫生约束:每行写入时逐行强制执行,脏数据到不了表里
CREATE TABLE profiles (
profile_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
display_name text NOT NULL,
status text NOT NULL DEFAULT 'active',
CONSTRAINT display_name_no_padding
CHECK (display_name = btrim(display_name)),
CONSTRAINT display_name_length
CHECK (char_length(display_name) BETWEEN 1 AND 80),
CONSTRAINT status_known_value
CHECK (status IN ('active', 'suspended', 'closed'))
);
INSERT INTO profiles (display_name) VALUES ('ada');
-- INSERT INTO profiles (display_name) VALUES (' ada ');
-- ↑ 违反 display_name_no_padding:btrim 后不相等,写入被拒绝
--
-- INSERT INTO profiles (display_name) VALUES ('pending');
-- ↑ 违反 status_known_value:不在枚举白名单内Inside the snippet
Several statements share this file — INSERT / CREATE, with profiles among the objects involved.
Mechanically, the statements are built from: 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; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Using it
The profiles table is the working surface here.
Key statements
INSERT INTO profiles (display_name) VALUES ('ada');
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.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.
FAQ
- Which relations are involved here?
- `profiles`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.