From 685a05f1cd6257926e581f0df9cefad3fcbefdbe Mon Sep 17 00:00:00 2001 From: Vincent Bernardoff Date: Fri, 14 Jun 2024 18:41:06 +0200 Subject: [PATCH] add Scan/Value for SQL conversion --- duration.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/duration.go b/duration.go index 9a0f7a4..26ee3f1 100644 --- a/duration.go +++ b/duration.go @@ -1,6 +1,7 @@ package duration import ( + "database/sql/driver" "encoding/json" "errors" "fmt" @@ -309,3 +310,27 @@ func (duration *Duration) UnmarshalJSON(source []byte) error { *duration = *parsed return nil } + +func (d *Duration) Scan(x interface{}) error { + switch v := x.(type) { + case []uint8: + parsed, err := Parse(string(v)) + if err != nil { + return fmt.Errorf("failed to parse duration: %w", err) + } + d = parsed + case string: + parsed, err := Parse(v) + if err != nil { + return fmt.Errorf("failed to parse duration: %w", err) + } + d = parsed + default: + return fmt.Errorf("value must be a string") + } + return nil +} + +func (d Duration) Value() (driver.Value, error) { + return d.String(), nil +}