douhanxujiuji6098 2019-01-04 07:51
浏览 124

sqlx将postgres数组扫描到结构中

I'm trying to create a basic commenting api in go. I can't seem to figure out how to scan postgresql arrays into an array of structs within a struct. I think I could probably have Thread.Posts type be jsonb but that seems inelegant since I would have to unmarshall it I think.

sql: Scan error on column index 3, name "posts": unsupported Scan, storing driver.Value type []uint8 into type *[]models.Post

var threadSchema = `
CREATE TABLE IF NOT EXISTS thread (
  id         SERIAL PRIMARY KEY,
  name       VARCHAR(100) NOT NULL,
  profile_id INTEGER REFERENCES profile (id)
)`

var postSchema = `
CREATE TABLE IF NOT EXISTS post (
  id         SERIAL PRIMARY KEY,
  comment    TEXT,
  profile_id INTEGER REFERENCES profile (id),
  thread_id  INTEGER REFERENCES thread (id)
)`

type Post struct {
    Id        int    `db:"id" json:"id"`
    Comment   string `db:"comment" json:"comment" binding:"required" form:"comment"`
    ProfileId int   `db:"profile_id" json:"profile_id" binding:"required" form:"profile_id"`
    ThreadId  int    `db:"thread_id" json:"thread_id" binding:"required" form:"thread_id"`
}

type Thread struct {
    Id        int    `db:"id" json:"id"`
    Name      string `db:"name" json:"name" binding:"required" form:"name"`
    ProfileId int    `db:"profile_id" json:"profile_id" binding:"required" form:"profile_id"`
    Posts     []Post `db:"posts" json:"posts" form:"posts"`
}

func GetThreads(db *sqlx.DB, c *gin.Context) {
    threads := []Thread{}
    err := db.Select(&threads, `
    SELECT thread.id,thread.name,thread.profile_id,array_agg(post.id) AS posts
    FROM thread
    INNER JOIN post ON thread.id = post.thread_id
    GROUP BY thread.id;
  `)
    if err != nil {
        log.Fatal(err)
    }
    c.JSON(http.StatusOK, gin.H{"data": threads})
}
  • 写回答

1条回答 默认 最新

  • dtol41388 2019-01-04 08:39
    关注

    First off, you can't do this with sqlx, whether or not you're using Postgres arrays.

    Second, your SQL query is simply aggregating Post IDs, not the content of the posts, so there's no way to get the data you want (using Go or otherwise).

    So here's what you can do:

    1. Use an anonymous embedded struct, capture all of the Post content in your SQL query, and then merge your duplicated Threads.

      type Post struct {
          Id        int    `db:"id" json:"id"`
          Comment   string `db:"comment" json:"comment" binding:"required" form:"comment"`
          ProfileId int   `db:"profile_id" json:"profile_id" binding:"required" form:"profile_id"`
          ThreadId  int    `db:"thread_id" json:"thread_id" binding:"required" form:"thread_id"`
      }
      
      type ThreadDb struct {
          Id        int    `db:"id" json:"id"`
          Name      string `db:"name" json:"name" binding:"required" form:"name"`
          ProfileId int    `db:"profile_id" json:"profile_id" binding:"required" form:"profile_id"`
          Post
      }
      
      type Thread struct {
          Id        int    `db:"id" json:"id"`
          Name      string `db:"name" json:"name" binding:"required" form:"name"`
          ProfileId int    `db:"profile_id" json:"profile_id" binding:"required" form:"profile_id"`
          Posts     []Post `db:"posts" json:"posts" form:"posts"`
      }
      
      
      func GetThreads(db *sqlx.DB, c *gin.Context) {
          threads := []ThreadDb{}
          err := db.Select(&threads, `
          SELECT thread.id,thread.name,thread.profile_id,post.id,post.comment,post.profile_id,post.thread_id
          FROM thread
          INNER JOIN post ON thread.id = post.thread_id
          GROUP BY post.id;
        `)
      
          thread_map := make(map[string]Thread)
      
          for i, thread := range threads {
              if _, ok := thread_map[thread.Id]; ok {
                  thread_map[thread.Id].Posts = append(thread_map[thread.Id].Posts, thread.Post)
              } else {
                  thread_map[thread.Id] = Thread{thread.Id, thread.Name, thread.ProfileId, []Post{thread.Post}}
              }
          }
      
          var threadSlice []string
      
          for k := range thread_map {
              threadSlice = append(threadSlice, k)
          }
      
          if err != nil {
              log.Fatal(err)
          }
          c.JSON(http.StatusOK, gin.H{"data": threadSlice})
      }
      
    2. Use GROUP_CONCAT or similar. I wouldn't recommend unless you plan on having a maximum of about 100 posts per thread.
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染