Idiomatic way of eager loading - how to populate deep nested association with database/sql and pq

648 views Asked by At

I was just wondering how to deal with eager loading queries to retrieve data with several associations, let me explain my models:

type User struct {
  Id uint
  Name string
  Username string
  Image string
}

type Post struct {
  Id unit
  Content string
  Author *User // I use user_id in author column for the posts table
  Comments []Comments
}

type Comments struct {
  Id unit
  PostId uint
  Message string
  CommentBy *User // I use user_id in comment_by column for the comments table
}

This is an example of retrieved data:

{
    "Posts": [
        {
            "Id": 1,
            "Content": "test post",
            "Author": {
                  "Id": 1,
                  "Name": "author",
                  "Username": "h3ll0",
                  "Image": "author.png"
            },
            "Comments": [
                {
                    "Id": 1,
                    "PostId": 1,
                    "Message": "good article",
                    "CommentBy": {
                        "Id": 2,
                        "Name": "second user",
                        "Username": "r3ader",
                        "Image": "reader.png"
                    }
                },
                {
                    "Id": 2,
                    "PostId": 1,
                    "Message": "bad article",
                    "CommentBy": {
                        "Id": 3,
                        "Name": "third user",
                        "Username": "thirD",
                        "Image": "third.png"
                    }
                }
            ]
        }
    ]
}

I want to retrieve the post data with all nested associations and map them to the Post struct. How would you do it with database/sql and pq (Postgres driver)?

I don't want to use any ORM at all, I only use database/SQL and SQLx.

Keep in mind that the performance is important because The posts and comments tables are big enough.

0

There are 0 answers