如果表中的两个值与我计划插入的值相同,我该如何制定策略以停止插入行
在插入新行之前,我需要检查是否已经进行了具有相同时间戳和产品ID的预订。
我正在努力制定这项政策,如果有人可以提供帮助,那就太好了。
这是我表格的架构:
create table Bookings (
id bigint not null primary key,
created_at timestamp default now(),
start timestamp default now(),
name character,
user_id uuid,
notes text,
product_id bigint references Services (id),
status text not null,
owner_id uuid default uuid_generate_v4()
);
我尝试使用没有运气的触发器,并且我发挥了一个功能来检查是否有具有相同时间戳和带有时间戳的产品ID的行,并且产品与输入一样输入,而bool则与输出相同。起初,我以为可以在政策中使用它,但是我收到了一些函数不存在的错误。
create or replace function same_time_bookings(bookingtime timestamp, product int)
returns boolean
as
$$
declare
returnbool boolean;
begin
SELECT case when COUNT(*) > 0
then 0
else 1
end into returnbool from "Bookings" where
product_id = product
and extract(year from start) = extract(year from bookingtime)
and extract(month from start) = extract(month from bookingtime)
and extract(day from start) = extract(day from bookingtime)
and extract(hour from start) = extract(hour from bookingtime);
return returnbool;
end;
$$ language plpgsql;
I need to check if a booking with the same timestamp and product id has been made before inserting a new row.
I am struggling with making this policy and would be great if anybody could help.
Here is the schema for my table:
create table Bookings (
id bigint not null primary key,
created_at timestamp default now(),
start timestamp default now(),
name character,
user_id uuid,
notes text,
product_id bigint references Services (id),
status text not null,
owner_id uuid default uuid_generate_v4()
);
I have tried using triggers with no luck and I made a function to check if there is a row with the same timestamp and product id with timestamp and product is as input and a bool as output. At first I was thinking I could use this in the policy but I received some errors that the function didn't exist.
create or replace function same_time_bookings(bookingtime timestamp, product int)
returns boolean
as
$
declare
returnbool boolean;
begin
SELECT case when COUNT(*) > 0
then 0
else 1
end into returnbool from "Bookings" where
product_id = product
and extract(year from start) = extract(year from bookingtime)
and extract(month from start) = extract(month from bookingtime)
and extract(day from start) = extract(day from bookingtime)
and extract(hour from start) = extract(hour from bookingtime);
return returnbool;
end;
$ language plpgsql;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要为2列创建一个唯一的约束
product_id
和start
。这样,您可以使用相同的product_id但时间戳多个行。You need to create a unique constraint for 2 columns
product_id
andstart
. This way you can have multiple rows with the same product_id but different timestamps.Demo in DBfiddle