activity.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package sqlite
  2. import (
  3. "context"
  4. "strings"
  5. "github.com/pkg/errors"
  6. "google.golang.org/protobuf/encoding/protojson"
  7. storepb "github.com/usememos/memos/proto/gen/store"
  8. "github.com/usememos/memos/store"
  9. )
  10. func (d *DB) CreateActivity(ctx context.Context, create *store.Activity) (*store.Activity, error) {
  11. payloadString := "{}"
  12. if create.Payload != nil {
  13. bytes, err := protojson.Marshal(create.Payload)
  14. if err != nil {
  15. return nil, errors.Wrap(err, "failed to marshal activity payload")
  16. }
  17. payloadString = string(bytes)
  18. }
  19. fields := []string{"`creator_id`", "`type`", "`level`", "`payload`"}
  20. placeholder := []string{"?", "?", "?", "?"}
  21. args := []any{create.CreatorID, create.Type.String(), create.Level.String(), payloadString}
  22. stmt := "INSERT INTO activity (" + strings.Join(fields, ", ") + ") VALUES (" + strings.Join(placeholder, ", ") + ") RETURNING `id`, `created_ts`"
  23. if err := d.db.QueryRowContext(ctx, stmt, args...).Scan(
  24. &create.ID,
  25. &create.CreatedTs,
  26. ); err != nil {
  27. return nil, err
  28. }
  29. return create, nil
  30. }
  31. func (d *DB) ListActivities(ctx context.Context, find *store.FindActivity) ([]*store.Activity, error) {
  32. where, args := []string{"1 = 1"}, []any{}
  33. if find.ID != nil {
  34. where, args = append(where, "`id` = ?"), append(args, *find.ID)
  35. }
  36. if find.Type != nil {
  37. where, args = append(where, "`type` = ?"), append(args, find.Type.String())
  38. }
  39. query := "SELECT `id`, `creator_id`, `type`, `level`, `payload`, `created_ts` FROM `activity` WHERE " + strings.Join(where, " AND ") + " ORDER BY `created_ts` DESC"
  40. rows, err := d.db.QueryContext(ctx, query, args...)
  41. if err != nil {
  42. return nil, err
  43. }
  44. defer rows.Close()
  45. list := []*store.Activity{}
  46. for rows.Next() {
  47. activity := &store.Activity{}
  48. var payloadBytes []byte
  49. if err := rows.Scan(
  50. &activity.ID,
  51. &activity.CreatorID,
  52. &activity.Type,
  53. &activity.Level,
  54. &payloadBytes,
  55. &activity.CreatedTs,
  56. ); err != nil {
  57. return nil, err
  58. }
  59. payload := &storepb.ActivityPayload{}
  60. if err := protojsonUnmarshaler.Unmarshal(payloadBytes, payload); err != nil {
  61. return nil, err
  62. }
  63. activity.Payload = payload
  64. list = append(list, activity)
  65. }
  66. if err := rows.Err(); err != nil {
  67. return nil, err
  68. }
  69. return list, nil
  70. }