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

visitField does not map custom types to underlying db types #803

Open
antonydenyer opened this issue Mar 16, 2023 · 0 comments
Open

visitField does not map custom types to underlying db types #803

antonydenyer opened this issue Mar 16, 2023 · 0 comments

Comments

@antonydenyer
Copy link

If you have a model with custom type and you create the table using NewCreateTable().Model() the type created in the db will be for type of the property rather than the underlying type that is produced.

e.g

type Hash struct {
	common.Hash
}

var _ driver.Valuer = (*Hash)(nil)

func (hash Hash) Value() (driver.Value, error) {
	return hash.Hash.ToHexString(), nil
}

var _ sql.Scanner = (*Hash)(nil)

func (hash *Hash) Scan(src interface{}) (err error) {
	switch src := src.(type) {
	case string:
		hash.Hash = common.HexStringToHash(src)
		return nil
	default:
		return fmt.Errorf("unsupported data type: %T", src)
	}
}

And when I do the following:

type MyModel struct {
  ID   uint64    `bun:",pk,autoincrement" json:"-"`
  Hash app.Hash  `json:"hash"`
}

_, err := db.NewCreateTable().
		Model((*MyModel)(nil)).
		Exec(ctx)

it will create the column with the type for a struct. This is fine when you're using sqllite as the underlying type is a string, but when you switch over to postgres the underlying type is jsonb. Which leads to a serialisation failure.

Currently (as best as I can tell) the only option is to use annotations of the model to specify the db type.

Would it be possible to extend the custom types to be able support something like:

func (hash Hash) SqlType() (driver.Type, error) {
	return sqltype.VarChar, nil
}

or perhaps to be able to register a specific mapping for migrations?

db.Dialect().AddSqlType(&MyModel{},  sqltype.VarChar)

Happy to take a stab at implementing. thoughts?

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

1 participant