activity.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package sqlite
  2. import (
  3. "context"
  4. "strings"
  5. "github.com/usememos/memos/store"
  6. )
  7. func (d *DB) CreateActivity(ctx context.Context, create *store.Activity) (*store.Activity, error) {
  8. fields := []string{"`creator_id`", "`type`", "`level`", "`payload`"}
  9. placeholder := []string{"?", "?", "?", "?"}
  10. args := []any{create.CreatorID, create.Type, create.Level, create.Payload}
  11. if create.ID != 0 {
  12. fields = append(fields, "`id`")
  13. placeholder = append(placeholder, "?")
  14. args = append(args, create.ID)
  15. }
  16. if create.CreatedTs != 0 {
  17. fields = append(fields, "`created_ts`")
  18. placeholder = append(placeholder, "?")
  19. args = append(args, create.CreatedTs)
  20. }
  21. stmt := "INSERT INTO activity (" + strings.Join(fields, ", ") + ") VALUES (" + strings.Join(placeholder, ", ") + ") RETURNING `id`, `created_ts`"
  22. if err := d.db.QueryRowContext(ctx, stmt, args...).Scan(
  23. &create.ID,
  24. &create.CreatedTs,
  25. ); err != nil {
  26. return nil, err
  27. }
  28. return create, nil
  29. }
  30. func (d *DB) ListActivity(ctx context.Context, find *store.FindActivity) ([]*store.Activity, error) {
  31. where, args := []string{"1 = 1"}, []any{}
  32. if find.ID != nil {
  33. where, args = append(where, "`id` = ?"), append(args, *find.ID)
  34. }
  35. query := "SELECT `id`, `creator_id`, `type`, `level`, `payload`, `created_ts` FROM `activity` WHERE " + strings.Join(where, " AND ")
  36. rows, err := d.db.QueryContext(ctx, query, args...)
  37. if err != nil {
  38. return nil, err
  39. }
  40. defer rows.Close()
  41. list := []*store.Activity{}
  42. for rows.Next() {
  43. activity := &store.Activity{}
  44. if err := rows.Scan(
  45. &activity.ID,
  46. &activity.CreatorID,
  47. &activity.Type,
  48. &activity.Level,
  49. &activity.Payload,
  50. &activity.CreatedTs,
  51. ); err != nil {
  52. return nil, err
  53. }
  54. list = append(list, activity)
  55. }
  56. if err := rows.Err(); err != nil {
  57. return nil, err
  58. }
  59. return list, nil
  60. }