doushang8846 2017-01-22 08:21
浏览 104

从golang查询Postgres复合类型

So I am using go-gorp to query postgres and I can't seem to query the composite type inside my table is giving an error. All I want is appropriately nested JSON response. My postgres schema is:

CREATE TYPE PhoneType AS ENUM ('MOBILE', 'HOME', 'WORK');

CREATE TYPE PhoneNumber AS (
  "Number" VARCHAR,
  "Type" PhoneType
);

CREATE TABLE Person (
  "Id" SERIAL PRIMARY KEY NOT NULL,
  "Name" VARCHAR NOT NULL,
  "Email" VARCHAR,
  "Number" PhoneNumber[]
);

Correspondingly in golang, I have

const (
  MOBILE PhoneType = iota
  HOME
  WORK
)

type PhoneNumber struct {
  Number string
  Type   PhoneType
}

type Person struct {
  Id          int
  Name        string
  Email       string
  PhoneNumber        // not sure how to get array of phone numbers here
}

And to query, I am using go-gorp as follows:

dbmap := &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}
var data []Person
_, err := dbmap.Select(&data, "SELECT * FROM Person")

the result I get has the format

{
  "Id":
  "Name":
  "Email"
  "Number": "{\"(..., ...)\"}"
  "Type": 0
}

what I'm expecting is:

{
  "Id":
  "Name":
  "Email":
  "PhoneNumber": [{
    "Number":
    "Type":
  }]
}

How can I change this nested composite type to the type friendly to my declaration in go?

EDIT: Looks like postres arrays and composite types become strings in go. How can I redesign the schema to achieve similar result?

  • 写回答

1条回答 默认 最新

  • dounuo1881 2017-01-22 12:55
    关注

    your type declaration is wrong, try this for example:

    type Phone struct {
       Number string
       Type   PhoneType
    }
    
    type Person struct {
      Id            int
      Name          string
      Email         string
      PhoneNumber   []Phone     
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常