Files
blog-server/internal/db/query/post_stats.sql
2026-08-19 22:05:49 +08:00

29 lines
540 B
SQL

-- name: IncrementPostStatsView :exec
WITH visitor AS (
INSERT INTO post_viewers (
post_id,
ip,
last_viewed_at
)
VALUES (
$1,
$2,
NOW()
)
ON CONFLICT (post_id, ip)
DO UPDATE
SET last_viewed_at = NOW()
WHERE post_viewers.last_viewed_at < NOW() - INTERVAL '30 minutes'
RETURNING post_id
)
INSERT INTO post_stats (
post_id,
view_count
)
SELECT
post_id,
1
FROM visitor
ON CONFLICT (post_id)
DO UPDATE
SET view_count = post_stats.view_count + 1;