"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Efficiently Scan Nested Structs with sqlx?

How Can I Efficiently Scan Nested Structs with sqlx?

Published on 2024-11-22
Browse:282

How Can I Efficiently Scan Nested Structs with sqlx?

Scanning into Nested Structs with sqlx

Nested structs present challenges when using sqlx. However, the documentation provides a solution through the use of embedded structs.

Embedded Structs

Sqlx supports embedded structs, allowing you to assign values to fields using Go's precedence rules for embedded attributes and methods.

Code Example

Consider the following code, where Address is not an embedded struct:

type Customer struct {
       Id      int     `json:"id" db:"id"`
       Name    string  `json:"name" db:"name"`
       Address Address `json:"adress"`
}

type Address struct {
       Street string `json:"street" db:"street"`
       City   string `json:"city" db:"city"`
}

This code will result in an error when attempting to scan into a Customer struct because the Address field is not embedded and does not have its own db tag.

To resolve this, embed Address into Customer:

type Customer struct {
   Id     int    `json:"id" db:"id"`
   Name   string `json:"name" db:"name"`
   Address
}

By embedding Address, its fields (including tags) are promoted into Customer, allowing sqlx to populate them from the query result.

JSON Output

Embedding Address will flatten the JSON output, as seen below:

{
    "id": 1,
    "name": "foo",
    "street": "bar",
    "city": "baz"
}

To address this, you can remap the DB struct to your original type or scan the query result into a map.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3