From 860ba6cc4af3597926aab5bddb2fb7768931537a Mon Sep 17 00:00:00 2001 From: "Erik Winter (aider)" Date: Mon, 2 Dec 2024 08:02:23 +0100 Subject: [PATCH] feat: Implement Recurrer interface methods for Postgres service --- sync/service/postgres.go | 52 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/sync/service/postgres.go b/sync/service/postgres.go index c55868b..1a7cf95 100644 --- a/sync/service/postgres.go +++ b/sync/service/postgres.go @@ -157,6 +157,58 @@ func (p *Postgres) migrate(wanted []string) error { return nil } +func (p *Postgres) RecursBefore(date time.Time) ([]item.Item, error) { + query := ` + SELECT id, kind, updated, deleted, body, recurrer, recur_next + FROM items + WHERE recur_next <= $1 AND recurrer IS NOT NULL` + + rows, err := p.db.Query(query, date) + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrPostgresFailure, err) + } + defer rows.Close() + + result := make([]item.Item, 0) + for rows.Next() { + var item item.Item + if err := rows.Scan(&item.ID, &item.Kind, &item.Updated, &item.Deleted, &item.Body, &item.Recurrer, &item.RecurNext); err != nil { + return nil, fmt.Errorf("%w: %v", ErrPostgresFailure, err) + } + result = append(result, item) + } + + return result, nil +} + +func (p *Postgres) RecursNext(id string, date time.Time) error { + var item item.Item + err := p.db.QueryRow(` + SELECT id, kind, updated, deleted, body, recurrer, recur_next + FROM items + WHERE id = $1`, id).Scan(&item.ID, &item.Kind, &item.Updated, &item.Deleted, &item.Body, &item.Recurrer, &item.RecurNext) + if err != nil { + if err == sql.ErrNoRows { + return ErrNotFound + } + return fmt.Errorf("%w: %v", ErrPostgresFailure, err) + } + + if item.Recurrer == nil { + return ErrNotARecurrer + } + + _, err = p.db.Exec(` + UPDATE items + SET recur_next = $1 + WHERE id = $2`, date, id) + if err != nil { + return fmt.Errorf("%w: %v", ErrPostgresFailure, err) + } + + return nil +} + func compareMigrations(wanted, existing []string) ([]string, error) { var needed []string if len(wanted) < len(existing) {