0

Prefacing this that im very new with Go and pgx. Is there a way to easily parse substruct values from a query?

So I do a Join query like:

rows, err := conn.Query(context.Background(),
    `SELECT 
        rdr.id AS r_Id,
        rdr.field1 AS r_Field2,
        rdr.field2 AS r_Field2,
        contact.firstname AS c_FirstName,
        contact.lastname AS c_LastName,
        contact.id AS c_Id 
    FROM rdr
    INNER JOIN contact ON rdr.contact=contact.id`)

Then my structs are

type Rdr struct {
    Id              int32     
    Field1          int32     
    Contact         Contact   
    Field2          time.Time
}

type Contact struct {
    Id        int
    FirstName string
    LastName  string
}

How can I parse the data returned in the rows into my Rdr struct. I would need to parse the correct fields into the Contact, ideally at the same time, but i dont see how to do that. I cant see how Scan would do it. We were looking at the FieldDescriptions and the Values but it gets very messy. Is there an easy/common way to do this? I imagine its a very common issue.

discodowney
  • 1,475
  • 6
  • 28
  • 58
  • You scan the nested fields in exactly the same way you scan the root fields. Have you tried it? If so, what problem did you encounter? – mkopriva May 10 '21 at 14:32
  • Id rather not use scan at all. what if i have dynamic queries and i dont know beforehand what fields are being returned, or objects for that matter – discodowney May 10 '21 at 14:35
  • 1
    I'm not sure I understand. If you don't want to scan at all, how then do you expect to get the data from the database into the struct? Are you looking for an ORM? `pgx` is not an ORM, it's a low-level driver. With `pgx` you do your own scanning, if you don't want to, then don't use `pgx`. – mkopriva May 10 '21 at 14:40
  • Hmmm... okay thanks. Im looking at GORM. our boss didnt want to use it if i could be avoided, going to find out why, but looks like we might have to. Thanks for the info – discodowney May 10 '21 at 14:50

0 Answers0