Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DynamoDBAttributeValue) Integer() hides float conversion and truncation #454

Closed
amwill04 opened this issue Jul 25, 2022 · 4 comments
Closed

Comments

@amwill04
Copy link

amwill04 commented Jul 25, 2022

When converting DynamoDBAttributeValue using Integer() method it currently hides the conversion to Float64 one is passed.

This hidden functionality hides its true nature and has led to errors downstream.

We are doing this as we are having to convert from a DynamoDBAttributeValue to json and therefore could be a float or an int

Example:

package main

import (
	"fmt"

	"github.com/aws/aws-lambda-go/events"
)

func main() {
	var val interface{}
	var err error
	// We may receive a float64 or an integer
	attr := events.NewNumberAttribute("0.123344")

	val, err = attr.Integer()
	if err != nil {
		// expect an error here but Integer() will return int64(float64) truncating the decimal
		// amd hiding the error.
		// we are therefore not able to correctly cast to float64
		val, err = attr.Float()
	}

	// To JSON - We are using a map as we are not sure what the key/values will be from the dynamodb stream
	output := map[string]interface{}{
		"key": val,
	}

	b, err := json.Marshal(output)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(b))
	// Output: {"key":0}
}

It would seem more predictable behaviour for Integer() to return an error if DynamoDBAttributeValue is not of integer type.

@amwill04
Copy link
Author

I should note: we could switch to use Float() upfront but this leads to issues with large int64 values

@bmoffatt
Copy link
Collaborator

The int64 returned by Integer() can't contain the largest DynamoDB Number either :) https://stackoverflow.com/a/53056505. If giant values or extreme precision matters, you may want to consider using String(), and the possibly the math/big library, to help fully preserve values downstream.

I'm also OK with an Int64(), that preserves the parse error, being added.

@amwill04
Copy link
Author

amwill04 commented Jul 26, 2022

@bmoffatt thanks

@bmoffatt
Copy link
Collaborator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants