Skip to content

copier fails silently when source field implements valuer interface#141

Open
thetarby wants to merge 1 commit intojinzhu:masterfrom
thetarby:fix-valuer-copy
Open

copier fails silently when source field implements valuer interface#141
thetarby wants to merge 1 commit intojinzhu:masterfrom
thetarby:fix-valuer-copy

Conversation

@thetarby
Copy link

@thetarby thetarby commented Apr 30, 2022

Think that I have a CompanyEntity struct which is used in database layer and a CompanyModel in business layer with same fields. In CompanyEntity I have a struct or slice field which is saved as json text in the database by implementing valuer/scanner. With this setup copier fails to copy the field implementing valuer from entity to model because what Value() method returns is not assignable to destination field type which is a struct.

This is a test with above mentioned setup. I expect copier to pass this test but current version fails to do so. Pr includes a simple solution.

import (
	"database/sql/driver"
	"encoding/json"
	"testing"
)

type CompanyEntity struct {
	Field1  string
	Field2  string
	Persons Persons
}

type Persons []PersonEntity

func (m Persons) Value() (driver.Value, error) {
	b, err := json.Marshal(m)
	if err != nil {
		return nil, err
	}

	return b, nil
}

type CompanyModel struct {
	Field1  string
	Field2  string
	Persons []PersonModel
}

type PersonEntity struct {
	Name    string
	Surname string
}

type PersonModel struct {
	Name    string
	Surname string
}

func TestCopier(t *testing.T) {
	s := CompanyEntity{
		Field1: "f1",
		Field2: "f2",
		Persons: []PersonEntity{
			{
				Name:    "john",
				Surname: "doe",
			},
		},
	}

	d := CompanyModel{}
	if err := Copy(&d, &s); err != nil{
		t.Error(err)
	}

	if len(d.Persons) == 0 {
		t.Error("copy is not successful")
	}
}

@thetarby
Copy link
Author

thetarby commented May 5, 2022

Does anybody have any thoughts on this?

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

Successfully merging this pull request may close these issues.

1 participant