From 8d6f16ef479e6b661214c4d93cf30cdb6cbee138 Mon Sep 17 00:00:00 2001 From: Robin Tang Date: Sun, 15 Dec 2024 22:23:57 -0800 Subject: [PATCH] String converters. --- lib/typing/converters/converters.go | 33 +++++++++++++++++++++++++++++ lib/typing/values/string.go | 19 +++++++++++------ 2 files changed, 45 insertions(+), 7 deletions(-) create mode 100644 lib/typing/converters/converters.go diff --git a/lib/typing/converters/converters.go b/lib/typing/converters/converters.go new file mode 100644 index 000000000..a01558b73 --- /dev/null +++ b/lib/typing/converters/converters.go @@ -0,0 +1,33 @@ +package converters + +import ( + "fmt" + + "github.com/artie-labs/transfer/lib/typing" + + "github.com/artie-labs/transfer/lib/typing/ext" +) + +type StringConverter interface { + Convert(value any) (string, error) +} + +func GetStringConverter(kd typing.KindDetails) (StringConverter, error) { + switch kd.Kind { + case typing.Date.Kind: + return DateStringConverter{}, nil + } + + return nil, nil +} + +type DateStringConverter struct{} + +func (DateStringConverter) Convert(value any) (string, error) { + _time, err := ext.ParseDateFromAny(value) + if err != nil { + return "", fmt.Errorf("failed to cast colVal as date, colVal: '%v', err: %w", value, err) + } + + return _time.Format(ext.PostgresDateFormat), nil +} diff --git a/lib/typing/values/string.go b/lib/typing/values/string.go index 544be3a9e..472371ac3 100644 --- a/lib/typing/values/string.go +++ b/lib/typing/values/string.go @@ -8,6 +8,8 @@ import ( "strings" "time" + "github.com/artie-labs/transfer/lib/typing/converters" + "github.com/artie-labs/transfer/lib/config/constants" "github.com/artie-labs/transfer/lib/stringutil" "github.com/artie-labs/transfer/lib/typing" @@ -36,14 +38,17 @@ func ToString(colVal any, colKind typing.KindDetails) (string, error) { return "", fmt.Errorf("colVal is nil") } - switch colKind.Kind { - case typing.Date.Kind: - _time, err := ext.ParseDateFromAny(colVal) - if err != nil { - return "", fmt.Errorf("failed to cast colVal as date, colVal: '%v', err: %w", colVal, err) - } + sv, err := converters.GetStringConverter(colKind) + if err != nil { + return "", fmt.Errorf("failed to get string converter: %w", err) + } + + // Prioritize converters + if sv != nil { + return sv.Convert(colVal) + } - return _time.Format(ext.PostgresDateFormat), nil + switch colKind.Kind { case typing.Time.Kind: _time, err := ext.ParseTimeFromAny(colVal) if err != nil {