0
votes

I'm trying to query a view in golang with gorm and save the result in a struct EdgeType containing NodeType. (Basically trying to implement the graphql-relay connection specification).

The view contains 4 fields:

cursor   bigint
id       bigint
text     text
user_id  bigint
type NodeType struct {
    ID     int64
    Text   string
    UserID int64
}
type EdgeType struct {
    Cursor int64
    Edge   NodeType
}

func (receiver EdgeType) TableName() string {
    return "connection_view"
}

As this alone doesn't work, so I tried to implement Scanner/Value interface.

Unfortunatelly, Scan isn't executed at all with the following call:

    connection := make([]EdgeType, 0)
    err := db.GormDB.Find(&connection).Error

This leads to my next problem: I can't debug my Scan/Value functions if they're not called. I've seen another answer pretty much describing my issue but with the advantage to be able to map the Child type to a specific geolocation type in postgres.

func (receiver *NodeType) Scan(src interface{}) error {
    // raw := src.(string)
    // fmt.Printf("raw: %s", raw)
    // maybe parse the src string and set parsed data to receiver?
    return nil
}

func (receiver NodeType) Value() (driver.Value, error) {
    // what to return for multiple fields?
    return receiver, nil
}

What can I return in my Value method to handle multiple fields at once? Or: Is that even possible/supported? Have I declared the Scan function wrongly or why isn't it called?

1
Have you tried using struct tags? i.e. Edge NodeType `gorm:"embedded"`. Read more here: gorm.io/docs/models.html#Embedded-Struct.mkopriva
OMG. Yeah works like a charm.Felix
By the way, as far as Scan/Value are concerned, those are intended to read/write single columns, i.e. the src given to Scan will always represent a single table column, and the return value from Value will always be used to assign a single column.mkopriva

1 Answers

1
votes

As mkopriva pointed out, there's a gorm:"embedded" tag.

type NodeType struct {
    ID     int64
    Text   string
    UserID int64
}

type EdgeType struct {
    Cursor int64
    Edge   NodeType `gorm:"embedded"`
}

This works without any Scan/Value functions.