memos/store/db/postgres/reaction.go

80 lines
2 KiB
Go
Raw Normal View History

2024-02-07 23:40:23 +08:00
package postgres
import (
"context"
"strings"
"github.com/usememos/memos/store"
)
2024-04-13 11:54:37 +08:00
func (d *DB) UpsertReaction(ctx context.Context, upsert *store.Reaction) (*store.Reaction, error) {
2024-02-07 23:40:23 +08:00
fields := []string{"creator_id", "content_id", "reaction_type"}
2024-10-10 21:06:32 +08:00
args := []interface{}{upsert.CreatorID, upsert.ContentID, upsert.ReactionType}
2024-02-07 23:40:23 +08:00
stmt := "INSERT INTO reaction (" + strings.Join(fields, ", ") + ") VALUES (" + placeholders(len(args)) + ") RETURNING id, created_ts"
if err := d.db.QueryRowContext(ctx, stmt, args...).Scan(
2024-04-13 11:54:37 +08:00
&upsert.ID,
2024-02-08 11:54:59 +08:00
&upsert.CreatedTs,
2024-02-07 23:40:23 +08:00
); err != nil {
return nil, err
}
2024-02-08 11:54:59 +08:00
reaction := upsert
2024-02-07 23:40:23 +08:00
return reaction, nil
}
2024-04-13 11:54:37 +08:00
func (d *DB) ListReactions(ctx context.Context, find *store.FindReaction) ([]*store.Reaction, error) {
2024-02-07 23:40:23 +08:00
where, args := []string{"1 = 1"}, []interface{}{}
if find.ID != nil {
where, args = append(where, "id = "+placeholder(len(args)+1)), append(args, *find.ID)
}
if find.CreatorID != nil {
where, args = append(where, "creator_id = "+placeholder(len(args)+1)), append(args, *find.CreatorID)
}
if find.ContentID != nil {
where, args = append(where, "content_id = "+placeholder(len(args)+1)), append(args, *find.ContentID)
}
rows, err := d.db.QueryContext(ctx, `
SELECT
id,
created_ts,
creator_id,
content_id,
reaction_type
FROM reaction
WHERE `+strings.Join(where, " AND ")+`
2024-02-08 21:20:51 +08:00
ORDER BY id ASC`,
2024-02-07 23:40:23 +08:00
args...,
)
if err != nil {
return nil, err
}
defer rows.Close()
2024-04-13 11:54:37 +08:00
list := []*store.Reaction{}
2024-02-07 23:40:23 +08:00
for rows.Next() {
2024-04-13 11:54:37 +08:00
reaction := &store.Reaction{}
2024-02-07 23:40:23 +08:00
if err := rows.Scan(
2024-04-13 11:54:37 +08:00
&reaction.ID,
2024-02-07 23:40:23 +08:00
&reaction.CreatedTs,
2024-04-13 11:54:37 +08:00
&reaction.CreatorID,
&reaction.ContentID,
2024-10-10 21:06:32 +08:00
&reaction.ReactionType,
2024-02-07 23:40:23 +08:00
); err != nil {
return nil, err
}
list = append(list, reaction)
}
if err := rows.Err(); err != nil {
return nil, err
}
return list, nil
}
func (d *DB) DeleteReaction(ctx context.Context, delete *store.DeleteReaction) error {
_, err := d.db.ExecContext(ctx, "DELETE FROM reaction WHERE id = $1", delete.ID)
return err
}