← 中文资源

简体中文版本

CHECK 约束的正则格式守护

格式规则下沉到数据库边界:CHECK 约束里用 POSIX 正则并锚定 ^ $ 做全串校验,大小写不符的运单号在写入时就被拒绝,应用与约束共用同一份规则。

阅读英文原文

实现说明

实际执行的是 INSERT / CREATE——shipments 是涉及的对象。 用到的 SQL 构件:CHECK 约束在写入时就把越界值拒之门外;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句。

常见问题

这个文件引用了哪些表?

shipments。

核心语句

CREATE TABLE shipments (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    tracking_code text NOT NULL CHECK (tracking_code ~ '^[A-Z]{3}-[0-9]{4}$'),
    weight_kg numeric(8,2) NOT NULL CHECK (weight_kg > 0)
);
INSERT INTO shipments (tracking_code, weight_kg) VALUES ('SHP-2026', 2.50);
INSERT INTO shipments (tracking_code, weight_kg) VALUES ('shp-2026', 2.50);

代码示例

-- CHECK constraints can use regex matching with ~; anchor with ^ and $ yourself or only a prefix matches
-- Shipment-code rule: three uppercase letters, a dash, four digits (SHP-2026); the constraint is the last guard before a row lands
CREATE TABLE shipments (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    tracking_code text NOT NULL CHECK (tracking_code ~ '^[A-Z]{3}-[0-9]{4}$'),
    weight_kg numeric(8,2) NOT NULL CHECK (weight_kg > 0)
);

INSERT INTO shipments (tracking_code, weight_kg) VALUES ('SHP-2026', 2.50);

-- A wrong-case write is rejected at the statement level: application and database share one rule
INSERT INTO shipments (tracking_code, weight_kg) VALUES ('shp-2026', 2.50);

-- Validate before inserting: keep this expression identical to the constraint's regex
SELECT 'SHP-2026' ~ '^[A-Z]{3}-[0-9]{4}$' AS valid_code;