如何处理用户在一段时间内可以发布的固定最大帖子数?

How to deal with fixed max number of posts a user can make within a time period?

对不起标题。

用户最多可以有 3 个活动 post,每个 post 活动时间为 48 小时。

我正在考虑将 active_post_{1/2/3}_idactive_post_{1/2/3}_expires_at 放在 users table 上,但想知道是否有更好的方法来处理这样的事情。

我将只存储 post 的时间戳,并使用中间层逻辑将活动 post 的数量限制为三个。

如果你有这样的table:

create table posts (
  id int generated always as identity,
  user_id int not null references users(id),
  created_at timestamptz not null,
  post_text text not null
);

您可以使用此查询获取活动 post 的数量,如果结果超过三个,则禁用用户创建新 post 的能力。

select count(*) 
  from posts
 where user_id = ?
   and created_at > now() - interval '48 hours';

这可能会被坚定的攻击者通过应用程序中的多个活动会话击败,但如果这是一个问题,那么我会使用相同的逻辑将可见的 posts 限制为每个用户只有三个。拉取post的列表时显示:

with rnums as (
  select user_id, created_at, post_text, 
         row_number() over (partition by user_id
                                order by created_at desc) as rn
    from posts
   where created_at > now() - interval '48 hours'
)
select user_id, created_at, post_text
  from rnums
 where rn <= 3
 order by user_id, created_at desc;

如果您想使用 PostgreSQL 来强制执行此约束,则需要将触发器加入其中。