我真的需要检查另一个表中的记录是否真的存在,如果 PostgreSQL 无论如何都会检查那个外键约束吗?
parent
通常,您在创建记录之前检查是否存在现有child
记录。但这是另一个要执行的查询。所以我认为最好只处理 PostgreSQL 错误并检查它是否是关于parent
记录不存在(违反外键约束)。
是更好地利用数据库服务器功能,还是没有为此目的?您是否建议在创建新记录之前进行所有完整性检查?
CREATE TABLE "public"."categories" (
"id" serial,
"name" varchar(100),
CONSTRAINT "categories__id_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "public"."products" (
"id" serial,
"category_id" integer NOT NULL,
"name" varchar(100),
CONSTRAINT "products__id_pkey" PRIMARY KEY ("id"),
CONSTRAINT "products__category_id_fkey" FOREIGN KEY ("category_id")
REFERENCES "categories" ("id") ON DELETE CASCADE
);
一个伪代码:
if (query("SELECT * FROM categories WHERE id = 123"))
query("INSERT INTO products (category_id, name) VALUES (123, 'Something')")
else
throw Error("Parent record does not exist")
try
query("INSERT INTO products (category_id, name) VALUES (123, 'Something')")
catch (Exception e)
if (e.code == '23503')
throw Error("Parent record does not exist")
else
throw Error("Some other error occured")
PostgreSQL 中的错误代码23503
是:
ERROR: insert or update on table "products" violates foreign key constraint "products__category_id_fkey"