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

GODRIVER-3436 Avoid initializing null data given custom decoder #1902

Merged
merged 4 commits into from
Dec 6, 2024

Conversation

prestonvasquez
Copy link
Collaborator

GODRIVER-3436

Summary

If the value reader is null, prevent DefaultValueDecoders from initializing a pointer to the zero value.

Background & Motivation

The current behavior will lead to unexpected results:

ill instantiate a pointer field decoded from null data if the user defines a UnmarshalBSONValue. For example:

package main

import (
	"fmt"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/bsontype"
	"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)

type DBInt64 int64

type Product struct {
	TotalForSell *DBInt64 `json:"total_for_sell" bson:"total_for_sell,omitempty"`
}

func (i *DBInt64) UnmarshalBSONValue(t bsontype.Type, value []byte) error {
	return nil
}

func main() {
	idx, doc := bsoncore.AppendDocumentStart(nil)
	doc = bsoncore.AppendNullElement(doc, "total_for_sell")

	doc, err := bsoncore.AppendDocumentEnd(doc, idx)
	if err != nil {
		panic(err)
	}

	bytes := bson.Raw(doc)

	got := Product{}
	if err := bson.Unmarshal(bytes, &got); err != nil {
		panic(err)
	}

	if got.TotalForSell != nil {
		fmt.Println("null value decoded as non-nil")
	}
}

Output:

❯ go run custom_type_with_pointer.go
null value decoded as non-nil

@prestonvasquez prestonvasquez added priority-1-high High Priority PR for Review priority-2-medium Medium Priority PR for Review priority-3-low Low Priority PR for Review and removed priority-1-high High Priority PR for Review priority-2-medium Medium Priority PR for Review labels Dec 5, 2024
Copy link
Contributor

API Change Report

No changes found!

@prestonvasquez prestonvasquez added priority-1-high High Priority PR for Review and removed priority-3-low Low Priority PR for Review labels Dec 6, 2024
Copy link
Collaborator

@qingyang-hu qingyang-hu left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@prestonvasquez prestonvasquez merged commit 6c22d67 into mongodb:v1 Dec 6, 2024
31 of 34 checks passed
@prestonvasquez prestonvasquez deleted the GODRIVER-3436 branch December 6, 2024 18:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
priority-1-high High Priority PR for Review
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants