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.

SqlData Integrity

Code

snippet
-- 文本卫生约束:每行写入时逐行强制执行,脏数据到不了表里
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

FAQ

Which relations are involved here?
`profiles`.