Files
jules/database/postgres/actions.go
T
2026-06-06 18:52:20 +03:00

50 lines
1.1 KiB
Go

package postgres
import (
"context"
"database/sql"
"github.com/google/uuid"
"m8sh.su/d/jules/database"
)
type Actions struct {
conn *sql.DB
}
func (a *Actions) Log(ctx context.Context, userID uuid.UUID, typ, content string) error {
_, err := a.conn.ExecContext(ctx, `
INSERT INTO actions (user_id, type, content)
VALUES ($1, $2, $3)
`, userID, typ, content)
return err
}
func (a *Actions) Recent(ctx context.Context, userID uuid.UUID, limit int) ([]database.Action, error) {
rows, err := a.conn.QueryContext(ctx, `
WITH deleted AS (
DELETE FROM actions
WHERE user_id = $1 AND executed_at < NOW() - INTERVAL '3 days'
)
SELECT user_id, executed_at, type, content
FROM actions
WHERE user_id = $1
ORDER BY executed_at DESC
LIMIT $2
`, userID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var actions []database.Action
for rows.Next() {
var action database.Action
if err = rows.Scan(&action.UserID, &action.ExecutedAt, &action.Type, &action.Content); err != nil {
return nil, err
}
actions = append(actions, action)
}
return actions, rows.Err()
}