You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.3 KiB

4 years ago
  1. package postgres
  2. import (
  3. "context"
  4. "database/sql"
  5. "github.com/Masterminds/squirrel"
  6. "github.com/gissleh/stufflog/internal/slerrors"
  7. "github.com/gissleh/stufflog/models"
  8. "github.com/jmoiron/sqlx"
  9. )
  10. type logRepository struct {
  11. db *sqlx.DB
  12. }
  13. func (r *logRepository) Find(ctx context.Context, id string) (*models.Log, error) {
  14. res := models.Log{}
  15. err := r.db.GetContext(ctx, &res, "SELECT * FROM log WHERE log_id=$1", id)
  16. if err != nil {
  17. if err == sql.ErrNoRows {
  18. return nil, slerrors.NotFound("Log")
  19. }
  20. return nil, err
  21. }
  22. return &res, nil
  23. }
  24. func (r *logRepository) List(ctx context.Context, filter models.LogFilter) ([]*models.Log, error) {
  25. sq := squirrel.Select("log.*").From("log").PlaceholderFormat(squirrel.Dollar)
  26. sq = sq.Where(squirrel.Eq{"user_id": filter.UserID})
  27. if len(filter.IDs) > 0 {
  28. sq = sq.Where(squirrel.Eq{"task_id": filter.IDs})
  29. }
  30. if len(filter.ItemIDs) > 0 {
  31. sq = sq.Where(squirrel.Eq{"item_id": filter.ItemIDs})
  32. }
  33. if filter.MinTime != nil {
  34. sq = sq.Where(squirrel.GtOrEq{
  35. "logged_time": *filter.MinTime,
  36. })
  37. }
  38. if filter.MaxTime != nil {
  39. sq = sq.Where(squirrel.LtOrEq{
  40. "logged_time": *filter.MaxTime,
  41. })
  42. }
  43. sq = sq.OrderBy("logged_time")
  44. query, args, err := sq.ToSql()
  45. if err != nil {
  46. return nil, err
  47. }
  48. res := make([]*models.Log, 0, 8)
  49. err = r.db.SelectContext(ctx, &res, query, args...)
  50. if err != nil {
  51. if err == sql.ErrNoRows {
  52. return res, nil
  53. }
  54. return nil, err
  55. }
  56. return res, nil
  57. }
  58. func (r *logRepository) Insert(ctx context.Context, log models.Log) error {
  59. _, err := r.db.NamedExecContext(ctx, `
  60. INSERT INTO log (
  61. log_id, user_id, task_id, item_id, logged_time, description
  62. ) VALUES (
  63. :log_id, :user_id, :task_id, :item_id, :logged_time, :description
  64. )
  65. `, &log)
  66. if err != nil {
  67. return err
  68. }
  69. return nil
  70. }
  71. func (r *logRepository) Update(ctx context.Context, log models.Log) error {
  72. _, err := r.db.NamedExecContext(ctx, `
  73. UPDATE log SET
  74. logged_time=:logged_time,
  75. description=:description
  76. WHERE log_id=:log_id
  77. `, &log)
  78. if err != nil {
  79. return err
  80. }
  81. return nil
  82. }
  83. func (r *logRepository) Delete(ctx context.Context, log models.Log) error {
  84. _, err := r.db.ExecContext(ctx, `DELETE FROM log WHERE log_id=$1`, log.ID)
  85. if err != nil {
  86. if err == sql.ErrNoRows {
  87. return slerrors.NotFound("Log")
  88. }
  89. return err
  90. }
  91. return nil
  92. }