From c9bb703e23a0fa95b22d1983cc589ba5b40e9225 Mon Sep 17 00:00:00 2001 From: Gabriel Saratura Date: Thu, 1 Dec 2022 12:22:51 +0100 Subject: [PATCH] Make fact object updatable in database --- pkg/factsmodel/facts.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/pkg/factsmodel/facts.go b/pkg/factsmodel/facts.go index 0703e63..d279aa2 100644 --- a/pkg/factsmodel/facts.go +++ b/pkg/factsmodel/facts.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/appuio/appuio-cloud-reporting/pkg/db" "github.com/jmoiron/sqlx" + "reflect" ) func GetByFact(ctx context.Context, tx *sqlx.Tx, fact *db.Fact) (*db.Fact, error) { @@ -31,6 +32,15 @@ func Ensure(ctx context.Context, tx *sqlx.Tx, ensureFact *db.Fact) (*db.Fact, er if err != nil { return nil, err } + } else { + ensureFact.Id = fact.Id + if !reflect.DeepEqual(fact, ensureFact) { + fmt.Printf("updating facts\n") + err = Update(tx, ensureFact) + if err != nil { + return nil, err + } + } } return fact, nil } @@ -45,6 +55,16 @@ func Create(p db.NamedPreparer, in *db.Fact) (*db.Fact, error) { return &category, err } +func Update(p db.NamedPreparer, in *db.Fact) error { + var fact db.Fact + err := db.GetNamed(p, &fact, + "UPDATE facts SET date_time_id=:date_time_id, query_id=:query_id, tenant_id=:tenant_id, category_id=:category_id, product_id=:product_id, discount_id=:discount_id, quantity=:quantity WHERE id=:id RETURNING *", in) + if err != nil { + err = fmt.Errorf("cannot update fact %v: %w", in, err) + } + return err +} + func New(dateTime *db.DateTime, query *db.Query, tenant *db.Tenant, category *db.Category, product *db.Product, discount *db.Discount, quanity float64) *db.Fact { return &db.Fact{ DateTimeId: dateTime.Id,