Hi, I’m Dung Huynh Duc . Nice to meet you.

About Me

With over a decade of experience under my belt as a full-stack developer, I've had the opportunity to spearhead project teams at tech startups in Vietnam, Thailand, Japan and Singapore. Additionally, I have worked as a freelance engineer for various companies based in Asia Pacific, Europe, and North America.

Presently, I serve the role of a Senior Full Stack Software Engineer at ACX. I am consistently committed to exploring and acquiring knowledge on emerging and popular technologies.

go
sqlx

#TIL 20 - How to fix unsupported Scan, storing driver.Value type []uint8 into type

blog_hero_#TIL 20 - How to fix unsupported Scan, storing driver.Value type []uint8 into type

What

Recently, I have run into this issue with mapping database fields with a struct.

unsupported Scan, storing driver.Value type []uint8 into type YOUR_STRUCT


How

At first, I would suggest checking the document about it https://jmoiron.github.io/sqlx/#advancedScanning

then write your custom scan as below. Thanks for a comment on the open Github issue on sqlx repository. I could manage to make it work.

package models

import (
	"encoding/json"
)

type Accreditor struct {
	ID   int32  `json:"id" db:"id"`
	Name string `json:"name" db:"name"`
}

type Registries []Registry
type AccreditorRegistries struct {
	Registries Registries `json:"registries" db:"registries,omitempty"`
	Accreditor
}

// advance scan for custom type, refer https://github.com/jmoiron/sqlx/issues/578#issuecomment-562401476
func parseJSONToModel(src interface{}, dest interface{}) error {
	var data []byte

	if b, ok := src.([]byte); ok {
		data = b
	} else if s, ok := src.(string); ok {
		data = []byte(s)
	} else if src == nil {
		return nil
	}

	return json.Unmarshal(data, dest)
}

func (r *Registries) Scan(src interface{}) error {
	return parseJSONToModel(src, r)
}